Terraform Plan无变更时无计划统计信息问题求助
问题原因
这是Terraform本身的设计行为,而非Ansible Tower或Playbook的问题:
terraform plan的"Plan: X to add..."统计行,仅针对基础设施资源的增/改/删变更(比如EC2实例、S3桶这类资源的属性变化)。- 当没有资源变更,但存在需要更新到状态文件的**输出值(Outputs)**时,Terraform只会输出提示:
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.,不会打印0变更的统计行。 - 你查看plan文件也看不到该统计,因为plan文件本身就不包含无资源变更时的这条统计信息——它只记录实际的资源变更内容。
解决办法
根据你的需求,有几种可靠的处理方式:
1. 利用Terraform的退出码判断(推荐)
使用-detailed-exitcode参数让terraform plan返回明确的退出码,无需依赖输出文本:
- 退出码
0:无任何变更(包括资源和输出值) - 退出码
2:存在资源变更 - 退出码
1:执行出错
在Ansible Playbook中可以这样实现:
- name: 执行terraform plan(导入后) command: terraform plan -detailed-exitcode -out=post_import_plan.plan register: tf_post_plan ignore_errors: true # 退出码2是正常变更,Ansible会默认标记为失败,所以需要忽略 - name: 提示存在资源变更 debug: msg: "Plan: 检测到资源变更" when: tf_post_plan.rc == 2 - name: 提示无资源变更 debug: msg: "Plan: 0 to add, 0 to change, 0 to destroy." when: tf_post_plan.rc == 0 - name: 处理plan执行错误 fail: msg: "terraform plan执行失败: {{ tf_post_plan.stderr }}" when: tf_post_plan.rc == 1
2. 解析Plan的JSON输出
将plan文件转为JSON格式,通过解析resource_changes数组的长度判断是否有资源变更:
- name: 生成plan文件 command: terraform plan -out=post_import_plan.plan register: tf_plan_run - name: 将plan转为JSON command: terraform show -json post_import_plan.plan register: tf_plan_json - name: 统计资源变更数量 set_fact: resource_change_count: "{{ (tf_plan_json.stdout | from_json).resource_changes | default([]) | length }}" - name: 输出变更统计 debug: msg: "Plan: {{ resource_change_count }} 个资源变更" when: resource_change_count > 0 - name: 输出无变更统计 debug: msg: "Plan: 0 to add, 0 to change, 0 to destroy." when: resource_change_count == 0
3. 文本过滤(不推荐,依赖输出格式)
如果必须依赖输出文本,可以检查是否存在"Plan: "开头的行,不存在则手动输出无变更信息:
- name: 执行terraform plan(导入后) command: terraform plan -out=post_import_plan.plan register: tf_post_plan - name: 手动输出无变更统计 debug: msg: "Plan: 0 to add, 0 to change, 0 to destroy." when: tf_post_plan.stdout is not search('^Plan: ')
内容的提问来源于stack exchange,提问作者user20757053
相关产品推荐
相关产品推荐

