Open5
SQSのデッドレターキューを試す
例えばSQSのイベントソースにLambdaを使用しており、Lambdaの処理が失敗した場合
- キューにメッセージが残る
- そのメッセージを再度処理しようとする
- また失敗する
- 以下繰り返し
のようなことになる。
それをデッドレターキューで防ぎたい
ドキュメント
図
参考
sqsで使うawscliメモ
属性の確認
# すべて
aws sqs get-queue-attributes \
--queue-url $URL \
--attribute-names All
# 残メッセージ数
aws sqs get-queue-attributes \
--queue-url $URL \
--attribute-names ApproximateNumberOfMessages
テストメッセージの送信
aws sqs get-queue-attributes
--queue-url $URL \
--attribute-names ApproximateNumberOfMessages
コード
.
├── lambda_function
│ ├── lambda_function.py
│ └── src.zip
├── lambda.tf
├── main.tf
├── sns.tf
├── sqs.tf
└── variables.tf
tfファイル
### sqs
resource "aws_sqs_queue" "main" {
name = "${var.env}-queue"
}
### lambda
### ID
data "aws_caller_identity" "current" {}
locals {
account_id = data.aws_caller_identity.current.account_id
}
### IAMロール
resource "aws_iam_role" "main" {
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = {
Effect = "Allow"
Action = "sts:AssumeRole"
Principal = {
Service = "lambda.amazonaws.com"
}
Condition = {
StringEquals = {
"aws:SourceAccount" = local.account_id
}
}
}
})
}
resource "aws_iam_policy" "main" {
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
Resource = [
aws_cloudwatch_log_group.main.arn,
"${aws_cloudwatch_log_group.main.arn}:*"
]
},
{
Effect = "Allow"
Action = [
"sqs:DeleteMessage",
"sqs:GetQueueAttributes",
"sqs:ReceiveMessage",
],
Resource = [
aws_sqs_queue.main.arn,
]
}
]
})
}
resource "aws_iam_role_policy_attachment" "main" {
role = aws_iam_role.main.name
policy_arn = aws_iam_policy.main.arn
}
### cloudwatch logs
resource "aws_cloudwatch_log_group" "main" {
name = "/aws/lambda/${aws_lambda_function.main.function_name}"
retention_in_days = 30
}
### Lambda
data "archive_file" "main" {
type = "zip"
source_dir = "${path.root}/lambda_function"
output_path = "${path.root}/lambda_function/src.zip"
}
resource "aws_lambda_function" "main" {
function_name = "sqs-dlq"
handler = "lambda_function.lambda_handler"
runtime = "python3.11"
filename = data.archive_file.main.output_path
source_code_hash = filebase64sha256(data.archive_file.main.output_path)
role = aws_iam_role.main.arn
}
### sqs-lambda eventsource mapping
resource "aws_lambda_event_source_mapping" "main" {
event_source_arn = aws_sqs_queue.main.arn
function_name = aws_lambda_function.main.arn
}