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

Terraform plan -detailed-exitcode遇变更返回0而非2的问题求助

Terraform plan -detailed-exitcode 返回码异常问题解决方案

问题描述

在Travis环境中执行terraform plan -detailed-exitcode命令,环境明确存在资源变更(将创建ip_collection.planner_test1),命令输出也显示Plan: 1 to add, 0 to change, 0 to destroy.,但脚本捕获到的返回码是0而非预期的2,更换多个Terraform版本后问题依旧。

相关脚本代码

捕获返回码的命令:

local plan_output=$(terraform plan -no-color -detailed-exitcode 2>&1) && plan_rc=0 || plan_rc=$?

git_comment函数:

function git_comment() {
    local command_output="${1}"
    local output_code="${2}"

    message=$(echo "${command_output}" | grep -E 'No changes.|Plan: ([0-9\(\)]+\sto\sadd,\s[0-9\(\)]+\sto\schange,\s[0-9\(\)]+\sto\sdestroy.)|Error:')

    if [ "${output_code}" -eq 0 ]; then
        print_info "${message}"
        payload=$(build_git_comment "No changes" ":large_blue_circle:" "${message}")
    elif [ "${output_code}" -eq 2 ]; then
        print_success "${message}"
        payload=$(build_git_comment "Success" ":green_circle:" "${message}" "${command_output}")
    else
        print_fail "${message}"
        payload=$(build_git_comment "Failed" ":red_circle:" "${message}" "${command_output}")
    fi
    print_info "********** ADDING DETAILED PLAN TO PR **********"
    add_git_comment "${payload}"
}

Terraform plan 输出

Terraform used the selected providers to generate the following execution

plan. Resource actions are indicated with the following symbols:

  + create

Terraform will perform the following actions:

  # ip_collection.planner_test1 will be created

  + resource "ip_collection" "planner_test1" {

      + description = "Planner_test1"

      + environment = "att"

      + id          = (known after apply)

      + ips         = [

          + "1.2.3.4",


        ]

      + name        = "Planner_test1"

    }

Plan: 1 to add, 0 to change, 0 to destroy.

问题分析

问题出在返回码的捕获逻辑上:local plan_output=$(terraform plan ...)会执行命令并捕获输出,但括号内命令的退出码会被$()完全覆盖,后续的&& plan_rc=0 || plan_rc=$?判断的是local plan_output=...这个赋值操作的退出码,而非terraform plan本身的退出码。由于赋值操作只要语法正确就会返回0,所以无论terraform plan返回2还是其他非0值,最终plan_rc都会被设为0。

解决方案

修改返回码捕获逻辑,直接获取terraform plan命令的退出码,避免被赋值操作覆盖:

# 先执行命令并捕获输出
local plan_output=$(terraform plan -no-color -detailed-exitcode 2>&1)
# 直接获取terraform plan的退出码
plan_rc=$?

或者如果需要先保存输出到文件再读入变量:

# 执行命令并将输出写入文件
terraform plan -no-color -detailed-exitcode 2>&1 > plan_output.txt
# 获取命令退出码
plan_rc=$?
# 读取文件内容到变量
local plan_output=$(cat plan_output.txt)

修改后,plan_rc就能正确对应terraform plan的退出码规则:存在变更时返回2,无变更返回0,执行出错返回非0的其他值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:45:11