Skip to content

SQS-triggered Function

SQS to Lambda

A Lambda function that is triggered by incoming messages from SQS queue.

The example below illustrates the deployment of an event-driven solution using SQS and Lambda function. Each time a new message is added to the queue, the Lambda function is invoked automatically to process it.

To simplify the deployment, this guide uses BYM's Terraform modules setup terraform-byks-module which provision the necessary IAM roles and permissions while handling the majority of the underlying configuration with predefined defaults.

components:

  • SQS queue
  • Lambda function
  • SNS subscription (optional)
source directory structure
├──application-name/
  ├── byks_application_name.tf
        lambda_functions {}
        sqs_queue {}
  └── locals.tf

Step 1: The Lambda Function

Add the following lambda_functions section to the byks_kattehotell.tf file.

byks_kattehotell.tf
module "byks_kattehotell" {
  source = "git@github.com:BYM-IKT/terraform-byks-module.git?ref=v12"
  # ...

  lambda_functions = {
    add-visitor-to-database = {
      override_name         = "kattehotell-add-visitor-test"
      ecr_uri               = data.terraform_remote_state.shared_kattehotell_ecr.outputs.kattehotell_add_visitors_ecr_repo
      image_tag             = var.environment
      environment_variables = local.kattehotell_add_visitor_environment_variables
    }
  } 
}
The required environment variables for the Lambda function can be provided in the locals.tf file inside kattehotell_add_visitor_environment_variables section.

locals.tf
1
2
3
4
5
locals {
  kattehotell_add_visitor_environment_variables = {
    ...
  }
}

Step 2: The SQS Queue

Update the byks_kattehotell.tf file by adding sqs_queuessection.

byks_kattehotell.tf
1
2
3
4
5
6
7
8
module "byks_kattehotell" {
  source = "git@github.com:BYM-IKT/terraform-byks-module.git?ref=v12"
  # ...

  sqs_queues = {
    new-visitors = { max_receive_count = 5 }
  }
}

Step 3: The SQS trigger inside the Lambda function

Add sqs_triggers block inside the lambda_functions section in the byks_kattehotell.tf file.

byks_kattehotell.tf
module "byks_kattehotell" {
  source = "git@github.com:BYM-IKT/terraform-byks-module.git?ref=v12"
  # ...

  lambda_functions = {
    add-visitor-to-database = {
      override_name         = "kattehotell-add-visitor-test"
      ...

      sqs_triggers = {
        new-visitors = {}
      }
    }
  } 
}

Step 4: SNS Subscription (Optional)

Update the byks_kattehotell.tf file by adding sns_topicssection.

byks_kattehotell.tf
module "byks_kattehotell" {
  source = "git@github.com:BYM-IKT/terraform-byks-module.git?ref=v12"
  # ...

  sns_topics = {
    created = {
      sqs_subscriptions = {
        new-visitors = {}
      }
    }
  }
}

Result:

Incoming message to the test-kattehotell-new-visitor SQS queue triggeres kattehotell-add-visitor-test Lambda function for a new deployment.