在Go中搜索和更新HCL中的字符串

时间:2018-05-07 17:39:16

标签: go hashicorp-vault hcl

嘿伙计们,我遇到了一个路障,试图弄清楚如何搜索我们所有的service/policy_names以确保他们具备某些能力。

假设我有类似以下的保险库政策

bash-4.4$ vault policy read service/admin
# Token policies
path "/auth/token/create" {
    capabilities = ["create", "update", "sudo"]
}

path "/auth/token/lookup" {
    capabilities = ["create", "update"]
}

path "/auth/token/renew" {
    capabilities = ["create", "update"]
}

path "/auth/token/revoke" {
    capabilities = ["create", "update"]
}

# View system policies
path "/sys/policy" {
    capabilities = ["read"]
}

# Allow full access to interact with all secrets
path "secret/*" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

我正在尝试扫描每个策略,如果路径没有正确的功能,请创建一个具有正确功能的新文件并保存。我被困在试图扫描每条路径并且有点熄灭。希望有人可以帮助或推荐一种更健全的方法。以上内容将保存到新文件service_admin.hcl,如下所示

bash-4.4$ less service_admin.hcl
# Token policies
path "/auth/token/create" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

path "/auth/token/lookup" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

path "/auth/token/renew" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

path "/auth/token/revoke" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

# View system policies
path "/sys/policy" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

# Allow full access to interact with all secrets
path "secret/*" {
    capabilities = ["create", "read", "update", "delete", "list"]
}

我到目前为止的代码如下,我选择了go因为我认为HCL库会帮助我,但我很难使用它。

package main

import (
   "github.com/hashicorp/vault/api"
   "log"
   "regexp"
)

func main() {
   cfg := api.DefaultConfig()
   cfg.Address = "http://localhost:8200"

   client, err := api.NewClient(cfg)
   if err != nil {
      log.Fatal(err)
   }

   client.SetToken("xxx")

   policies, err := client.Sys().ListPolicies()
   if err != nil {
      log.Fatal(err)
   }


   var listPolicies []string
   for _, policy := range policies {
      matched, _ := regexp.MatchString("^service", policy)
      if matched {
         listPolicies = append(listPolicies, policy)
      }
   }

   for _, policy := range listPolicies {
      policyContents, _ := client.Sys().GetPolicy(policy)

      // parse := hcl.Parse(policyContents) // ????
      // Does each `path` have `capabilities = ["create", "read", "update", "delete", "list"]`
      log.Println(policyContents)

      break
   }
}

0 个答案:

没有答案