Creating AWS Lambdas through Terraform using archive_file

Preface

In Terraform the aws_lambda_function has a parameter called source_code_hash. This parameter is a base64-encoded SHA256 hash of the package file specified with either filename or s3_key. The file itself is typically a zip file.

Editing your code and zipping it up over and over can become a tedious process and if you use version control, it’s better practice to just edit a single file and have it zip itself automatically for terraform to use.

The archive_file is also supported within Terraform Enterprise.

Tutorial

For this tutorial we will be creating a hello world lambda. A variables.tf is missing however in the real-world you would still likely have one.

1Create your main.tf

This is where it gets juicy.

Create your main.tf file. In your main.tf you will have the following Terraform resources created which we will cover below.

Lambda Function

Lambda Role

Lambda Role Policy for CloudWatch Logs

Archiving Lambda Code

At this point you will have an empty main.tf file.

2Create your lambda source code file

We will be creating a nodejs lambda. So our code will be written in javascript.

Create a file call example.js within a new folder called lambda. This “lambda” folder will also be used when terraform creates the zip file for you.

Your handler is your filename.method. So for us it will be example.handler, this will be used later on in the tutorial.