go生成terraform .tf配置

代码

复制代码
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"
}
相关推荐
花酒锄作田9 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237179 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian9 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript