Created
May 20, 2024 21:15
-
-
Save HackToHell/9f48ca088a46a28044104d96781d6cbe to your computer and use it in GitHub Desktop.
Split each block of terraform hcl2 into individual files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"github.com/hashicorp/hcl/v2" | |
"os" | |
"path/filepath" | |
"github.com/hashicorp/hcl/v2/hclwrite" | |
) | |
func main() { | |
// Define command-line flags for input file and output directory | |
inputFile := flag.String("input", "", "Path to the input HCL file") | |
outputDir := flag.String("output", "", "Directory to save individual HCL block files") | |
flag.Parse() | |
// Check if the input file and output directory are provided | |
if *inputFile == "" || *outputDir == "" { | |
fmt.Println("Usage: go run main.go -input=<input-file> -output=<output-dir>") | |
return | |
} | |
// Create the output directory if it does not exist | |
if err := os.MkdirAll(*outputDir, os.ModePerm); err != nil { | |
fmt.Printf("Error creating output directory: %v\n", err) | |
return | |
} | |
// read *inputFile and make it into a bytearray | |
file, err := os.ReadFile(*inputFile) | |
if err != nil { | |
fmt.Printf("Error reading input file: %v\n", err) | |
return | |
} | |
f, diags := hclwrite.ParseConfig(file, "example.tf", hcl.Pos{Line: 1, Column: 1}) | |
if diags.HasErrors() { | |
fmt.Printf("Failed to parse HCL file: %v\n", diags) | |
return | |
} | |
// Iterate over the blocks and write each to a separate file | |
for i, block := range f.Body().Blocks() { | |
blockFile := hclwrite.NewEmptyFile() | |
blockFile.Body().AppendBlock(block) | |
outputFile := filepath.Join(*outputDir, fmt.Sprintf("block_%d.hcl", i+1)) | |
if err := os.WriteFile(outputFile, blockFile.Bytes(), 0644); err != nil { | |
fmt.Printf("Error writing block file %s: %v\n", outputFile, err) | |
return | |
} | |
} | |
fmt.Println("HCL blocks have been successfully split into individual files.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment