You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins运行Terraform代码报错:AWS Provider无有效凭据如何解决?

根因定位

本次报错的核心是Terraform AWS Provider调用AWS开放API时未找到合法的身份校验凭证,和你存放在GitLab的.ppk密钥无关联:.ppk是SSH协议登录EC2实例的认证密钥,不属于AWS服务商层面的API调用凭证。

修复步骤
  • 第一步:在Jenkins全局凭证库新增AWS凭证
    进入Jenkins控制台→凭证→系统→全局凭据,新建用户名与密码类型的凭证:
    • 用户名字段填写AWS IAM账号的Access Key ID
    • 密码字段填写AWS IAM账号的Secret Access Key
    • 自定义凭证ID,例如aws-terraform-cred
  • 第二步:修改Jenkins流水线注入凭证环境变量
    AWS Provider会默认读取AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY环境变量作为认证凭证,调整后的流水线代码如下:
    pipeline{
        agent any
        tools {
            terraform 'terraform'
        }
        // 新增环境变量块注入AWS凭证
        environment {
            AWS_ACCESS_KEY_ID = credentials('aws-terraform-cred').username
            AWS_SECRET_ACCESS_KEY = credentials('aws-terraform-cred').password
            // 替换为你实际使用的AWS区域,需和provider.tf中配置的区域一致
            AWS_REGION = "us-east-1"
        }
        stages{
            stage('Git Checkout'){
                steps{
                    git branch: 'main', credentialsId: 'github id', url: 'https://gitlab.com/path/project'
                }
            }
            
            stage('Terraform init'){
                steps{
                    dir('terraform-aws-ec2-with-vpc'){
                        sh 'terraform init'
                    }
                }
            }
            
            stage('Terraform plan'){
                steps{
                    dir('terraform-aws-ec2-with-vpc'){
                        // 可选:执行aws sts get-caller-identity提前校验凭证有效性
                        // sh 'aws sts get-caller-identity'
                        sh 'ls -ltra'
                        sh 'terraform plan'
                    }
                }
            }
            
            stage('Terraform apply'){
                steps{
                    dir('terraform-aws-ec2-with-vpc'){
                        sh 'terraform apply --auto-approve'
                    }
                }
            }
        }
    }
    
  • 第三步:修复原有流水线逻辑缺陷
    你原有的流水线存在两处逻辑错误,也会导致后续执行失败:
    • 第一个terraform init步骤未进入terraform-aws-ec2-with-vpc目录,属于无效执行
    • terraform apply步骤未进入terraform-aws-ec2-with-vpc目录,无法读取配置文件

内容的提问来源于stack exchange,提问作者Niladri Dey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:30:01