首页 > 解决方案 > 在 golang 中使用 hclwrite 更改 Terraform 文件

问题描述

在我将Regex 模式与 terraform 模块代码相匹配的帖子之后,如果我们想对 terraform 文件进行外科手术写入,建议查看 golang 的 hclwrite 模块。

我花了一些时间学习 go 并在 go 中重写了 python 脚本。该脚本涵盖了它在 terraform 文件中查找带有字符串“模块”的文件的初始部分。由于 hclwrite 函数要求字节数组,我还将文件内容转换为字节数组。

我们需要获取一个以模块开头的 terraform 块,然后将其与其相应的资源元素一起写回。为此,我在字典中查询模块,然后写回资源。我们如何使用 hclwrite 做到这一点?以下是我使用的一些参考资料: 1.示例https://xuanwo.io/2020/04/13/get-started-with-hcl2/ 2. hcl 语法包https://godoc.org/github.com/ hashcorp/terraform/vendor/github.com/hashicorp/hcl/v2/hclsyntax#ParseConfig

改变

module mymodule {

}
To resource resource_name {
}

到目前为止我在 go 中编写的代码

func main() {
    var text string = "module"
    var dirpath = "<path to the files>/*.tf"
    //Get the terraform files in the directory and select files with string 'module'
    matches, _ := filepath.Glob(dirpath)
    for _, match := range matches {
        if IsExist(text, match) {
            fmt.Println(match)
            var chunk []byte

            file, err := os.Open(match)
            if err != nil {
                panic(err.Error())
            }
            defer file.Close()
            reader := bufio.NewReader(file)
            buffer := bytes.NewBuffer(make([]byte, 0))
            // var chunk []byte
            var eol bool
            var str_array []string
            for {
                if chunk, eol, err = reader.ReadLine(); err != nil {
                    break
                }
                buffer.Write(chunk)
                if !eol {
                    str_array = append(str_array, buffer.String())
                    buffer.Reset()
                }
            }

            if err == io.EOF {
                err = nil
            }

        }
    }
}

标签: go

解决方案


推荐阅读