github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/helper/variables/flag_file.go (about) 1 package variables 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 7 "github.com/hashicorp/hcl" 8 "github.com/mitchellh/go-homedir" 9 ) 10 11 // FlagFile is a flag.Value implementation for parsing user variables 12 // from the command line in the form of files. i.e. '-var-file=foo' 13 type FlagFile map[string]interface{} 14 15 func (v *FlagFile) String() string { 16 return "" 17 } 18 19 func (v *FlagFile) Set(raw string) error { 20 vs, err := loadKVFile(raw) 21 if err != nil { 22 return err 23 } 24 25 *v = Merge(*v, vs) 26 return nil 27 } 28 29 func loadKVFile(rawPath string) (map[string]interface{}, error) { 30 path, err := homedir.Expand(rawPath) 31 if err != nil { 32 return nil, fmt.Errorf( 33 "Error expanding path: %s", err) 34 } 35 36 // Read the HCL file and prepare for parsing 37 d, err := ioutil.ReadFile(path) 38 if err != nil { 39 return nil, fmt.Errorf( 40 "Error reading %s: %s", path, err) 41 } 42 43 // Parse it 44 obj, err := hcl.Parse(string(d)) 45 if err != nil { 46 return nil, fmt.Errorf( 47 "Error parsing %s: %s", path, err) 48 } 49 50 var result map[string]interface{} 51 if err := hcl.DecodeObject(&result, obj); err != nil { 52 return nil, fmt.Errorf( 53 "Error decoding Terraform vars file: %s\n\n"+ 54 "The vars file should be in the format of `key = \"value\"`.\n"+ 55 "Decoding errors are usually caused by an invalid format.", 56 err) 57 } 58 59 err = flattenMultiMaps(result) 60 if err != nil { 61 return nil, err 62 } 63 64 return result, nil 65 }