Joey Yi Zhao
Joey Yi Zhao

Reputation: 42454

How to make SAM template file work for two different environment?

I am using AWS SAM to deploy my lambda to AWS. I created a template.yaml file and SAM will use this file to generate the packaged yaml. It works fine but I don't know how to make the same template file for two environment prod and staging. I want to change lambda function name and API gateway paht for different env. For example, I'd like to name it mylambda-prod for production and mylambda-staging for staging. The function name is defined in the template file in a hard coded way. Below is my template file. How can I make the function name and API gateway path to be dynamical? I know I can define two different template files but I am looking for a better way.

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: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs8.10
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: post

Upvotes: 1

Views: 891

Answers (1)

Reza Nasiri
Reza Nasiri

Reputation: 1435

I don't think you can change the function names but you can assign the paths dynamically and use a combination of Map and Parameters to have different values based on different parameter values. something like this:

Parameters: 
  Environment: 
  Type: String
  Default: dev
Mappings: 
  PathsMap:
     dev:
       path1: /hello1
       path2: /hello2
     prd:
       path1: hello11
       path2: /hello12

and in you function definition you assign the path like this

Path: !FindInMap [ PathsMap, !Ref Environment, path1]

you can override the parameter value when you deploy your template

Upvotes: 1

Related Questions