如何通过cloudformation运行或测试我的Lambda函数

时间:2019-06-19 13:10:52

标签: amazon-cloudformation

我创建了lambda函数并通过cloudformation进行了部署。 我希望在创建cloudformation堆栈后自动执行lambda函数。

2 个答案:

答案 0 :(得分:0)


AWSTemplateFormatVersion: "2010-09-09"
Resources:
  Roleforlambda:
    Type: "AWS::IAM::Role"
    Properties: 
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - 
            Effect: "Allow"
            Principal: 
              Service: 
                - "lambda.amazonaws.com"
            Action: 
              - "sts:AssumeRole"
  RolePolicies: 
    Type: "AWS::IAM::Policy"
    Properties: 
      PolicyName: "root"
      PolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - 
            Effect: "Allow"
            Action: "*"
            Resource: "*"
      Roles: 
        - 
          Ref: "Roleforlambda"
  lambdaFunction1:   
    Type: AWS::Lambda::Function
    Description: For getting Instance ID
    Properties:
      Handler: index.lambda_handler
      Role: !GetAtt Roleforlambda.Arn
      Code: 
        ZipFile: !Sub |
          import json
          import boto3  
          import cfnresponse

          def create_key_pair(instanceid):
            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'])

          def lambda_handler(event, context):

            try:
              if event['RequestType'] == 'Delete':
                print("delete called")
                response = 'SUCCESS'
            else:
              print("create called")
              create_key_pair(instanceid)
              response = 'SUCCESS'
            cfnresponse.send(event, context, cfnresponse.SUCCESS)    
            return response
      Runtime: python3.7
      Timeout: 200

  MyFrontEndTest: 
    Type: "Custom::Lambdatrigger"
    Properties: 
      ServiceToken: !GetAtt lambdaFunction1.Arn
      key: return x
Outputs: 
  CustomResourceAttribute1: 
    Value: !Ref MyFrontEndTest

答案 1 :(得分:0)

我希望触发此lambda并获取instane-id的值作为输出