提升@Aksel's answer 答案:这是一个 Terraform 解决方案;以防有人在搜索它。
Terraform's documentation 给出的示例不适用于我。
以下tf文件基于@Aksel's answer
main.tf
# main.tf
# AWS region
variable "aws_region" {
description = "AWS region"
type = string
default = "ap-southeast-1"
# default = "ap-northeast-1"
# default = "us-east-1"
}
# Caller identity
data "aws_caller_identity" "current" {}
iam.tf
- 为 API Gateway 设置角色,附加角色策略以允许向 SQS 发送消息
# iam.tf
resource "aws_iam_role" "apigw_sqs_role" {
name = "api_sqs_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy" "allow_apigw_sqs_policy" {
name = "allow_apigw_sqs_policy"
role = aws_iam_role.apigw_sqs_role.id
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":[
"sqs:SendMessage",
],
"Resource":"*"
}]
}
EOF
}
sqs.tf
# sqs.tf
resource "aws_sqs_queue" "my_sqs_queue" {
name = "my-queue"
}
apigateway.tf
- 使用 websocket 协议定义 API 网关
- 设置 $default 路由并附加集成
- apigateway 集成:
-
integration_type = "AWS" 和 integration_method = "POST"
-
integration_uri = arn:aws:apigateway:<aws_region>:sqs:path/<aws_account_id>/<sqs_name>
- 例如
arn:aws:apigateway:ap-southeast-1:sqs:path/111111110111/my-queue
-
credentials_arn 是iam.tf 中定义的角色
# apigateway.tf
# API Gateway
resource "aws_apigatewayv2_api" "apigw_websocket" {
name = "websocket-api"
protocol_type = "WEBSOCKET"
route_selection_expression = "$request.body.action"
}
resource "aws_apigatewayv2_route" "apigw_websocket_default_route" {
api_id = aws_apigatewayv2_api.apigw_websocket.id
route_key = "$default"
route_response_selection_expression = "$default"
target = "integrations/${aws_apigatewayv2_integration.apigw_websocket_default_integration_sqs.id}"
}
resource "aws_apigatewayv2_integration" "apigw_websocket_default_integration_sqs" {
api_id = aws_apigatewayv2_api.apigw_websocket.id
integration_type = "AWS"
integration_method = "POST"
integration_uri = "arn:aws:apigateway:${var.aws_region}:sqs:path/${data.aws_caller_identity.current.account_id}/${aws_sqs_queue.my_sqs_queue.name}/"
credentials_arn = aws_iam_role.apigw_sqs_role.arn
passthrough_behavior = "NEVER"
request_parameters = {
"integration.request.header.Content-Type" = "'application/x-www-form-urlencoded'"
}
request_templates = {
"application/json" : "Action=SendMessage&MessageBody=$util.urlEncode($input.body)"
}
}