How to Perform Serverless Canary Release on Lambda via Terraform?

Amazon Web Services has introduced canary release for Lambda functions. So, we will be able to rolling out new software versions in production by slowly.

Let’s get started!

The first version of the Lambda function (index.js):

exports.handler = async(event) => {
const response = {
statusCode: 200,
body: JSON.stringify("V1")
};
return response;
};

data "archive_file" "blog_endpoint_zip" {
type = "zip"
source_file = "index.js"
output_path = "blog_endpoint.zip"
}
resource "aws_lambda_function" "blog_endpoint" {
filename = "blog_endpoint.zip"
function_name = "blog_endpoint"
role = "${data.aws_iam_role.the_role.arn}"
handler = "index.handler"
source_code_hash = "${data.archive_file.blog_endpoint_zip.output_base64sha256}"
runtime = "nodejs8.10"
publish = true
}
data "aws_iam_role" "the_role" {
name = "your_role_name_here"
}
output "version number" {
value = "${aws_lambda_function.blog_endpoint.version}"
}
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
version number = 1
exports.handler = async(event) => {
const response = {
statusCode: 200,
body: JSON.stringify("V2")
};
return response;
};
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
Outputs:
version number = 2
aws lambda create-alias --function-name blog_endpoint --name production --function-version 2 --routing-config "AdditionalVersionWeights={1=0.5}"

Let’s test it!

root@terraform:~# aws lambda invoke --invocation-type RequestResponse --function-name blog_endpoint:production --region eu-central-1 --log-type None out.txtroot@terraform:~# cat out.txt
{"statusCode":200,"body":"\"V2\""}
root@terraform:~# aws lambda invoke --invocation-type RequestResponse --function-name blog_endpoint:production --region eu-central-1 --log-type None out.txtroot@terraform:~# cat out.txt
{"statusCode":200,"body":"\"V1\""}

Hey, Wait! I’m using API Gateway!

No worries. You can call the alias via API Gateway. Please take a look at the screenshot below:

Don’t forget to append the alias to the Lambda function name

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store