执行“替换”操作;terraform.ReadPlan不再使用“;

执行“替换”操作;terraform.ReadPlan不再使用“;,terraform,Terraform,Microsoft提供了一个使用Terratest测试Terraform基础设施的示例: 代码中有一个有趣的部分: // Terraform init and plan only tfPlanOutput := "terraform.tfplan" terraform.Init(t, tfOptions) terraform.RunTerraformCommand(t, tfOptions, terraform.FormatArgs

Microsoft提供了一个使用Terratest测试Terraform基础设施的示例: 代码中有一个有趣的部分:

        // Terraform init and plan only
        tfPlanOutput := "terraform.tfplan"
        terraform.Init(t, tfOptions)
        terraform.RunTerraformCommand(t, tfOptions, terraform.FormatArgs(tfOptions.Vars, "plan", "-out="+tfPlanOutput)...)

        // Read and parse the plan output
        f, err := os.Open(path.Join(tfOptions.TerraformDir, tfPlanOutput))
        if err != nil {
            t.Fatal(err)
        }
        defer f.Close()
        plan, err := terraformCore.ReadPlan(f)
如果您尝试在Terraform 0.12上执行它,则会出现错误:

terraform.ReadPlan is no longer in use; use planfile.Open instead

问题是,我如何重新实现微软的代码来使用Terraform 0.12?如何将*文件转换为计划

此错误消息针对的是使用Terraform代码库本身的人员,而不是外部调用者。
terraform
Go包不是一个公共API,因此,尽管从技术上讲,其他Go代码库可以调用它,但它没有兼容性承诺,任何其他调用它的系统都可能在将来的版本中被重构破坏(正如我们在本例中看到的)

话虽如此,Terraform 0.12引入了一种受支持的方式,通过对保存的计划文件进行解码,以便在其他软件中进行检查

terratest
有一个函数,您可以使用该函数运行
terraform show-json
并获取原始json输出:

planJSON, err := terraform.RunTerraformCommandAndGetStdoutE(
    t, tfOptions, terraform.FormatArgs("show", "-json", tfPlanOutput)...
)

然后,您可以使用Go标准库
encoding/json
包将其解析为您自己的一些
struct
类型,这些类型涵盖了您打算编写的测试所需的子集。

您的解决方案非常聪明!谢谢
但是,我不得不添加一些小的修改,因为FormatArgs需要*选项作为第一个参数:``func FormatArgs(Options*Options,args…string)```所以我的最终解决方案是:```tfOptionsEmpty:=&terraform.Options{}planJSON,err:=terraform.runterraformcommandgetstdoute(t,tfOptions,terraform.FormatArgs(tfOptionsEmpty,“show”,“-json”“``注意:RunTerraFormCommandGetStdoute将传入您在TerraformOptions中定义的任何变量