Vikas Garg
Posted on November 19, 2020
AWS SAM is a nice tool when it comes to orchestrating a new serverless stack. It has its own quirks and shenanigans which needs to be worked around. One such was the lack of support for namespaced stacks, which could come in handy where you have multiple developers deploying in the same environment during development phase.
But thanks to --config-file
samcli option, this has become possible. Here is my take on how we can establish this.
Create Sam Configuration File
You need to create a new configuration file, which will have the same contents as existing samconfig.toml file apart from some minor differences as highlighted below.
samconfig.toml
stack_name = "blog-sam-custom-namespace-dev"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-s7lq825ncn5b"
s3_prefix = "blog-sam-custom-namespace-dev"
region = "us-east-1"
capabilities = "CAPABILITY_NAMED_IAM"
parameter_overrides = """
Environment=dev
NodeEnv=dev
"""
samconfig-jdoe.toml
stack_name = "blog-sam-custom-namespace-jdoe"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-s7lq825ncn5b"
s3_prefix = "blog-sam-custom-namespace-jdoe"
region = "us-east-1"
capabilities = "CAPABILITY_NAMED_IAM"
parameter_overrides = """
Environment=jdoe
NodeEnv=jdoe
"""
Update your template
Update your template.yaml(or yml) like following,
S3UploaderFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: build/s3-uploader
Handler: index.handler
Role: !Sub ${BlogSamCustomNamespaceRole.Arn}
Environment:
Variables:
ENV: !Ref Environment
NODE_ENV: !Ref NodeEnv
Note: If you have multiple functions, you can also move the environment variable declaration to Globals.
Handle or use environment in the code
Now, if you want to use the passed in environment, you can use it in following way (not limited to),
const S#_BUCKET = `blog-sam-custom-namespace-bucket-${process.env.ENV}`;
Deploy
Given you already have your AWS profile set and project built, you can run the following command to deploy,
sam deploy --config-file samconfig-jdoe.toml
If everything goes well, you will get the stack deployed ending with your provided namespace.
Full code can be found here.
Posted on November 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.