Serverless Cloudformation Parameters
Introduction
While working with AWS, we all love creating infra with code, be it terraform, cdk or cloudformation. Me personally, I love cloudformation over any thing else. Also we use parameters to make the cloudformation more dynamic, be it getting different values for different environments or having to use different env or having to use different config values.
In order to deploy our beautifully crafted cloudformation, we have 2 tools at our hand, we can use either AWS SAM or Serverless Framework. Having worked with both, I find Serverless Framework light years ahead of AWS SAM. One core reason I have so much dislike for AWS SAM is, we can't break apart our long cloudformation into different files unless we want them as nested stack.
Serverless Framework
If we talk about Serverless, well, I've been using this tool for over 5 years and I have so much love for this framework. It addresses every pain points that SAM has left us with while supporting pure cloudformation code and providing easy way of splitting cloudformation snippets into multiple files.
If your stack grows huge, like really really huge, Serverless even provides Serverless Compose plugin, which not only manages to structure big stacks really nicely, but also provides following super cool features:
- Parallel deployment for multiple services
- Capability to share outputs from one stack(service) to another
- Running commands across multiple stacks
Now these are all nice and good but about Cloudformation Parameters which is our main concern here, well, serverless supports that as well. Let's look into how we can make use of that.
Using Parameters in Serverless
Parameters:
BucketName:
Type: String
Default: test-bucket
Stage:
Type: String
Default: dev
AllowedValues: [dev, uat, prod]
Resources:
MyS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${BucketName}-${Stage}"
AccessControl: Private
service: s3-bucket-param
frameworkVersion: "3"
provider:
name: aws
stage: dev
region: us-east-1
stackParameters:
- ParameterKey: BucketName
ParameterValue: ${param:BucketName}
- ParameterKey: Stage
ParameterValue: ${param:Stage}
resources:
- ${file(s3.yml)}
This is how we use the Cloudformation Parameters in Serverless. We define all the Parameters that we require under stackParameters
and either we can provide the value directly or through the serverless parameters. In order to supply the value and deploy the stack, we do the following command:
serverless deploy --param "BucketName=my-test-bucet" --param "Stage=dev"