Skip to content

Instantly share code, notes, and snippets.

@cwgem
Created May 4, 2018 18:18
Show Gist options
  • Save cwgem/1111c220ad1d176f37849b40dbd2d6b4 to your computer and use it in GitHub Desktop.
Save cwgem/1111c220ad1d176f37849b40dbd2d6b4 to your computer and use it in GitHub Desktop.
Messing around with loading an HCL ast via finding tf files recursively in a directory passed in via args
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/hashicorp/hcl"
"github.com/hashicorp/hcl/hcl/ast"
)
func load_terraform(path string) (*ast.File, error) {
dat, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err)
return nil, err
}
ast, err := hcl.ParseBytes(dat)
if err != nil {
fmt.Println(err)
return nil, err
}
return ast, nil
}
func main() {
flag.Parse()
root := flag.Arg(0)
var results []*ast.File
err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
fi, err := os.Stat(path)
if err != nil {
fmt.Println(err)
return err
}
if fi.Mode().IsRegular() == true {
if filepath.Ext(path) == ".tf" {
tf, err := load_terraform(path)
if err != nil {
fmt.Println(err)
return err
}
results = append(results, tf)
}
}
return nil
})
fmt.Printf("Terraform files loaded is: %d\n", len(results))
if err != nil {
fmt.Println(err)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment