go - 在 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
}
}
}
}
解决方案
推荐阅读
- javascript - 获取对象的最大值(个数)
- javascript - 为什么当我在 div 中加载脚本时此函数停止工作?
- c# - 如何在 MDI 中正确显示 Windows 窗体应用程序中的子侧栏和子窗体?
- c# - 使用文件容器中包含的文件的文件路径,在 c++ 和 c# 中
- ios - 使用 UIView 扩展存储变量复制 UIView
- c++ - 为什么我不能从 QML 读取暴露的 C++ 数据?
- javascript - if 语句仅在 for 循环的索引 2 上执行
- ruby-on-rails - 如何将对象推入 Rails 5 中的 ActiveRecord::Relation
- android - 引起:org.gradle.internal.resolve.ModuleVersionResolveException:无法解析 com.android.support:multidex-instrumentation:1.0.2
- spring-boot - @SpringBootTest 和 @WebMvcTest 可以共存吗