AWS CustomeResource停留在更新中

问题描述

我尝试使用lambda函数从SSM中获取一些值,并在通过UserData创建实例时通过EC2将其提供给它。我停留在CREATE_IN_PROGRESS阶段的过程中。 Lambda函数已创建,并返回当我通过亚马逊控制台运行测试但customeresource卡住时想要的值。

    Type: AWS::Lambda::Function
    Properties:
      FunctionName: "GetKeyFunction"
      Handler: "index.handler"
      Runtime: "python3.6"
      Timeout: 5
      Role: !GetAtt LamdaExecutionRole.Arn
      Code:
        ZipFile: |
          import boto3
          
          def handler(event,context):
            ssm = boto3.client('ssm')
            response = ssm.get_parameter(Name='private_key',WithDecryption=True)
            key = response['Parameter']['Value']
            return key
    
  KeyCustomeResource:
    Type: Custom::LamdaInvoker
    DependsOn: LambdaFunction
    Properties:
      Servicetoken: !GetAtt LamdaFunction.Arn

但是KeyCustomeResource停留在CREATE_IN_PROGRESS。我对python和AWS都很陌生。我无法弄清楚其中缺少什么?

谢谢

解决方法

您的自定义资源被卡住了,因为Cloudformation不知道它是否已成功部署。最终它将超时,您将能够手动将其删除。

要正常工作,在lambda函数中,您需要将“成功”或“失败”状态返回给Cloudformation,并在“数据”字段中返回“键”,如下所示:

response_data = {
    'Status': 'SUCCESS','StackId': event['StackId'],'RequestId': event['RequestId'],'LogicalResourceId': event['LogicalResourceId'],'PhysicalResourceId': str(uuid.uuid4()) if event['RequestType'] == 'Create' else event['PhysicalResourceId'],'Data': {
        'Key': response['Parameter']['Value']
    }
}

return response_data

类似地,如果lambda失败或出现异常,则需要发送Status:FAILED和['Data'] ['Reason'],以帮助Cloudformation回滚或顺利删除

您可以使用Cloudformation GetAtt来访问模板中的“键”,如下所示:PrivateKey: !GetAtt KeyCustomeResource.Key