CloudFormation - access parameter from lambda code

I have a template CloudFormationthat looks like this:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template will deploy stuff",
    "Parameters":{
    "myParamToLambdaFunction" : {
        "Description" : "Please enter the the value",
        "Type" : "String",
        "ConstraintDescription" : "must have some value."
    }
},
"Resources": {
    "SecGrpValidatorFromCFTemplate": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "FunctionName": "mylambdafunctionname",
            "Handler": "myfile.lambda_handler",
            "Role": {
                "Fn::GetAtt": ["somerole", "Arn"]
            },
            "Timeout": "30",
            "Runtime": "python2.7",
            "Code": {
                "S3Bucket":"mybucket",
                "S3Key":"mylambdafunction.zip"
            }
        }
    }
}

I need to pass the value of myParamToLambdaFunctionthe lambda function.

Is there any way to do this?

+3
source share
6 answers

From November 18, 2016 , AWS Lambda now supports environment variables that CloudFormation supports using the property Environmenton AWS::Lambda::Function.

Add the property Environmentto your resource as follows:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template will deploy stuff",
    "Parameters":{
    "myParamToLambdaFunction" : {
        "Description" : "Please enter the the value",
        "Type" : "String",
        "ConstraintDescription" : "must have some value."
    }
},
"Resources": {
    "SecGrpValidatorFromCFTemplate": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "FunctionName": "mylambdafunctionname",
            "Handler": "myfile.lambda_handler",
            "Role": {
                "Fn::GetAtt": ["somerole", "Arn"]
            },
            "Timeout": "30",
            "Runtime": "python2.7",
            "Code": {
                "S3Bucket":"mybucket",
                "S3Key":"mylambdafunction.zip"
            },
            "Environment": {
                "Variables": {
                    "myParam": {
                        "Ref": "myParamToLambdaFunction"
                    }
                }
            }
        }
    }
}

Lambda (, os.environ['myParam'] Python).

+2

, , zip .

, , :

"CopyLogsStreamToFirehose": {
  "Type": "AWS::Lambda::Function",
  "Properties": {
    "Code": {
      "ZipFile": {
        "Fn::Join": [
          "",
          [
            "import base64\n",
            "import boto3\n",
            "def on_new_kinesis_data(event, context):\n",
            "   client = boto3.client('firehose')\n",
            "   records = [ {'Data': base64.b64decode(r['kinesis']['data']) + '\\n' } for r in event['Records']]\n",
            "   client.put_record_batch(DeliveryStreamName='",
            {
              "Ref": "LogsDeliveryStream"
            },
            "', Records=records)\n",
            "   print 'Successfully processed {} records.'.format(len(event['Records']))\n"
          ]
        ]
      }
    },
    "Description": "Kinesis Stream to Firehose Stream",
    "Handler": "index.on_new_kinesis_data",
    "Role": {
      "Fn::GetAtt": [
        "CopyLogsStreamToFirehoseRole",
        "Arn"
      ]
    },
    "Runtime": "python2.7",
    "Timeout": 5
  }
0

Lambda . . .

1 - - . , , var stackName = context.functionName.split('-')[0];, . /. , , CloudFormation . , 2 .

2 - DynamoDB ( S3 ) . , , .

0

, - - .

, , , , . AWS::AutoScaling::LifecycleHook NotificationMetadata, , Route53ZoneId:

"MyLifecycleHook": {
  "Type": "AWS::AutoScaling::LifecycleHook",
  "Properties": {
    "AutoScalingGroupName": { "Ref": "MyASG" },
    "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING",
    "NotificationMetadata": { "Fn::Join": [ "", [
      "{",
      "  \"Route53ZoneId\": \"YOUR_ROUTE53_ZONE_IDENTIFIER_HERE\"",
      "}"
    ] ] },
    "NotificationTargetARN": { "Ref": "MyTopic" },
    "RoleARN": { "Fn::GetAtt": [ "MyLifecycleHookRole", "Arn" ] }
  }
}

Then in your lambda handler, assuming you are writing it in Python, you can access the variables in this dictionary, for example:

def handler(event, context):
    message = json.loads(event[u'Records'][0][u'Sns'][u'Message'])
    metadata = json.loads(message['NotificationMetadata'])

    logger.info("Route53 Zone Identifier {0}".format(metadata['Route53ZoneId']))
0
source

If your Lambda function is behind the API loop, you can use RequestTemplates to modify the request before it reaches that function. The configuration below will send the original request body along with a parameter defined as YourCloudformationParameter:

"RequestTemplates": {
  "application/json": {
    "Fn::Join": [
      "",
      [
        "{",
          "\"body\": $input.json('$'),",
          "\"env\": {",
            "\"yourCloudformationParameter\": \"", { "Ref": "YourCloudformationParameter" }, "\"",
          "}",
        "}"
      ]
    ]
  }
},
0
source

Source: https://habr.com/ru/post/1649823/


All Articles