iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > GO >如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?
  • 546
分享到

如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?

2024-02-09 11:02:16 546人浏览 安东尼
摘要

PHP小编柚子教你如何使用golang脚本修改TerrafORM(HCL格式)文件中的值。Terraform是一种基础设施即代码工具,可以帮助我们管理和自动化云基础设施。但是,如果我们

PHP小编柚子教你如何使用golang脚本修改TerrafORM(HCL格式)文件中的值。Terraform是一种基础设施即代码工具,可以帮助我们管理和自动化云基础设施。但是,如果我们需要频繁地修改Terraform文件中的某些值,手动操作将变得非常繁琐。因此,使用Golang脚本来修改Terraform文件中的值将会是一个更高效的方法。在本文中,我将向您展示如何使用Golang编写一个脚本来实现这一目标,以便您能够轻松地在Terraform文件中进行值的修改。

问题内容

我正在尝试对我拥有的 terraform 文件进行少量自动化,该文件定义了 Azure 网络安全组。本质上,我有一个网站和 ssh 访问,我只想允许我的公共 ip 地址,我可以从 icanhazip.com 获取该地址。我希望使用 golang 脚本将我的 ip 写入 .tf 文件的相关部分(本质上是设置 security_rule.source_address_prefixes 的值)。

我正在尝试在 golang 中使用 hclsimple 库,并尝试了 gohclhclwrite 等,但本质上我在将 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://www.php.cn/link/f56de5ef149cf0aedcc8f4797031e229 是不可能的(请参阅这里 https://www.php.cn/link/f56de5ef149cf0aedcc8f4797031e229/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 格式)文件中的值?的详细内容,更多请关注编程网其它相关文章!

您可能感兴趣的文档:

--结束END--

本文标题: 如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?

