Terraform 计划输出:使用的编码是什么

Terraform plan output: what is the encoding being used

我已经保存 terraform plan -out=my-plan 并打算将其保存到源代码管理并进一步注入自定义工具以进行摄取和执行测试等。

但是my-plan的文件内容乱七八糟,不知道用的是什么编码。

Terraform 计划文件使用的编码是什么?

Terraform 计划输出是二进制格式,不能在 Terraform 之外使用。从技术上讲,您可能可以使用 Terraform 用来处理格式的任何东西来序列化它,但是没有稳定的 API 并且可以随时更改。

Hashicorp 员工之一(Phinze) briefly covered this in this issue: https://github.com/hashicorp/terraform/issues/7976

一个可能相当脆弱的选项是简单地解析来自 运行 terraform plan 的文本输出。我使用 Terraform Landscape to format plan outputs locally when working with JSON diffs that Terraform doesn't handle at all and that copes with this fine. However it also tends to break on the "minor" version upgrades (eg 0.9 to 0.10) as Terraform doesn't specify this as an API at all. Terraform Plan Parser 也解析文本输出并注意到它非常不适合与二进制输出一起使用。

我找到了这个并且适合使用tfjson

Terraform 正在使用 gob format to encode/decode plan till version 0.11.x 这在 terraform 版本 0.12 上发生了变化,他们开始使用协议缓冲区。

tfjson 项目可能不适用于 0.11.x 和 0.12.x,除非您重写那里的依赖关系

虽然此处提到的其他工具很有用,但 Terraform space 中的内容会定期更改,并且第三方工具通常无法保持最新​​。

一段时间以来,Terraform 直接支持以与您 运行 plan:

时显示的相同的人类可读格式查看计划文件
terraform show <filename>

从 v0.12 开始,您现在还可以查看 JSON 格式的计划文件,您可以保存该文件以使用其他工具进一步处理:

terraform show -json <filename>

https://www.terraform.io/docs/internals/json-format.html 上有对 JSON 架构的解释。在撰写本文时,请注意:

The output ... currently has major version zero to indicate that the format is experimental and subject to change. A future version will assign a non-zero major version ... We do not anticipate any significant breaking changes to the format before its first major version, however.