AWS lambda:没有名为'cfnresponse'的模块

问题描述 投票:4回答:2

我已经部署了一个包含以下内容的AWS Lambda:

import json
import boto3
import cfnresponse
import urllib.request
from botocore.exceptions import ClientError

def lambda_handler(event, context):
...
cfnresponse.send(event, context, status, responseData, "CustomResourcePhysicalID")

我试图在我的cloudformations中获得cfnresponse的值:

Resources:
  API:
    Type: Custom::API
    Version: '1.0'
    Properties:
      ServiceToken: arn:aws:lambda:eu-west-1:1234567891011:function:getCountry
Outputs:
  Status:
    Value:
       !GetAtt API.Data

现在cfn卡住了,我得到了错误:

Unable to import module 'lambda_function': No module named 'cfnresponse' 

我在做什么错?当我检查docs时,似乎是这样做的方法。

amazon-web-services aws-lambda amazon-cloudformation
2个回答
5
投票
Cfnresponse仅在python 2.7中默认在lambda中可用。可能您正在使用3.6。

1
投票
您是否在ZipFile中指定了函数的源代码?如果您指定一个实际的zip文件,则不会包含该模块。

当您使用

ZipFile属性指定您的函数的源代码且该函数与AWS CloudFormation自定义资源进行交互时,您可以加载cfn-response模块以将响应发送到那些资源。该模块包含send方法,该方法通过Amazon S3预签名URL(ResponseURL)将响应对象发送到自定义资源。

如果您需要使用实际的zip文件,或者由于其他任何原因而无法使用zip文件,则可以自己添加该模块。您提供的链接中提供了其源代码。对于Python 3,它是:

# Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. # This file is licensed to you under the AWS Customer Agreement (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at http://aws.amazon.com/agreement/ . # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. # See the License for the specific language governing permissions and limitations under the License. from botocore.vendored import requests import json SUCCESS = "SUCCESS" FAILED = "FAILED" def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False): responseUrl = event['ResponseURL'] print(responseUrl) responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name responseBody['StackId'] = event['StackId'] responseBody['RequestId'] = event['RequestId'] responseBody['LogicalResourceId'] = event['LogicalResourceId'] responseBody['NoEcho'] = noEcho responseBody['Data'] = responseData json_responseBody = json.dumps(responseBody) print("Response body:\n" + json_responseBody) headers = { 'content-type' : '', 'content-length' : str(len(json_responseBody)) } try: response = requests.put(responseUrl, data=json_responseBody, headers=headers) print("Status code: " + response.reason) except Exception as e: print("send(..) failed executing requests.put(..): " + str(e))

© www.soinside.com 2019 - 2024. All rights reserved.