Terraform Cloud未识别GitHub Actions中的TF_VAR环境变量
问题
我在GitHub Actions流水线中使用如下Terraform Cloud工作流:
terraform: name: "Terraform Plan" runs-on: ubuntu-latest needs: build permissions: contents: read pull-requests: write env: TF_CLOUD_ORGANIZATION: "xxx" TF_API_TOKEN: "${{ secrets.TF_API_TOKEN }}" TF_WORKSPACE: "xxx" CONFIG_DIRECTORY: "./infrastructure" steps: - name: Checkout uses: actions/checkout@v3 - name: Set variables run: echo "TF_VAR_image_tag=$(echo $GITHUB_SHA | cut -c 1-6)" >> $GITHUB_ENV - name: Upload Configuration uses: hashicorp/tfc-workflows-github/actions/upload-configuration@v1.0.4 id: plan-upload with: directory: ./ workspace: ${{ env.TF_WORKSPACE }} speculative: true - name: Create Plan Run uses: hashicorp/tfc-workflows-github/actions/create-run@v1.0.4 id: plan-run with: workspace: ${{ env.TF_WORKSPACE }} configuration_version: ${{ steps.plan-upload.outputs.configuration_version_id }} plan_only: true
我尝试通过设置TF_VAR_image_tag环境变量为Terraform变量image_tag赋值,但始终收到错误提示:
The root module input variable "image_tag" is not set, and has no default value
我的image_tag变量定义如下:
variable "image_tag" { type = string }
请问我遗漏了什么配置?
解决方案
核心问题是:你在GitHub Actions runner本地设置的TF_VAR_*环境变量,不会自动传递到Terraform Cloud的云端运行环境中。Terraform Cloud的plan/apply运行是在它自身的基础设施上执行的,并非你的GitHub Actions runner,所以runner上的环境变量无法被Terraform Cloud直接读取。
解决方法是直接在create-run步骤中通过variables参数传递变量:
- 修改
Create Plan Run步骤,添加variables字段传入image_tag的值:
- name: Create Plan Run uses: hashicorp/tfc-workflows-github/actions/create-run@v1.0.4 id: plan-run with: workspace: ${{ env.TF_WORKSPACE }} configuration_version: ${{ steps.plan-upload.outputs.configuration_version_id }} plan_only: true variables: '{"image_tag": "${{ env.TF_VAR_image_tag }}"}'
- 你也可以跳过设置环境变量的步骤,直接在参数里生成
image_tag的值,简化流程:
variables: '{"image_tag": "${{ substr(github.sha, 0, 6) }}"}'
另外提个细节:你在env里定义了CONFIG_DIRECTORY: "./infrastructure",但upload-configuration步骤的directory用的是./,如果你的Terraform配置确实在./infrastructure目录下,建议把这个参数改成${{ env.CONFIG_DIRECTORY }},避免上传不必要的文件,不过这不是变量未传递的直接原因。
内容的提问来源于stack exchange,提问作者DSteman
相关产品推荐
相关产品推荐

