Fargate私有容器通过Terraform访问Secrets Manager报错求助
问题现象
AWS控制台启动Fargate服务时弹出以下错误:
ResourceInitializationError: unable to pull secrets or registry auth: execution resource retrieval failed: unable to retrieve secret from asm: service call has been retried 5 time(s): failed to fetch secret arn:aws:secretsmanager:us-east-1:xxx:secret:example_secret_1-e88LWc from secrets manager: RequestCanceled: request context canceled caused by: context deadline exceeded
代码中的核心问题与修复方案
1. 任务安全组出站规则限制
你的example_service安全组仅允许443端口出站,但未指定可访问的目标范围,导致Fargate任务无法与Secrets Manager的VPC端点建立连接。
修正代码:
resource "aws_security_group" "example_service" { vpc_id = aws_vpc.example_vpc.id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] # 根据实际需求调整访问源 } egress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["10.0.0.0/16"] # 指向你的VPC私有IP段,确保能访问VPC端点 } }
2. S3 VPC端点类型错误
S3的VPC端点必须使用Gateway类型,而非Interface类型,错误的类型会导致S3流量路由异常,间接影响任务初始化(如ECR镜像拉取依赖S3)。
修正代码:
resource "aws_vpc_endpoint" "s3" { vpc_id = aws_vpc.example_vpc.id service_name = "com.amazonaws.${var.aws_region}.s3" vpc_endpoint_type = "Gateway" # 修正为Gateway类型 route_table_ids = [aws_route_table.example.id] # 关联子网路由表,引导S3流量走内网 auto_accept = true }
注:需先创建并关联对应子网的路由表
3. IAM执行角色权限缺失
任务执行角色缺少secretsmanager:DescribeSecret权限,导致无法在获取密钥值前完成密钥描述验证,触发请求失败。
修正代码:
data "aws_iam_policy_document" "secrets_access" { statement { effect = "Allow" actions = [ "secretsmanager:GetSecret", "secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret" # 添加该权限 ] resources = [ "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current_user.account_id}:secret:*" ] } }
4. 任务定义中Secret ARN引用不当
当前任务定义使用了Secret版本的ARN,虽然能生效,但推荐直接使用Secret的基础ARN,Secrets Manager会自动获取最新版本。
修正代码:
container_definitions = jsonencode([{ name = "example_container" image = "hello-world" secrets = [{ name = "example_secret" valueFrom = aws_secretsmanager_secret.example_secret.arn # 改用Secret的基础ARN }] portMappings = [{ containerPort = 80 hostPort = 80 }] }])
验证步骤
- 应用上述修正后重新部署Terraform资源
- 启动Fargate服务,查看任务状态
- 若仍超时,检查CloudWatch任务初始化日志获取更详细错误信息
- 确认VPC端点状态为
available,且安全组规则允许任务安全组的443流量入站
内容的提问来源于stack exchange,提问作者eltiare

