在hashicorp/terraform-exec中调用tf.Apply()设置Target参数报错求助
问题
我正尝试使用hashicorp/terraform-exec的Go SDK为terraform apply命令添加target参数,对应的CLI命令是terraform apply --auto-approve --target 'module.example'。但当我把targets传入ApplyOption{}并传递给Apply()函数时出现错误,错误提示为invalid composite literal type tfexec.ApplyOption。
我的代码如下:
package main import ( "context" "github.com/hashicorp/terraform-exec/tfexec" ) func main() { // 创建tfexec.Executor实例 tf, err := tfexec.NewTerraform("/path/to/terraform/binary") if err != nil { panic(err) } err = tf.Init(context.Background(), tfexec.Upgrade(true)) if err != nil { panic(err) } // 定义要应用的目标资源 targets := []string{"module.example", "module.another_example"} // 创建带targets的ApplyOption applyOption := tfexec.ApplyOption{ Targets: targets, } // 应用Terraform配置并传入目标参数 err = tf.Apply(context.Background(), applyOption) if err != nil { panic(err) } }
执行go run test.go时得到错误:
command-line-arguments ./test.go:23:17: invalid composite literal type tfexec.ApplyOption
请问我哪里操作有误?
解决方法
你错在对terraform-exec SDK的API使用逻辑理解偏差:tfexec.ApplyOption是接口类型,不能直接用结构体字面量实例化,SDK专门提供了构造函数来生成符合该接口的选项实例。
正确做法是用tfexec.Targets()函数创建target选项,同时如果需要对应CLI的--auto-approve参数,还要加上tfexec.AutoApprove()选项。修改后的代码如下:
package main import ( "context" "github.com/hashicorp/terraform-exec/tfexec" ) func main() { tf, err := tfexec.NewTerraform("/path/to/terraform/binary") if err != nil { panic(err) } err = tf.Init(context.Background(), tfexec.Upgrade(true)) if err != nil { panic(err) } targets := []string{"module.example", "module.another_example"} // 使用SDK提供的构造函数创建选项并传入Apply方法 err = tf.Apply(context.Background(), tfexec.Targets(targets...), tfexec.AutoApprove()) if err != nil { panic(err) } }
核心要点
tfexec.Targets()接收可变参数字符串,对应CLI的--target参数,用于指定要操作的目标资源tfexec.AutoApprove()对应CLI的--auto-approve参数,跳过交互式确认直接执行Apply()方法接收的是多个tfexec.ApplyOption接口实例,不能直接实例化结构体传入
内容的提问来源于stack exchange,提问作者Sumit Das
相关产品推荐
相关产品推荐

