英文:
How to pass `ApplyConfig` to `tf.Apply()` in `hashicorp / terraform-exec`?
问题
我正在尝试使用 Terraform 的 golang sdk(terraform-exec)为 terraform apply 命令添加一个 target。理想情况下,等效的 CLI 命令是 terraform apply --auto-approve --target 'module.example'。但是,当我将 targets 传递给 ApplyOptions{} 中的 Apply() 函数时,我遇到了以下错误。有人可以指出我在这里做错了什么吗?
错误信息是 invalid composite literal type tfexec.ApplyOptioncompiler。
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"}
	// 创建一个包含目标的 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。
英文:
I am trying to add a target to terraform apply command using golang sdk for terraform in hashicorp/terraform-exec
Ideally, the equivalent command for CLI is terraform apply --auto-approve --target 'module.example'
But I am getting the following error when I pass the targets in  ApplyOptions{} to the Apply() function.
Can anybody point me what I am doing wring here?
package main
import (
	"context"
	"github.com/hashicorp/terraform-exec/tfexec"
)
func main() {
	// Create a new tfexec.Executor instance
	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)
	}
	// Define the targets you want to apply
	targets := []string{"module.example", "module.another_example"}
	// Create an ApplyOption with the targets
	applyOption := tfexec.ApplyOption{
		Targets: targets,
	}
	// Apply the Terraform configuration with the defined targets
	err = tf.Apply(context.Background(), applyOption)
	if err != nil {
		panic(err)
	}
}
The error says, invalid composite literal type tfexec.ApplyOptioncompiler
go run test.go # command-line-arguments ./test.go:23:17: invalid composite literal type tfexec.ApplyOption
答案1
得分: 0
我认为以下代码应该可以工作:
	targets := []tfexec.ApplyOption{
		tfexec.Target("module.example"),
		tfexec.Target("module.another_example"),
	}
	// 使用定义的目标应用 Terraform 配置
	err = tf.Apply(context.Background(), targets...)
	if err != nil {
		panic(err)
	}
英文:
I think the following should work:
	targets := []tfexec.ApplyOption{
		tfexec.Target("module.example"),
		tfexec.Target("module.another_example"),
	}
	// Apply the Terraform configuration with the defined targets
	err = tf.Apply(context.Background(), targets...)
	if err != nil {
		panic(err)
	}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论