Majestic.cloud

Using parameter overrides for different environments with an AWS SAM template

AWS SAM

Sometimes when you want to use the same AWS SAM template for multiple environments, such as dev or prod you might run into certain troubles. For example if you need to create a specific resource with a specific name, like for example an S3 bucket with the name “sn7-website” then you will have errors because you can’t have the same bucket name for the dev and the prod environments.

Sure, you could leave out the name completely and let AWS generate it for you, that works in some cases but in other cases where you need to rely on this value in some other places then this is not possible. So you have to find a solution to create a bucket named “dev-sn7-website” for the dev environment and a bucket named “prod-sn7-website” for the production environment.

Luckily AWS SAM has some options in this case. You can use the parameter-overrides option of the sam deploy command. But first you need to do some adjustments to your SAM template:

Parameters:
  Env:
    Type: String
    Default: dev
  S3BucketName:
    Type: String
    Default: sn7-website

Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "${Env}-${S3BucketName}"

You see we defined a Parameters section where you define your environment with the Env parameter having the default value “dev” and then the S3BucketName with the default value sn7-website.

Then at the bottom you see how we are generating the BucketName by concatenating the environment with the S3BucketName.

Now the final step, we need to deploy this which will actually create the resources

If you would use the plain deploy like this:

sam deploy

Then it would use the default values and deploy a bucket called “dev-sn7-website” due to the default values it has in the template

But if you override the parameters with the –parameter-overrides flag, like this:

sam deploy --parameter-overrides Env=prod

Then you would override the environment to “prod” and you would get the “prod-sn7-website” bucket name.

You can go a step further and override the bucket name as well, like this:

sam deploy --parameter-overrides Env=prod S3BucketName=some-other-bucket-name

This would result in the bucket being named “prod-some-other-bucket-name”

So you get the idea, this is how parameter overrides work and they can be used for a variety of purposes, one of them being this way of injecting the environment to the same SAM template. So no, you don’t need two templates for two different environments.

Exit mobile version