错误:获取状态锁失败:AccessDeniedException:用户 arn:aws:iam::123456789012:user/ci-bot 无权对资源 my-terraform-lock-table 执行 dynamodb:PutItem 操作
Error: Error acquiring the state lock: AccessDeniedException: User: arn:aws:iam::123456789012:user/ci-bot is not authorized to perform: dynamodb:PutItem on resource: my-terraform-lock-table
ID: policy/terraform-state-lock-dynamodb-permission-denied
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Terraform v1.5.0 | active | — | — | — |
| AWS Provider v5.0.0 | active | — | — | — |
根因分析
CI/CD IAM 角色缺少用于 Terraform 状态锁定的 DynamoDB 表的 dynamodb:PutItem 权限。
English
The CI/CD IAM role lacks the dynamodb:PutItem permission on the DynamoDB table used for Terraform state locking.
官方文档
https://developer.hashicorp.com/terraform/language/settings/backends/s3#dynamodb-state-locking解决方案
-
向 CI 角色添加所需的 IAM 策略:{"Effect": "Allow", "Action": ["dynamodb:PutItem", "dynamodb:GetItem", "dynamodb:DeleteItem"], "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/my-terraform-lock-table"} -
使用限制较少的 Terraform 后端配置,例如禁用 DynamoDB 锁定的 S3 后端(不推荐用于生产环境)。
无效尝试
常见但无效的做法:
-
95% 失败
Deleting the lock item does not fix the IAM permission; it only removes the symptom. The lock mechanism is disabled, leading to concurrent state writes.
-
80% 失败
While it resolves the immediate error, it introduces a security risk by allowing the CI user to delete tables or modify data beyond locking needs.
-
90% 失败
The error will recur when the pipeline runs again; the fix is not automated or scalable.