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

如何通过GitHub Action流水线仅执行Terraform变更并修复无变更执行apply问题

修复Terraform漂移检测流水线的apply执行问题

问题描述

我搭建了一个用于Terraform漂移检测的GitHub Action流水线,当前存在的问题是:即使Terraform plan未检测到需要处理的变更(比如过滤掉了google_project_iam_binding类型资源的删除/更新操作),流水线依然会执行terraform apply步骤。

问题原因

现有流水线中,terraform plan步骤在以下场景会返回退出码0:

  • Terraform plan本身未检测到任何变更
  • Terraform plan检测到变更,但经过jq过滤后,不存在需要处理的目标变更(即仅存在google_project_iam_binding类型的删除/更新)

而terraform apply步骤的执行条件是if: ${{ success() }},只要terraform plan步骤执行成功(退出码为0或2),就会触发apply,导致无变更时也执行了不必要的apply操作。

修复方案

修改terraform apply步骤的执行条件,仅当terraform plan步骤最终返回退出码2(即存在需要处理的变更)时才执行apply。具体需要:

  1. 给terraform plan步骤添加id属性,以便后续步骤引用其退出码
  2. 将terraform apply的执行条件改为判断terraform plan步骤的退出码是否等于2

修改后的完整流水线代码

# An exit code of 0 indicated no changes, 1 a terraform failure, 2 there are pending changes.
- name: terraform plan
  id: plan
  run:  |
    set +e
    terraform plan -detailed-exitcode -input=false -out=${{ github.sha }}.plan
    retVal=$?
    set -e
    if [ $retVal -eq 2 ]; then
      value=$(terraform show -json ${{ github.sha }}.plan | jq '.resource_changes[] | select((.type != "google_project_iam_binding") and (.change.actions | index("delete","update")))')
      if [ -z "${value}" ]; then
        exit 0
      fi
    fi
    exit $retVal

- name: Notify via teams
  uses: dhollerbach/actions.send-message-to-ms-teams
  if: ${{ failure() }} 
  with:
    message: "Pipeline is failed "

- name: terraform apply
  if: ${{ steps.plan.exitcode == 2 }}
  id: apply
  run: |
    terraform apply -auto-approve ${{ github.sha }}.plan

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:21