How to configure different settings per stage with Serverless Framework
Serverless Framework is a great way to quickly build and deploy services in AWS Lambda (Or Azure Functions, or Google Cloud Functions, etc…), but if you’re working in a more complex environment you might find a few things aren’t quite covered in the documentation.
One such thing that I came across was when my Lambda function needed to make an API call to another service to retrieve some data, meaning that the Lambda needs to have the right VPC configuration to access the other API.
The serverless.yml configuration file has a vpc section where this can be specified, but in my case there were different instances of the service for different environments, each with their own VPC settings. How to set that up?
Luckily serverless.yml allows the developer to access variables, including those passed in on the command line (Like the stage — this should tell us whether we’re deploying to dev or production). It’s also possible to access an external JavaScript file and read data from there.
Here’s what I ended up with…
In serverless.yml I have the following settings:
vpc:
securityGroupIds: ${file(config/vpc-config-${opt:stage}.js):securityGroups}
subnetIds: ${file(config/vpc-config-${opt:stage}.js):subnets}This references a file called vpc-config-dev.js or vpc-config-prod.js in the config folder. The contents of those files look like this:
module.exports.subnets = () => {
return [
'subnet-foo',
'subnet-bar'
];
};
module.exports.securityGroups = () => {
return ['sg-really-secure'];
};Serverless can then access the configurations by calling the relevant function in the JavaScript file. The arrays are handled correctly, too! You can add as many different configurations as you need, and could easily extend this model to cover all sorts of settings.
If you need more flexibility than the stage command-line option, Serverless can also read environment variables by using the format ${env:SOME_ENVIRONMENT_VARIABLE} — you can then have any arbitrary set of configurations you like.