4

My Lambda code is stored in a S3 bucket. I use CloudFormation to deploy in the child account.

Lambda code snippet:

def lambda_handler(event,context):
  ids = ["${id}"]

The CloudFormation uses the parameters to take in the id as:

Parameters:

    id:  
      Type: String
      Description: Name of id. 
      Default: abc

However the id doesn't get populated in the lambda because the code is stored in the S3 bucket.

How to go about it?

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
RMish
  • 131
  • 2
  • 11
  • Could you please clarify your "end-to-end" requirements? For example, are you saying that you have a parameter in a CloudFormation template and you wish to make that value available to all future invocations of an AWS Lambda function that is created in the same template? – John Rotenstein Jul 29 '19 at 22:30

2 Answers2

17

From your description, it seems your requirement is:

  • A CloudFormation template takes an input parameter
  • You wish to make the value of that input parameter available to all invocations of an AWS Lambda function that is defined in the same template

You could achieve this by passing the parameter to the Lambda function via an Environment Variable.

When defining the Lambda function in the CloudFormation template, environment variables can be provided:

Type: AWS::Lambda::Function
Properties: 
  Code: 
    Code
  Environment:
    Variables:
      id:
        Ref: PARAMETER-NAME
...

In this case, the value of the variable is coming from a parameter.

Within your Lambda code, you would then access the environment variable. Here's a Python example:

import os

def lambda_handler(event, context):
    print("environment variable: " + os.environ['id'])

References:

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
2

Another approach is storing parameters in parameter store of system manager, which can be managed in cloudformation script as well.

Kane
  • 8,035
  • 7
  • 46
  • 75