AWS CloudFormation自定义资源不起作用

时间:2019-06-30 06:38:30

标签: amazon-web-services aws-lambda amazon-cloudformation

我已经创建了一个自定义资源来触发AWS Lambda函数并获取实例ID作为输出。自定义资源未在CloudFormation中创建。

     Code: 
        ZipFile: !Sub |
          import json
          import boto3  
          import os

          def lambda_handler(event, context):
            ec2 = boto3.client('ec2', 'us-east-1')
            response = ec2.describe_instances()
            for reservation_data in response['Reservations']:
              for instance_data in reservation_data['Instances']:
                  for tags_data in instance_data['Tags']:
                    print(instance_data['InstanceId'])

      Runtime: python3.7
      Timeout: 200

  MyFrontEndTest: 
    Type: Custom::lambdatrigger
    Properties: 
      ServiceToken: !GetAtt lambdaFunction3.Arn
      ActionType: MyFrontEndTest
Outputs:
  Message:
    Description: Gets the instance id 
    Value: !GetAtt 'MyFrontEndTest'

1 个答案:

答案 0 :(得分:1)

Amazon CloudFormation自定义资源需要将其完成信号发回CloudFormation ,而不是简单地返回值。

这可以通过cfn-response Module完成,例如:

ZipFile: |
  import json
  import cfnresponse
  def handler(event, context):
    responseValue = int(event['ResourceProperties']['Input']) * 5
    responseData = {}
    responseData['Data'] = responseValue
    cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")

如果CloudFormation没有收到信号,则堆栈最终将超时并且资源将回滚。

此外,如果您希望查看与自定义资源相关的日志信息,则可能需要分配一个角色,该角色可以输出到CloudWatch Logs 。例如,默认的AWSLambdaBasicExecutionRole包括:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}