I'm an SRE engineer. @hayaosato. This time, I would like to call AWS Lambda (hereinafter, Lambda), which is super convenient for building a serverless architecture, from Amazon SQS (hereinafter, SQS). The code is here
Lambda Lambda resources can be created as follows. The application is a script for slack notifications.
// IAM Role for Lambda Function
resource "aws_iam_role" "default" {
name = var.service_name
description = "IAM Rolw for ${var.service_name}"
assume_role_policy = file("${var.service_name}_role.json")
}
resource "aws_iam_policy" "default" {
name = var.service_name
description = "IAM Policy for ${var.service_name}"
policy = file("${var.service_name}_policy.json")
}
resource "aws_iam_role_policy_attachment" "default" {
role = aws_iam_role.default.name
policy_arn = aws_iam_policy.default.arn
}
// Lambda Function Resources
resource "aws_cloudwatch_log_group" "default" {
name = "/aws/lambda/${var.service_name}"
retention_in_days = 7
}
data archive_file "default" {
type = "zip"
source_dir = "src"
output_path = var.output_path
}
resource "aws_lambda_function" "default" {
filename = var.output_path
function_name = var.service_name
role = aws_iam_role.default.arn
handler = "lambda_function.lambda_handler"
source_code_hash = data.archive_file.default.output_base64sha256
runtime = "python3.6"
environment {
variables = {
SLACK_API_KEY = var.SLACK_API_KEY
}
}
}
When creating a Lambda function with Terraform, please use the archive resource ʻarchive_file. By using this, you can generate a zip and apply it to the Lambda function as it is, which is very easy. In other words, you can just incorporate this configuration into CI and
terraform apply` from the CI tool.
SQS SQS resources can be created as follows.
resource "aws_sqs_queue" "default" {
name = "${var.service_name}.fifo"
fifo_queue = true
content_based_deduplication = true
}
Terraform has a resource called lambda_event_source_mapping for setting Lambda triggers. This time I will use this.
resource "aws_lambda_event_source_mapping" "default" {
event_source_arn = aws_sqs_queue.default.arn
function_name = aws_lambda_function.default.arn
}
Also, since this resource currently only supports SQS, DynamoDB, and Kinesis, it cannot be linked from SNS (the wreckage of the resource created to link the code with SNS ...).
If you put the ARN of a resource that cannot be specified in ʻevent_source_arn, it will be
creating ... `infinitely.
However, the event from S3 can be executed normally.
Let's actually issue a queue with the created resource and execute it. I was able to
After all serverless is good
Recommended Posts