解决 Terraform 报错 no valid credential sources for S3 指南
分析 Terraform 在执行 init 时连接 AWS S3 后端存储报 no valid credential sources 的排查方法与环境变量凭据配置。
问题现象
在终端执行 terraform init 初始化远端状态后端时报错退出:
Initializing the backend...
Error: error configuring S3 Backend: no valid credential sources for S3 Backend found.
Please see https://www.terraform.io/docs/language/settings/backends/s3.html
for more information about providing credentials.
Error: NoCredentialProviders: no valid providers in chain.
触发根因
- 终端环境中未注入 AWS 访问凭证(
AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY或 AWS Profile)。 - 在 CI/CD 容器中执行时,IAM Role 没有挂载或元数据服务(IMDSv2)未放开访问权限。
~/.aws/credentials文件中指定的 profile 名称与 Terraform backend 配置中的 profile 名称不一致。
解决步骤与操作命令
步骤一:通过环境变量显式注入临时凭证
在当前会话中导出有效凭证:
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_DEFAULT_REGION="us-east-1"
# 若使用 STS 临时 Token,同时导出 Session Token
export AWS_SESSION_TOKEN="AQoDYXdzEJr1..."
步骤二:核实 backend 配置中的 profile 与 region
在 backend.tf 中确认配置无误:
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "prod/terraform.tfstate"
region = "us-east-1"
# 若依赖 ~/.aws/credentials 中的命名配置,指定 profile
# profile = "default"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
步骤三:测试 AWS CLI 凭证有效性
在执行 init 前验证凭证链是否可用:
aws sts get-caller-identity
若返回对应的 Account 和 Arn,则说明凭证生效。
验证确认
重新执行后端初始化:
terraform init -reconfigure
控制台输出 Successfully configured the backend "s3"! Terraform has been successfully initialized! 即表示后端凭证连接成功。


