Is it possible to define constants in SAM templates to make my template file more maintainable?

Viewed 1733

I am using AWS SAM to deploy my AWS Lambda functions to AWS.

I was able to define the Runtime once in the Globals section and was wondering if I could define a constant for the AWS Role to be assumed by my Lambdas (Role: arn:aws:iam::12345678:role/lambda-role), which is currently repeated in the template file for each function.

Here is my SAM template:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: python3.7

Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_a
      Role: arn:aws:iam::12345678:role/lambda-role

  FunctionB:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_b
      Role: arn:aws:iam::12345678:role/lambda-role
2 Answers

You could use Parameters or Mappings for that.

For example with Parameters:

Parameters:

  LambdaRoleArn:
    Type: String
    Default: arn:aws:iam::12345678:role/lambda-role

# Then for example

Resoureces:

  FunctionB:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_b
      Role: !Ref LambdaRoleArn

For example with Mappings:

Mappings:

  Lambda:
     Role: 
       Value: arn:aws:iam::12345678:role/lambda-role

# Then for example

Resoureces:

  FunctionB:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_b
      Role: !FindInMap [Lambda, Role, Value]

The advantage of mappings is that they can't be modified when deploying the template. But obviously, if you want to be able to do it, then parameters should be used.

You can use parameters and override them on deploy or use guided deploy to save them for next deploy run.

Check this template:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: python3.7

Parameters:
  role:
    Type: String

Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_a
      Role: ${role}

  FunctionB:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/
      Handler: app.event_handler_b
      Role: ${role}

How to deploy:

sam deploy --template-file template.yaml --stack-name mystack --capabilities CAPABILITY_IAM --parameter-overrides role=arn:aws:iam::12345678:role/lambda-role

Alternatively, you can use the --guided cli parameter. Check the docs from AWS below:

For example, when executing the sam deploy --guided command, AWS SAM CLI automatically adds the required parameters into the configuration file. You can subsequently execute sam deploy with no parameters, and the values will be retrieved from the configuration file.

Related