0

我尝试使用 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 都很陌生。我无法弄清楚其中缺少什么?

谢谢你

4

1 回答 1

0

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

要正常工作,在您的 lambda 函数中,您需要将 SUCCESS 或 FAILED 状态返回给 Cloudformation,并在 Data 字段中返回您的“键”,如下所示:

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

于 2020-08-18T10:29:53.447 回答