1
votes

I want to dynamically create names for my resources in my Cloud Formation stack when using AWS SAM if this is possible.

E.g. when I package or deploy I want to be able to add soemthing to the command line like this:

sam package --s3-bucket..... --parameters stage=prod

When in my template.yml file somehow to do something like this:

Resources:
  OrdersApi:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: orders-api-${stage}
      CodeUri: ./src/api/services/orders/
      ...

Note for the OrdersApi property of FunctionName I want to dynamically set it to orders-api-prod which is the value I attempted to pass in on the CLI.

I can do this quite easily using the Serverless Framework but I can't quite work out how to do it with SAM.

2

2 Answers

4
votes

You can use functions like Sub to construct resource names in CloudFormation. Something along the lines:

Parameters:
  stage:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod
Resources:
  OrdersApi:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub 'orders-api-${stage}'
1
votes

The answer posted by lexicore is correct and you can form values in certain parts of the template.yaml file using the !Sub function e.g.

FunctionName: !Sub 'orders-api-${stage}'

The missing part of why this wouldn't work is that you need to pass the parameters through to the sam deploy command in a specific format. From reading the AWS docs, sam deployis shorthand for aws cloudformation deploy.... That command allows you to pass parameters using the following syntax:

aws cloudformation deploy .... --parameter-overrides stage=dev

This syntax can also be used with the sam deploy command e.g.

sam deploy --template-file packaged.yml ..... --parameter-overrides stage=dev

Note that in this example stage=dev applies to the Parameters section of the template.yaml file e.g.

Parameters:
  stage:
    Type: String
    AllowedValues:
      - dev
      - stage
      - prod

This approach allowed me to pass in parameters and dynamically change values as the cloud formation stack was deployed.