0
votes

I am learning aws SAM Cli. I created a project for a lambda function. I want to be able to pass a parameter to this cloudformation template that my python code can read and use when the lambda function executes. how/where do I indicate this in my cloudformation template file below. such that, either i can specify a default value for that parameter or override it when i create the stack from my template.

template.yaml -

AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda SAM Template
Globals:
  Function:
    Timeout: 60

Resources:
  mysamplefunction:
    Properties:
      CodeUri: s3://some-bucket/qhfqep238974384y
      Description: some app
      FunctionName: mysamplefunction
      Handler: main.lambda_handler
      Role: arn:aws:iam::0949928960903:role/LambdaRole
      Runtime: python3.7
    Type: AWS::Serverless::Function
...

main.py


def lambda_handler(event, context):
    print('parameter passed to cloud formation template');
   
1

1 Answers

1
votes

You add a top level parameters section to your template, with a structure like the below example.

Parameters: 
  InstanceTypeParameter: 
    Type: String
    Default: t2.micro
    AllowedValues: 
      - t2.micro
      - m1.small
      - m1.large
    Description: Enter t2.micro, m1.small, or m1.large. Default is t2.micro.

You can then reference these in your template using the Ref intrinsic function such as the example below.

Ec2Instance:
  Type: AWS::EC2::Instance
  Properties:
    InstanceType:
      Ref: InstanceTypeParameter
    ImageId: ami-0ff8a91507f77f

For getting this into your Lambda code you would probably want to use an environment variable within your Lambda CloudFormation resource.

More information about parameters can be found on the parameters page. By using the Ref intrinsic function with a suitable environment variable name you could then reference this within your code such as in the example below.

import os
region = os.environ['MY_VARIABLE']