github.com/wata727/tflint@v0.12.2-0.20191013070026-96dd0d36f385/tflint/terraform.go (about) 1 package tflint 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "log" 8 "os" 9 "path/filepath" 10 "strings" 11 12 "github.com/hashicorp/terraform/configs" 13 "github.com/hashicorp/terraform/terraform" 14 "github.com/zclconf/go-cty/cty" 15 ) 16 17 var defaultValuesFile = "terraform.tfvars" 18 19 // ParseTFVariables parses the passed Terraform variable CLI arguments, and returns terraform.InputValues 20 func ParseTFVariables(vars []string, declVars map[string]*configs.Variable) (terraform.InputValues, error) { 21 variables := make(terraform.InputValues) 22 for _, raw := range vars { 23 idx := strings.Index(raw, "=") 24 if idx == -1 { 25 return variables, fmt.Errorf("`%s` is invalid. Variables must be `key=value` format", raw) 26 } 27 name := raw[:idx] 28 rawVal := raw[idx+1:] 29 30 var mode configs.VariableParsingMode 31 declVar, declared := declVars[name] 32 if declared { 33 mode = declVar.ParsingMode 34 } else { 35 mode = configs.VariableParseLiteral 36 } 37 38 val, diags := mode.Parse(name, rawVal) 39 if diags.HasErrors() { 40 return variables, diags 41 } 42 43 variables[name] = &terraform.InputValue{ 44 Value: val, 45 SourceType: terraform.ValueFromCLIArg, 46 } 47 } 48 49 return variables, nil 50 } 51 52 func getTFDataDir() string { 53 dir := os.Getenv("TF_DATA_DIR") 54 if dir != "" { 55 log.Printf("[INFO] TF_DATA_DIR environment variable found: %s", dir) 56 } else { 57 dir = ".terraform" 58 } 59 60 return dir 61 } 62 63 func getTFModuleDir() string { 64 return filepath.Join(getTFDataDir(), "modules") 65 } 66 67 func getTFModuleManifestPath() string { 68 return filepath.Join(getTFModuleDir(), "modules.json") 69 } 70 71 func getTFWorkspace() string { 72 if envVar := os.Getenv("TF_WORKSPACE"); envVar != "" { 73 log.Printf("[INFO] TF_WORKSPACE environment variable found: %s", envVar) 74 return envVar 75 } 76 77 envData, _ := ioutil.ReadFile(filepath.Join(getTFDataDir(), "environment")) 78 current := string(bytes.TrimSpace(envData)) 79 if current != "" { 80 log.Printf("[INFO] environment file found: %s", current) 81 } else { 82 current = "default" 83 } 84 85 return current 86 } 87 88 func getTFEnvVariables() terraform.InputValues { 89 envVariables := make(terraform.InputValues) 90 for _, e := range os.Environ() { 91 idx := strings.Index(e, "=") 92 envKey := e[:idx] 93 envVal := e[idx+1:] 94 95 if strings.HasPrefix(envKey, "TF_VAR_") { 96 log.Printf("[INFO] TF_VAR_* environment variable found: key=%s", envKey) 97 varName := strings.Replace(envKey, "TF_VAR_", "", 1) 98 99 envVariables[varName] = &terraform.InputValue{ 100 Value: cty.StringVal(envVal), 101 SourceType: terraform.ValueFromEnvVar, 102 } 103 } 104 } 105 106 return envVariables 107 }