|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "html/template" |
| 6 | + "os" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +var replacer *strings.Replacer |
| 12 | + |
| 13 | +func init() { |
| 14 | + replacer = strings.NewReplacer(":", ".", |
| 15 | + "]", "", |
| 16 | + "}", "", |
| 17 | + "{", "", |
| 18 | + "\"", "", |
| 19 | + ")", "", |
| 20 | + "(", "", |
| 21 | + "[", "", |
| 22 | + ",", "", |
| 23 | + "var.", "", |
| 24 | + " ", "", |
| 25 | + ) |
| 26 | +} |
| 27 | + |
| 28 | +var varTemplate = template.Must(template.New("var_file").Parse(`{{ range . }} variable "{{ . }}" { |
| 29 | + description = "" |
| 30 | +} |
| 31 | +{{end}} |
| 32 | +`)) |
| 33 | + |
| 34 | +var var_prefix = "var." |
| 35 | + |
| 36 | +type TerraformVars struct { |
| 37 | + Variables []string |
| 38 | +} |
| 39 | + |
| 40 | +func contains(slice []string, value string) bool { |
| 41 | + if len(slice) == 0 { |
| 42 | + return false |
| 43 | + } |
| 44 | + for _, s := range slice { |
| 45 | + if value == s { |
| 46 | + return true |
| 47 | + } |
| 48 | + } |
| 49 | + return false |
| 50 | +} |
| 51 | + |
| 52 | +func main() { |
| 53 | + var parsed_vars []string |
| 54 | + fileHandle, _ := os.Open("test.tf") |
| 55 | + defer fileHandle.Close() |
| 56 | + fileScanner := bufio.NewScanner(fileHandle) |
| 57 | + |
| 58 | + for fileScanner.Scan() { |
| 59 | + if strings.Contains(fileScanner.Text(), var_prefix) { |
| 60 | + pattern := regexp.MustCompile(`var.([a-z?_]+)`) |
| 61 | + match := pattern.FindAllStringSubmatch(fileScanner.Text(), 1) |
| 62 | + if len(match) != 0 { |
| 63 | + res := replacer.Replace(match[0][0]) |
| 64 | + if !contains(parsed_vars, res) { |
| 65 | + parsed_vars = append(parsed_vars, res) |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + err := varTemplate.Execute(os.Stdout, parsed_vars) |
| 71 | + if err != nil { |
| 72 | + panic(err) |
| 73 | + } |
| 74 | +} |
0 commit comments