DEV Community

Vikas Garg
Vikas Garg

Posted on

Namespaced Stacks via SAM

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.

There can be only one!!
There can be only one!!

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
"""
Enter fullscreen mode Exit fullscreen mode

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
"""
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}`;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

If everything goes well, you will get the stack deployed ending with your provided namespace.

We are all the same
We are all the same

Full code can be found here.

Top comments (0)