本文链接: https://www.lsjlt.com/news/562497.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何让 Golang 脚本修改 Terraform(HCL 格式)文件中的值?
    php小编柚子教你如何使用Golang脚本修改Terraform(HCL格式)文件中的值。Terraform是一种基础设施即代码工具,可以帮助我们管理和自动化云基础设施。但是,如果我们...
    99+
    2024-02-09
  • win7如何修改文件格式
    要修改文件的格式,你需要使用一个文件格式转换工具或者将文件保存为不同的格式。以下是在Windows 7中进行文件格式转换的一些常见方...
    99+
    2023-09-28
    win7
  • 如何使用python批量修改文本文件编码格式
    使用python批量修改文本文件编码格式 把文本文件的编码格式进行批量幻化,比如ascii, gb2312, utf8等,相互转化,字符集的大小来看,utf8>gb2312&g...
    99+
    2023-03-24
    python批量修改文本文件编码格式 python批量修改文件编码
  • 如何利用vbscript脚本修改文件内容
    这篇文章主要讲解了“如何利用vbscript脚本修改文件内容”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何利用vbscript脚本修改文件内容”吧!利用vbscript脚本修改文件内容,...
    99+
    2023-06-08
  • 如何在golang中修改文件内容
    今天编程网给大家带来了《如何在golang中修改文件内容》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支...
    99+
    2024-04-05
  • 如何用php修改中文编码格式
    这篇文章主要讲解了“如何用php修改中文编码格式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何用php修改中文编码格式”吧!一、中文编码方式的种类在介绍如何改变中文编码格式之前,需要先了...
    99+
    2023-07-05
  • 如何实现Shell脚本中非交互式修改密码
    本篇内容介绍了“如何实现Shell脚本中非交互式修改密码”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1:使用chpasswdchpassw...
    99+
    2023-06-09
  • 聊聊如何在Golang中修改配置文件
    在应用程序的开发过程中,有一个非常重要的文件——配置文件(configuration file)往往包含了各种参数和选项,以调整应用程序的行为和表现形式。常见的配置文件格式有ini、json、yaml等等。虽然配置文件对于应用程序的正确运行...
    99+
    2023-05-14
  • 详解如何在Golang中修改变量的值
    Golang是当今最为流行的编程语言之一,它具有简单易用、高效、安全等优点,使得它在应用开发领域里得到越来越广泛的应用。在程序开发过程中,我们经常需要改变变量的值,本文将介绍如何在Golang中改变变量的值以及相关的语法细节。一、变量的声明...
    99+
    2023-05-14
  • 如何让Vista中的Media Center支持更多文件格式及文件夹
    这篇文章将为大家详细讲解有关如何让Vista中的Media Center支持更多文件格式及文件夹,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。Media Center 中把媒体文件分为三类放...
    99+
    2023-06-14
  • php中如何让图片没有缓存文件格式
    本篇内容主要讲解“php中如何让图片没有缓存文件格式”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php中如何让图片没有缓存文件格式”吧!强制浏览器不缓存图片默认情况下,浏览器会缓存已经下载的图...
    99+
    2023-07-06
  • 如何修改php格式文件?步骤和技巧分享
    PHP是一种服务器端脚本语言,经常用于Web开发。如果您是一名PHP程序员或者想要在网站上使用PHP,您可能需要修改PHP格式文件。在本篇文章中,我们将探讨如何修改PHP格式文件的步骤和技巧。步骤一:了解PHP文件格式在您进行修改之前,您需...
    99+
    2023-05-14
    php
  • 如何编写Shell脚本批量修改文件后缀名代码
    本篇内容介绍了“如何编写Shell脚本批量修改文件后缀名代码”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!代码如下:#!/bin/basho...
    99+
    2023-06-09
  • 如何修改pdf文件中的文字
    本篇内容主要讲解“如何修改pdf文件中的文字”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何修改pdf文件中的文字”吧!修改pdf文件中的文字教程:要修改pdf文件,是要用pdf编辑器的。所以...
    99+
    2023-07-02
  • 如何使用golang中的os.Chmod函数修改文件的权限
    如何使用Golang中的os.Chmod函数修改文件权限文件权限是操作系统中非常重要的概念之一,它控制着文件在系统中的访问权限。在Golang中,可以使用os包中的Chmod函数来修改文件的权限。本文将介绍如何使用该函数来实现文件权限的修改...
    99+
    2023-11-18
    Golang osChmod 文件权限修改
  • 如何修改csv文件的编码形式
    不同的软件版本更改csv文件编码的位置不同,以下提供一种最简单的更改csv文件编码方法: csv文件右键打开方式,选择记事本,右下角即为当前的编码形式  以图所示:当前的编码形式为utf-8  2.更改编码形式 文件另存为,既可以在编码位...
    99+
    2023-09-13
    python 开发语言
  • 如何使用Java计算修改文件的MD5值
    目录什么是 MD5 ?MD5 的应用下载文件校验上传文件文件去重文件过滤修改文件的 MD5 值一个简单的计算 md5 的程序修改 MD5 值什么是 MD5 ? MD5(Message...
    99+
    2023-05-15
    JavaMD5值 java计算文件MD5值 java修改MD5值
  • Golang文件读取实战:如何应对不同格式的文件
    Golang是一种高效的编程语言,它可以处理各种数据类型和文件格式。在文件读取方面,Golang提供了多种方法,使我们能够应对各种文件格式的读取需求。本文将介绍如何在Golang中读取常见的几种文件格式,包括...
    99+
    2024-01-19
    Golang 文件读取 文件格式
  • Golang如何修改文件的编码?教程解析
    go 中修改文件编码的步骤:使用 ioutil.readfile 读取原始文件。将读取到的 []byte 转换为 string。设置新的编码(如 "utf-8")。使...
    99+
    2024-04-03
    golang 文件编码
  • 如何使用 JavaScript 修改 TextArea 中的文本
    JavaScript 是一种脚本语言,用于构建交互式的网页应用程序。TextArea 是一个常用的 HTML 元素,用于让用户输入大段文本。在开发网站和应用程序的过程中,JavaScript 可以用来操作 TextArea 中的文本内容,实...
    99+
    2023-05-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作