Skip to content

Instantly share code, notes, and snippets.

@mizzy
Created May 29, 2020 07:05
Show Gist options
  • Save mizzy/23bf3b6c355c3273060d04c268219ab7 to your computer and use it in GitHub Desktop.
Save mizzy/23bf3b6c355c3273060d04c268219ab7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
gohcl2 "github.com/hashicorp/hcl/v2/gohcl"
hcl2parse "github.com/hashicorp/hcl/v2/hclparse"
)
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() {
files := []string{
"project_iam_member.tf",
"project_iam_custom_role.tf",
"service_account.tf",
}
for _, f := range files {
parser := hcl2parse.NewParser()
p, parseDiags := parser.ParseHCLFile(f)
if parseDiags.HasErrors() {
log.Fatal(parseDiags.Error())
}
var raw topLevel
decodeDiags := gohcl2.DecodeBody(p.Body, nil, &raw)
if decodeDiags.HasErrors() {
log.Fatal(decodeDiags.Error())
}
for _, r := range raw.Resources {
fmt.Printf("terraform import %s.%s ", r.Type, r.Name)
if r.Type == "google_project_iam_member" {
fmt.Printf("\"%s %s %s\"\n", r.Config["project"], r.Config["role"], r.Config["member"])
} else if r.Type == "google_project_iam_custom_role" {
fmt.Printf("projects/%s/roles/%s\n", r.Config["project"], r.Config["role_id"])
} else if r.Type == "google_service_account" {
fmt.Printf("projects/%s/serviceAccounts/%[email protected]\n", r.Config["project"], r.Config["account_id"])
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment