Search code examples
aws-lambdastring-interpolationaws-sam

AWS Lambda String interpolation not working


So i was trying to over ride the lambda environment, i used string interpolation, but there is a small thing i am unable to understand, so basically following is my Lambda, if you see the function name it has a place holder for Environment. But when i deploy it like this

aws cloudformation deploy --template-file build/output.yaml --stack-name test-stack --capabilities CAPABILITY_IAM --parameter-overrides Environment=de
v

The placeholder doesn't update the following code

Parameters:
  Environment:
    Type: String

Resources:
    HelloWorldFunction:
        Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
        Properties:
            CodeUri: src
            Handler: index.lambda_handler
            Runtime: python3.6
            FunctionName: HelloLambda-${Environment}
            MemorySize: 128
            Timeout: 30
            Policies:
              - AWSLambdaBasicExecutionRole 

But if i do same like this Parameters: Environment: Type: String

Resources:

 HelloWorldFunction:
        Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
        Properties:
            CodeUri: src
            Handler: index.lambda_handler
            Runtime: python3.6
            FunctionName: !Sub HelloLambda-${Environment}
            MemorySize: 128
            Timeout: 30
            Policies:
              - AWSLambdaBasicExecutionRole

The above execution works, so whats the difference between FunctionName: !Sub HelloLambda-${Environment} and FunctionName: HelloLambda-${Environment}


Solution

  • By having !Sub in the front, you are invoking Sub-function with cloud formation. It takes the template parameters and applies the replacement where needed.

    More documentation at,

    https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html

    !Sub HelloLambda-${Environment}

    takes the Environment variable and replace with the value specified, thus you get different functions based on the environment variable.