AWS SAM Template setting environment specific variables
Asked Answered
P

2

8

I am trying to configure a Lambda function's S3 policy bucket that is environment specific. I would like to be able to pass a variable during either "sam package" or "sam deploy" specifying "dev", "test" or "prod". The variable would be used in the template.yaml file to select environment specific settings:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  image-processing


Resources:
  ImageProcessingFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/image-processing.handler
      Runtime: nodejs12.x
      CodeUri: .
      MemorySize: 256
      Timeout: 300
      Policies:
        S3CrudPolicy:
          BucketName: dev-bucket-name  <-- change this to dev, test or prod

How can I achieve this using Parameters and or Variables? Thank you.

Pearliepearline answered 26/11, 2019 at 23:18 Comment(0)
P
15

You should use —parameter-overrides in your sam deploy command.

sam deploy cli

Let me demonstrate how:

In your template.yaml:

Parameters:
Env:
    Type: String

S3Bucket:
    Type: String

Resources:

ImageProcessingFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/image-processing.handler
      Runtime: nodejs12.x
      CodeUri: .
      MemorySize: 256
      Timeout: 300
      Policies:
        S3CrudPolicy:
          BucketName: !Sub "${Env}-${S3Bucket}"

Then execute:

sam deploy --template-file packaged.yaml --stack-name yourstack --capabilities CAPABILITY_IAM --parameter-overrides Env=dev S3Bucket=bucket-name

If you want to pass your parameters from a .json file per env you should consider using cross-env ENV=dev to pass your Env variable and then using gulp or whatever to execute your sam deploy --parameter-overrides command while passing your json file according to your Env variable (process.env.ENV) (converted to how parameters overrides pattern ) as parameter-overrides params.

Hope this helps

Parliamentary answered 27/11, 2019 at 9:57 Comment(4)
Note that it's: --parameter-overrides, parameter singular.Loudermilk
Thanks. Actually it is written correctly in other parts of my answer.Parliamentary
Indentation problem here (loathe to fix it)?Robinett
Is this still the latest and greatest way of doing it? I just seams too complicated to still be the common way of doing such a common thing. I just run into problems, trying to combine CLI and samtemplate.yaml, as someone described here: github.com/aws/aws-sam-cli/issues/5169#issuecomment-1548825825 (TL;DR: not working)Luca
J
4

You want to use the Parameters section of the template. Check out the docs here. You can then use the --parameter-overrides flag with the sam deploy command.

Jovitajovitah answered 27/11, 2019 at 4:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.