首頁  >  文章  >  後端開發  >  如何讓 Golang 腳本修改 Terraform(HCL 格式)檔案中的值?

如何讓 Golang 腳本修改 Terraform(HCL 格式)檔案中的值?

WBOY
WBOY轉載
2024-02-09 12:06:28863瀏覽

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

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 格式)檔案中的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除