如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
我正在尝试对我拥有的 terraform 文件进行少量自动化,该文件定义了 azure 网络安全组。本质上,我有一个网站和 ssh 访问,我只想允许我的公共 ip 地址,我可以从 icanhazip.com 获取该地址。我希望使用 golang 脚本将我的 ip 写入 .tf 文件的相关部分(本质上是设置 security_rule.source_address_prefixes 的值)。
我正在尝试在 golang 中使用 hclsimple 库,并尝试了 gohcl、hclwrite 等,但本质上我在将 hcl 文件转换为 golang 结构方面没有取得任何进展。
我的 terraform 文件(我相信是 hcl 格式)如下:
resource "azurerm_network_security_group" "my_nsg" {
name = "my_nsg"
location = "loc"
resource_group_name = "rgname"
security_rule = [
{
access = "deny"
description = "desc"
destination_address_prefix = "*"
destination_address_prefixes = []
destination_application_security_group_ids = []
destination_port_range = ""
destination_port_ranges = [
"123",
"456",
"789",
"1001",
]
direction = "inbound"
name = "allowinboundthing"
priority = 100
protocol = "*"
source_address_prefix = "*"
source_address_prefixes = [
# obtain from icanhazip.com
"1.2.3.4"
]
source_application_security_group_ids = []
source_port_range = "*"
source_port_ranges = []
},
{
access = "allow"
description = "grant acccess to app"
destination_address_prefix = "*"
destination_address_prefixes = []
destination_application_security_group_ids = []
destination_port_range = ""
destination_port_ranges = [
"443",
"80",
]
direction = "inbound"
name = "allowipinbound"
priority = 200
protocol = "*"
source_address_prefix = ""
source_address_prefixes = [
# obtain from icanhazip.com
"1.2.3.4"
]
source_application_security_group_ids = []
source_port_range = "*"
source_port_ranges = []
}
]
}
这是我用我的 golang 脚本所得到的,试图将上述数据表示为结构,然后解码 .tf 文件本身(我从 hclsimple 本地复制了几个方法,以便拥有它按照其文档中的建议解码 .tf 文件。
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsimple"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/json"
)
type config struct {
networksecuritygroup []networksecuritygroup `hcl:"resource,block"`
}
type networksecuritygroup struct {
type string `hcl:"azurerm_network_security_group,label"`
name string `hcl:"mick-linux3-nsg,label"`
nameattr string `hcl:"name"`
location string `hcl:"location"`
resourcegroupname string `hcl:"resource_group_name"`
securityrule []securityrule `hcl:"security_rule,block"`
}
type securityrule struct {
access string `hcl:"access"`
description string `hcl:"description"`
destinationaddressprefix string `hcl:"destination_address_prefix"`
destinationaddressprefixes []string `hcl:"destination_address_prefixes"`
destinationapplicationsecuritygroupids []string `hcl:"destination_application_security_group_ids"`
destinationportrange string `hcl:"destination_port_range"`
destinationportranges []string `hcl:"destination_port_ranges"`
direction string `hcl:"direction"`
name string `hcl:"name"`
priority int `hcl:"priority"`
protocol string `hcl:"protocol"`
sourceaddressprefix string `hcl:"source_address_prefix"`
sourceaddressprefixes []string `hcl:"source_address_prefixes"`
sourceapplicationsecuritygroupids []string `hcl:"source_application_security_group_ids"`
sourceportrange string `hcl:"source_port_range"`
sourceportranges []string `hcl:"source_port_ranges"`
}
func main() {
// lets pass this in as a param?
configfilepath := "nsg.tf"
// create new config struct
var config config
// this decodes the tf file into the config struct, and hydrates the values
err := mydecodefile(configfilepath, nil, &config)
if err != nil {
log.fatalf("failed to load configuration: %s", err)
}
log.printf("configuration is %#v", config)
// let's read in the file contents
file, err := os.open(configfilepath)
if err != nil {
fmt.printf("failed to read file: %v\n", err)
return
}
defer file.close()
// read the file and output as a []bytes
bytes, err := io.readall(file)
if err != nil {
fmt.println("error reading file:", err)
return
}
// parse, decode and evaluate the config of the .tf file
hclsimple.decode(configfilepath, bytes, nil, &config)
// iterate through the rules until we find one with
// description = "grant acccess to flask app"
// code go here
for _, nsg := range config.networksecuritygroup {
fmt.printf("security rule: %s", nsg.securityrule)
}
}
// basically copied from here https://github.com/hashicorp/hcl/blob/v2.16.2/hclsimple/hclsimple.go#l59
// but modified to handle .tf files too
func mydecode(filename string, src []byte, ctx *hcl.evalcontext, target interface{}) error {
var file *hcl.file
var diags hcl.diagnostics
switch suffix := strings.tolower(filepath.ext(filename)); suffix {
case ".tf":
file, diags = hclsyntax.parseconfig(src, filename, hcl.pos{line: 1, column: 1})
case ".hcl":
file, diags = hclsyntax.parseconfig(src, filename, hcl.pos{line: 1, column: 1})
case ".json":
file, diags = json.parse(src, filename)
default:
diags = diags.append(&hcl.diagnostic{
severity: hcl.diagerror,
summary: "unsupported file format",
detail: fmt.sprintf("cannot read from %s: unrecognized file format suffix %q.", filename, suffix),
})
return diags
}
if diags.haserrors() {
return diags
}
diags = gohcl.decodebody(file.body, ctx, target)
if diags.haserrors() {
return diags
}
return nil
}
// taken from here https://github.com/hashicorp/hcl/blob/v2.16.2/hclsimple/hclsimple.go#l89
func mydecodefile(filename string, ctx *hcl.evalcontext, target interface{}) error {
src, err := ioutil.readfile(filename)
if err != nil {
if os.isnotexist(err) {
return hcl.diagnostics{
{
severity: hcl.diagerror,
summary: "configuration file not found",
detail: fmt.sprintf("the configuration file %s does not exist.", filename),
},
}
}
return hcl.diagnostics{
{
severity: hcl.diagerror,
summary: "failed to read configuration",
detail: fmt.sprintf("can't read %s: %s.", filename, err),
},
}
}
return mydecode(filename, src, ctx, target)
}
当我运行代码时,本质上我正在努力定义 networksecuritygroup.securityrule,并使用上述代码收到以下错误:
2023/05/24 11:42:11 Failed to load configuration: nsg.tf:6,3-16: Unsupported argument; An argument named "security_rule" is not expected here. Did you mean to define a block of type "security_rule"? exit status 1
非常感谢任何建议
正确答案
因此,目前 https://github.com/minamijoyo/hcledit 是不可能的(请参阅这里 https://github.com/minamijoyo/hcledit/issues/50 - 这个建议 hclwrite 本身需要进行更改以方便)
所以我按照@martin atkins 的建议进行了解决:
我创建了一个包含 locals 变量的 locals.tf 文件,然后我在 nsg 安全规则中引用该变量:
locals {
my_ip = "1.2.3.4"
}
现在我只需获取我的 ip 并使用 sed 更新 locals.tf 文件中的值
my_ip=$(curl -s -4 icanhazip.com) sed -i "s|my_ip = \".*\"|my_ip = \"$my_ip\"|" locals.tf
以上就是《如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?》的详细内容,更多关于的资料请关注golang学习网公众号!
Spring Boot Rest常用框架注解有哪些
- 上一篇
- Spring Boot Rest常用框架注解有哪些
- 下一篇
- GoLang 中的时间戳和时区
-
- Golang · Go问答 | 1小时前 | Go问答 · URL Go net/url RawPath EscapedPath
- Go url.RawPath 设置后为什么可能被 EscapedPath 忽略
- 370浏览 收藏
-
- Golang · Go问答 | 2小时前 | Go问答 · Go url.JoinPath PathEscape RawPath
- Go url.JoinPath 为什么会转义某些路径字符
- 140浏览 收藏
-
- Golang · Go问答 | 6小时前 |
- Go MaxBytesReader 超限后为什么还需要处理连接状态
- 399浏览 收藏
-
- Golang · Go问答 | 6小时前 |
- Go ResponseController Flush 为什么可能返回 ErrNotSupported
- 197浏览 收藏
-
- Golang · Go问答 | 7小时前 |
- Go multipart.FileHeader Filename 为什么不能直接拼接本地路径
- 412浏览 收藏
-
- Golang · Go问答 | 7小时前 |
- Go multipart ReadForm 为什么仍会在内存保留字段值
- 202浏览 收藏
-
- Golang · Go问答 | 7小时前 | go · Go multipart/form-data mime/multipart SetBoundary
- Go multipart.SetBoundary 为什么必须在创建 Part 前调用
- 284浏览 收藏
-
- Golang · Go问答 | 8小时前 |
- Go multipart NextPart 为什么会自动解码 quoted-printable
- 474浏览 收藏
-
- Golang · Go问答 | 8小时前 |
- Go slog.WithGroup 空组名为什么只做内联分组
- 260浏览 收藏
-
- Golang · Go问答 | 8小时前 |
- Go slog LevelVar 修改后为什么旧 Handler 也会生效
- 193浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 253次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 298次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 267次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 248次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 54次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
