GitLab Pipeline执行Terraform Init失败,报错无sh命令求助
GitLab Pipeline Terraform执行失败问题解决
错误根源
hashicorp/terraform官方镜像的默认ENTRYPOINT是terraform,当你在before_script或script中执行非Terraform命令(如apk、pip)时,GitLab Runner会将这些命令传递给Terraform执行,从而触发"Terraform has no command named 'sh'"类错误。
解决方案
修改plan任务的配置,覆盖镜像默认的ENTRYPOINT,让Runner可以直接执行shell命令,以下是两种常用实现方式:
方式1:清空ENTRYPOINT(推荐)
在plan任务中添加entrypoint: [""],让Runner使用默认shell执行命令:
plan: image: hashicorp/terraform:${TF_VERSION} stage: plan entrypoint: [""] # 覆盖默认ENTRYPOINT before_script: - apk add --no-cache python3 py3-pip - pip install awscli - terraform init script: - terraform plan -out=tfplan artifacts: paths: - tfplan only: - main
方式2:指定shell路径作为ENTRYPOINT
直接指定shell执行路径,确保所有命令通过shell运行:
plan: image: hashicorp/terraform:${TF_VERSION} stage: plan entrypoint: ["/bin/sh", "-c"] before_script: - apk add --no-cache python3 py3-pip - pip install awscli - terraform init script: - terraform plan -out=tfplan artifacts: paths: - tfplan only: - main
额外检查项
- 确认项目根目录下存在
.tf后缀的Terraform配置文件,避免terraform init因找不到配置文件失败。 - 验证
AWS_ACCESS_KEY_ID和AWS_SECRET_ACCESS_KEY已正确设置为项目受保护变量,且main分支为受保护分支,确保变量能正常注入到Pipeline中。
内容的提问来源于stack exchange,提问作者user28263994
相关产品推荐
相关产品推荐

