VariableValues is a helper function that converts a slice of TemplateVersionVariable into a map of cty.Value for use in coder/preview.
(vals []database.TemplateVersionVariable)
| 13 | // VariableValues is a helper function that converts a slice of TemplateVersionVariable |
| 14 | // into a map of cty.Value for use in coder/preview. |
| 15 | func VariableValues(vals []database.TemplateVersionVariable) (map[string]cty.Value, error) { |
| 16 | ctyVals := make(map[string]cty.Value, len(vals)) |
| 17 | for _, v := range vals { |
| 18 | value := v.Value |
| 19 | if value == "" && v.DefaultValue != "" { |
| 20 | value = v.DefaultValue |
| 21 | } |
| 22 | |
| 23 | if value == "" { |
| 24 | // Empty strings are unsupported I guess? |
| 25 | continue // omit non-set vals |
| 26 | } |
| 27 | |
| 28 | var err error |
| 29 | switch v.Type { |
| 30 | // Defaulting the empty type to "string" |
| 31 | // TODO: This does not match the terraform behavior, however it is too late |
| 32 | // at this point in the code to determine this, as the database type stores all values |
| 33 | // as strings. The code needs to be fixed in the `Parse` step of the provisioner. |
| 34 | // That step should determine the type of the variable correctly and store it in the database. |
| 35 | case "string", "": |
| 36 | ctyVals[v.Name] = cty.StringVal(value) |
| 37 | case "number": |
| 38 | ctyVals[v.Name], err = cty.ParseNumberVal(value) |
| 39 | if err != nil { |
| 40 | return nil, xerrors.Errorf("parse variable %q: %w", v.Name, err) |
| 41 | } |
| 42 | case "bool": |
| 43 | parsed, err := strconv.ParseBool(value) |
| 44 | if err != nil { |
| 45 | return nil, xerrors.Errorf("parse variable %q: %w", v.Name, err) |
| 46 | } |
| 47 | ctyVals[v.Name] = cty.BoolVal(parsed) |
| 48 | default: |
| 49 | // If it is a complex type, let the cty json code give it a try. |
| 50 | // TODO: Ideally we parse `list` & `map` and build the type ourselves. |
| 51 | ty, err := json.ImpliedType([]byte(value)) |
| 52 | if err != nil { |
| 53 | return nil, xerrors.Errorf("implied type for variable %q: %w", v.Name, err) |
| 54 | } |
| 55 | |
| 56 | jv, err := json.Unmarshal([]byte(value), ty) |
| 57 | if err != nil { |
| 58 | return nil, xerrors.Errorf("unmarshal variable %q: %w", v.Name, err) |
| 59 | } |
| 60 | ctyVals[v.Name] = jv |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return ctyVals, nil |
| 65 | } |
no test coverage detected