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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:52:44