Skip to content

Instantly share code, notes, and snippets.

@mizzy
Last active May 11, 2020 07:12
Show Gist options
  • Save mizzy/679c70c74b6b4e1f1f7597886e516df7 to your computer and use it in GitHub Desktop.
Save mizzy/679c70c74b6b4e1f1f7597886e516df7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"log"
"regexp"
"strings"
gohcl2 "github.com/hashicorp/hcl/v2/gohcl"
hcl2parse "github.com/hashicorp/hcl/v2/hclparse"
hcl2write "github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
type topLevel struct {
Resources []resource `hcl:"resource,block"`
}
type resource struct {
Type string `hcl:"type,label"`
Name string `hcl:"name,label"`
Config map[string]string `hcl:",remain"`
}
func main() {
parser := hcl2parse.NewParser()
p, parseDiags := parser.ParseHCLFile("project_iam_member.tf")
if parseDiags.HasErrors() {
log.Fatal(parseDiags.Error())
}
var raw topLevel
decodeDiags := gohcl2.DecodeBody(p.Body, nil, &raw)
if decodeDiags.HasErrors() {
log.Fatal(decodeDiags.Error())
}
w := hcl2write.NewFile()
rootBody := w.Body()
for _, r := range raw.Resources {
member := r.Config["member"]
member = strings.Replace(member, "serviceAccount:", "sa_", 1)
member = strings.Replace(member, "group:", "", 1)
member = strings.Replace(member, "user:", "", 1)
re := regexp.MustCompile("@.+$")
member = re.ReplaceAllString(member, "")
role := r.Config["role"]
role = strings.Replace(role, "projects/subier-dev/roles/", "", 1)
role = strings.Replace(role, "roles/", "", 1)
r.Name = fmt.Sprintf("%s_%s", member, role)
r.Name = strings.Replace(r.Name, ".", "_", -1)
resourceBlock := rootBody.AppendNewBlock("resource", []string{r.Type, r.Name})
resourceBody := resourceBlock.Body()
for k, v := range r.Config {
resourceBody.SetAttributeValue(k, cty.StringVal(v))
}
rootBody.AppendNewline()
}
err := ioutil.WriteFile("./out.tf", w.Bytes(), 0644)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment