Setup Lambda to Event Source from SQS in Terraform

This guide will show you exactly how setup AWS Lambda to use SQS as an event source with Terraform.

Don’t poll. Do.

The old days of polling for messages on a queue are over. Why wait for messages, when you can process them as they come through?

AWS now supports SQS as an event source for Lambda functions. Yey.

This means that as SQS receives a message, it can trigger a Lambda function automatically to do some processing. Async baby.

Terraform code for setting up SQS

This is boilerplate SQS code from HashiCorp

Terraform code for setting up Lambda

This is boilerplate Lambda code from HashiCorp

Terraform code for setting up an SQS Event Source

This is the magic sauce for setting up a Lambda event source from SQS

The key concepts to understand here are that:

  1. Create an Event Source Mapping that takes the ARN of SQS as a parameter
  2. Set it to Enabled so that it immediately starts sending events to Lambda
  3. Set the batch size to whatever your requirements are. If you need to send 5 messages at a time, instead of every message once, change the batch_size value.

Verifying the Setup

  1. Log into AWS and go to the SQS console
  2. Select your queue
  3. On the bottom go to the Lambda Triggers tab
  4. You should see the ARN of your Lambda function with an Enabled Status
  5. Go to the Lambda console
  6. Select your Lambda function
  7. You should see SQS as a Trigger attached to your lambda
You should see SQS as a Trigger attached on the left handside
When you click on SQS and scroll to the bottom, you should see it Enabled

Now you can asynchronously process messages all day, erry day.

Hire AWS Solutions Architects & DevOps Engineers

Do you need AWS Solutions Architects & DevOps Engineers to build out your cloud, save costs or improve security? Hire me or my team.