代码

package main
 
import (
    "fmt"
    "github.com/hashicorp/hcl/v2/hclwrite"
    "github.com/zclconf/go-cty/cty"
    "os"
    "io/ioutil"
)

func main() {
    // 创建一个空的文件体系
    f := hclwrite.NewEmptyFile()
    // 创建一个body对象,所有的hcl元素都将附加在这个对象上
    body := f.Body()

    //var re cty.Value
    re := cty.StringVal("ami-abc123")
    ak := cty.StringVal("ami-abc123")
    sk := cty.StringVal("ami-abc123")
    region := cty.StringVal("ami-abc123")

    //创建privader
    privader := body.AppendNewBlock("provider", []string{"alicloud"}).Body()
    privader.SetAttributeValue("access_key", ak)
    privader.SetAttributeValue("secret_key", sk)
    privader.SetAttributeValue("region", region)

    // 创建一个resource元素,并且添加到body中
    resource := body.AppendNewBlock("resource", []string{"aws_instance", "web"}).Body()
    //resource.SetAttributeValue("ami", "ami-abc123")
    //resource.SetAttributeValue("instance_type", "t2.micro")
    resource.SetAttributeValue("ami", re)
    resource.SetAttributeValue("instance_type", re)

    // 创建一个output元素,并且添加到body中
    output := body.AppendNewBlock("output", []string{"web_ip"}).Body()
    //output.SetAttributeValue("value", "${aws_instance.web.private_ip}")
    output.SetAttributeValue("value", re)
    // 将内容写入到文件中
    _,err := f.WriteTo(os.Stdout)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    //fmt.Printf("n:%v\n",n)

        // 将格式化后的HCL代码写入文件
    err = ioutil.WriteFile("example.tf", f.Bytes(), 0644)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Terraform configuration updated successfully.")

执行结果:

# go run hclwrite2.go
provider "alicloud" {
  access_key = "ami-abc123"
  secret_key = "ami-abc123"
  region     = "ami-abc123"
}
resource "aws_instance" "web" {
  ami           = "ami-abc123"
  instance_type = "ami-abc123"
}
output "web_ip" {
  value = "ami-abc123"
}
Terraform configuration updated successfully.
# cat example.tf 
provider "alicloud" {
  access_key = "ami-abc123"
  secret_key = "ami-abc123"
  region     = "ami-abc123"
}
resource "aws_instance" "web" {
  ami           = "ami-abc123"
  instance_type = "ami-abc123"
}
output "web_ip" {
  value = "ami-abc123"
}
03-12 16:40