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.

tamsler
  • 1,275
  • 1
  • 18
  • 26

2 Answers2

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

Assael Azran
  • 2,863
  • 1
  • 9
  • 13
  • Note that it's: `--parameter-overrides`, parameter singular. – oflisback Jan 12 '20 at 10:56
  • Thanks. Actually it is written correctly in other parts of my answer. – Assael Azran Jan 12 '20 at 11:01
  • Indentation problem here (loathe to fix it)? – jtlz2 Sep 08 '22 at 07:31
  • **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: https://github.com/aws/aws-sam-cli/issues/5169#issuecomment-1548825825 (TL;DR: not working) – Andreas Lundgren Aug 11 '23 at 10:38
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.

jtlz2
  • 7,700
  • 9
  • 64
  • 114
Joey Kilpatrick
  • 1,394
  • 8
  • 20