如何在Terraform定义的AWS ECS任务中使用AWS SSM作为valueFrom?
AWS ECS Terraform配置SSM参数作为环境变量的解决方案
核心问题根因
你在container_definitions的配置中重复定义了secrets字段:先声明了包含SSM参数的secrets数组,后续又额外添加了一行secrets : null,后者会直接覆盖前者的配置,导致最终生成的任务定义中secrets字段为null,配置不生效。
修正步骤
- 第一步:删除
container_definitions中多余的secrets : null行,同时修正配置中混用=和:、字段后缺少逗号的语法问题 - 第二步:确认ECS任务执行角色(即
execution_role_arn对应的IAM角色)已配置足够权限:- 允许
ssm:GetParameter动作,资源为你引用的SSM参数ARN - 如果你的SSM参数使用KMS加密,还需要额外允许
kms:Decrypt动作,资源为对应KMS密钥的ARN
- 允许
- 第三步:确认
valueFrom填写的是SSM参数的完整ARN,不可仅填写参数名
修正后配置示例
container_definitions = jsonencode( [ { name = aws_ecs_cluster.cluster.name, image = "${var.image_url}:latest", cpu = 7, dnsSearchDomains = null, network_configuration = "awsvpc", entryPoint = null, portMappings = [ { hostPort = 8080, protocol = "tcp", containerPort = 8080 }, { hostPort = 8793, protocol = "tcp", containerPort = 8793 } ], command = null, linuxParameters = null, environment = [ { name = "name", value = "harcoded" }, ], secrets = [ { name = "parameter-name", valueFrom = "arn:aws:ssm:eu-west-2:111111111:parameter/my_env_var_name_in_ssm" }, ], resourceRequirements = null, ulimits = null, dnsServers = null, mountPoints = null, workingDirectory = null, dockerSecurityOptions = null, memoryReservation = 128, volumesFrom = [], stopTimeout = null, startTimeout = null, firelensConfiguration = null, dependsOn = null, disableNetworking = null, interactive = null, healthCheck = null, essential = true, links = null, hostname = null, extraHosts = null, pseudoTerminal = null, user = null, readonlyRootFilesystem = null, dockerLabels = null, systemControls = null, privileged = null } ] )
验证方法
重新执行terraform apply后,查看生成的任务定义JSON,secrets字段会显示你配置的参数,任务启动后会自动从SSM拉取值作为环境变量注入容器。
内容的提问来源于stack exchange,提问作者mrc
相关产品推荐
相关产品推荐

