1 // The config package is responsible for loading and validating the
11 hcl2 "github.com/hashicorp/hcl2/hcl"
12 "github.com/hashicorp/hil/ast"
13 "github.com/hashicorp/terraform/helper/hilmapstructure"
14 "github.com/hashicorp/terraform/plugin/discovery"
15 "github.com/hashicorp/terraform/tfdiags"
16 "github.com/mitchellh/reflectwalk"
19 // NameRegexp is the regular expression that all names (modules, providers,
20 // resources, etc.) must follow.
21 var NameRegexp = regexp.MustCompile(`(?i)\A[A-Z0-9_][A-Z0-9\-\_]*\z`)
23 // Config is the configuration that comes from loading a collection
24 // of Terraform templates.
26 // Dir is the path to the directory where this configuration was
27 // loaded from. If it is blank, this configuration wasn't loaded from
28 // any meaningful directory.
34 ProviderConfigs []*ProviderConfig
40 // The fields below can be filled in by loaders for validation
45 // AtlasConfig is the configuration for building in HashiCorp's Atlas.
46 type AtlasConfig struct {
52 // Module is a module used within a configuration.
54 // This does not represent a module itself, this represents a module
55 // call-site within an existing configuration.
60 Providers map[string]string
64 // ProviderConfig is the configuration for a resource provider.
66 // For example, Terraform needs to set the AWS access keys for the AWS
68 type ProviderConfig struct {
75 // A resource represents a single Terraform resource in the configuration.
76 // A Terraform resource is something that supports some or all of the
77 // usual "create, read, update, delete" operations, depending on
79 type Resource struct {
80 Mode ResourceMode // which operations the resource supports
85 Provisioners []*Provisioner
88 Lifecycle ResourceLifecycle
91 // Copy returns a copy of this Resource. Helpful for avoiding shared
92 // config pointers across multiple pieces of the graph that need to do
94 func (r *Resource) Copy() *Resource {
99 RawCount: r.RawCount.Copy(),
100 RawConfig: r.RawConfig.Copy(),
101 Provisioners: make([]*Provisioner, 0, len(r.Provisioners)),
102 Provider: r.Provider,
103 DependsOn: make([]string, len(r.DependsOn)),
104 Lifecycle: *r.Lifecycle.Copy(),
106 for _, p := range r.Provisioners {
107 n.Provisioners = append(n.Provisioners, p.Copy())
109 copy(n.DependsOn, r.DependsOn)
113 // ResourceLifecycle is used to store the lifecycle tuning parameters
114 // to allow customized behavior
115 type ResourceLifecycle struct {
116 CreateBeforeDestroy bool `mapstructure:"create_before_destroy"`
117 PreventDestroy bool `mapstructure:"prevent_destroy"`
118 IgnoreChanges []string `mapstructure:"ignore_changes"`
121 // Copy returns a copy of this ResourceLifecycle
122 func (r *ResourceLifecycle) Copy() *ResourceLifecycle {
123 n := &ResourceLifecycle{
124 CreateBeforeDestroy: r.CreateBeforeDestroy,
125 PreventDestroy: r.PreventDestroy,
126 IgnoreChanges: make([]string, len(r.IgnoreChanges)),
128 copy(n.IgnoreChanges, r.IgnoreChanges)
132 // Provisioner is a configured provisioner step on a resource.
133 type Provisioner struct {
139 OnFailure ProvisionerOnFailure
142 // Copy returns a copy of this Provisioner
143 func (p *Provisioner) Copy() *Provisioner {
146 RawConfig: p.RawConfig.Copy(),
147 ConnInfo: p.ConnInfo.Copy(),
149 OnFailure: p.OnFailure,
153 // Variable is a module argument defined within the configuration.
154 type Variable struct {
156 DeclaredType string `mapstructure:"type"`
161 // Local is a local value defined within the configuration.
167 // Output is an output defined within the configuration. An output is
168 // resulting data that is highlighted by Terraform when finished. An
169 // output marked Sensitive will be output in a masked form following
170 // application, but will still be available in state.
179 // VariableType is the type of value a variable is holding, and returned
180 // by the Type() function on variables.
181 type VariableType byte
184 VariableTypeUnknown VariableType = iota
190 func (v VariableType) Printable() string {
192 case VariableTypeString:
194 case VariableTypeMap:
196 case VariableTypeList:
203 // ProviderConfigName returns the name of the provider configuration in
204 // the given mapping that maps to the proper provider configuration
205 // for this resource.
206 func ProviderConfigName(t string, pcs []*ProviderConfig) string {
208 for _, v := range pcs {
210 if strings.HasPrefix(t, k) && len(k) > len(lk) {
218 // A unique identifier for this module.
219 func (r *Module) Id() string {
220 return fmt.Sprintf("%s", r.Name)
223 // Count returns the count of this resource.
224 func (r *Resource) Count() (int, error) {
225 raw := r.RawCount.Value()
226 count, ok := r.RawCount.Value().(string)
228 return 0, fmt.Errorf(
229 "expected count to be a string or int, got %T", raw)
232 v, err := strconv.ParseInt(count, 0, 0)
234 return 0, fmt.Errorf(
235 "cannot parse %q as an integer",
243 // A unique identifier for this resource.
244 func (r *Resource) Id() string {
246 case ManagedResourceMode:
247 return fmt.Sprintf("%s.%s", r.Type, r.Name)
248 case DataResourceMode:
249 return fmt.Sprintf("data.%s.%s", r.Type, r.Name)
251 panic(fmt.Errorf("unknown resource mode %s", r.Mode))
255 // ProviderFullName returns the full name of the provider for this resource,
256 // which may either be specified explicitly using the "provider" meta-argument
257 // or implied by the prefix on the resource type name.
258 func (r *Resource) ProviderFullName() string {
259 return ResourceProviderFullName(r.Type, r.Provider)
262 // ResourceProviderFullName returns the full (dependable) name of the
263 // provider for a hypothetical resource with the given resource type and
264 // explicit provider string. If the explicit provider string is empty then
265 // the provider name is inferred from the resource type name.
266 func ResourceProviderFullName(resourceType, explicitProvider string) string {
267 if explicitProvider != "" {
268 // check for an explicit provider name, or return the original
269 parts := strings.SplitAfter(explicitProvider, "provider.")
270 return parts[len(parts)-1]
273 idx := strings.IndexRune(resourceType, '_')
275 // If no underscores, the resource name is assumed to be
276 // also the provider name, e.g. if the provider exposes
277 // only a single resource of each type.
281 return resourceType[:idx]
284 // Validate does some basic semantic checking of the configuration.
285 func (c *Config) Validate() tfdiags.Diagnostics {
290 var diags tfdiags.Diagnostics
292 for _, k := range c.unknownKeys {
293 diags = diags.Append(
294 fmt.Errorf("Unknown root level key: %s", k),
298 // Validate the Terraform config
299 if tf := c.Terraform; tf != nil {
300 errs := c.Terraform.Validate()
301 for _, err := range errs {
302 diags = diags.Append(err)
306 vars := c.InterpolatedVariables()
307 varMap := make(map[string]*Variable)
308 for _, v := range c.Variables {
309 if _, ok := varMap[v.Name]; ok {
310 diags = diags.Append(fmt.Errorf(
311 "Variable '%s': duplicate found. Variable names must be unique.",
319 for k, _ := range varMap {
320 if !NameRegexp.MatchString(k) {
321 diags = diags.Append(fmt.Errorf(
322 "variable %q: variable name must match regular expression %s",
328 for _, v := range c.Variables {
329 if v.Type() == VariableTypeUnknown {
330 diags = diags.Append(fmt.Errorf(
331 "Variable '%s': must be a string or a map",
338 fn := func(n ast.Node) (interface{}, error) {
339 // LiteralNode is a literal string (outside of a ${ ... } sequence).
340 // interpolationWalker skips most of these. but in particular it
341 // visits those that have escaped sequences (like $${foo}) as a
342 // signal that *some* processing is required on this string. For
343 // our purposes here though, this is fine and not an interpolation.
344 if _, ok := n.(*ast.LiteralNode); !ok {
350 w := &interpolationWalker{F: fn}
351 if v.Default != nil {
352 if err := reflectwalk.Walk(v.Default, w); err == nil {
354 diags = diags.Append(fmt.Errorf(
355 "variable %q: default may not contain interpolations",
363 // Check for references to user variables that do not actually
364 // exist and record those errors.
365 for source, vs := range vars {
366 for _, v := range vs {
367 uv, ok := v.(*UserVariable)
372 if _, ok := varMap[uv.Name]; !ok {
373 diags = diags.Append(fmt.Errorf(
374 "%s: unknown variable referenced: '%s'; define it with a 'variable' block",
382 // Check that all count variables are valid.
383 for source, vs := range vars {
384 for _, rawV := range vs {
385 switch v := rawV.(type) {
387 if v.Type == CountValueInvalid {
388 diags = diags.Append(fmt.Errorf(
389 "%s: invalid count variable: %s",
395 if v.Type == PathValueInvalid {
396 diags = diags.Append(fmt.Errorf(
397 "%s: invalid path variable: %s",
406 // Check that providers aren't declared multiple times and that their
407 // version constraints, where present, are syntactically valid.
408 providerSet := make(map[string]bool)
409 for _, p := range c.ProviderConfigs {
411 if _, ok := providerSet[name]; ok {
412 diags = diags.Append(fmt.Errorf(
413 "provider.%s: multiple configurations present; only one configuration is allowed per provider",
420 _, err := discovery.ConstraintStr(p.Version).Parse()
422 diags = diags.Append(&hcl2.Diagnostic{
423 Severity: hcl2.DiagError,
424 Summary: "Invalid provider version constraint",
426 "The value %q given for provider.%s is not a valid version constraint.",
429 // TODO: include a "Subject" source reference in here,
430 // once the config loader is able to retain source
431 // location information.
436 providerSet[name] = true
439 // Check that all references to modules are valid
440 modules := make(map[string]*Module)
441 dupped := make(map[string]struct{})
442 for _, m := range c.Modules {
443 // Check for duplicates
444 if _, ok := modules[m.Id()]; ok {
445 if _, ok := dupped[m.Id()]; !ok {
446 dupped[m.Id()] = struct{}{}
448 diags = diags.Append(fmt.Errorf(
449 "module %q: module repeated multiple times",
454 // Already seen this module, just skip it
460 // Check that the source has no interpolations
461 rc, err := NewRawConfig(map[string]interface{}{
465 diags = diags.Append(fmt.Errorf(
466 "module %q: module source error: %s",
469 } else if len(rc.Interpolations) > 0 {
470 diags = diags.Append(fmt.Errorf(
471 "module %q: module source cannot contain interpolations",
476 // Check that the name matches our regexp
477 if !NameRegexp.Match([]byte(m.Name)) {
478 diags = diags.Append(fmt.Errorf(
479 "module %q: module name must be a letter or underscore followed by only letters, numbers, dashes, and underscores",
484 // Check that the configuration can all be strings, lists or maps
485 raw := make(map[string]interface{})
486 for k, v := range m.RawConfig.Raw {
488 if err := hilmapstructure.WeakDecode(v, &strVal); err == nil {
493 var mapVal map[string]interface{}
494 if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil {
499 var sliceVal []interface{}
500 if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil {
505 diags = diags.Append(fmt.Errorf(
506 "module %q: argument %s must have a string, list, or map value",
511 // Check for invalid count variables
512 for _, v := range m.RawConfig.Variables {
515 diags = diags.Append(fmt.Errorf(
516 "module %q: count variables are only valid within resources",
520 diags = diags.Append(fmt.Errorf(
521 "module %q: self variables are only valid within resources",
527 // Update the raw configuration to only contain the string values
528 m.RawConfig, err = NewRawConfig(raw)
530 diags = diags.Append(fmt.Errorf(
531 "%s: can't initialize configuration: %s",
536 // check that all named providers actually exist
537 for _, p := range m.Providers {
539 diags = diags.Append(fmt.Errorf(
540 "module %q: cannot pass non-existent provider %q",
549 // Check that all variables for modules reference modules that
551 for source, vs := range vars {
552 for _, v := range vs {
553 mv, ok := v.(*ModuleVariable)
558 if _, ok := modules[mv.Name]; !ok {
559 diags = diags.Append(fmt.Errorf(
560 "%s: unknown module referenced: %s",
567 // Check that all references to resources are valid
568 resources := make(map[string]*Resource)
569 dupped = make(map[string]struct{})
570 for _, r := range c.Resources {
571 if _, ok := resources[r.Id()]; ok {
572 if _, ok := dupped[r.Id()]; !ok {
573 dupped[r.Id()] = struct{}{}
575 diags = diags.Append(fmt.Errorf(
576 "%s: resource repeated multiple times",
582 resources[r.Id()] = r
586 // Validate resources
587 for n, r := range resources {
588 // Verify count variables
589 for _, v := range r.RawCount.Variables {
592 diags = diags.Append(fmt.Errorf(
593 "%s: resource count can't reference count variable: %s",
596 case *SimpleVariable:
597 diags = diags.Append(fmt.Errorf(
598 "%s: resource count can't reference variable: %s",
603 case *ModuleVariable:
604 case *ResourceVariable:
605 case *TerraformVariable:
610 diags = diags.Append(fmt.Errorf(
611 "Internal error. Unknown type in count var in %s: %T",
617 if !r.RawCount.couldBeInteger() {
618 diags = diags.Append(fmt.Errorf(
619 "%s: resource count must be an integer", n,
624 // Validate DependsOn
625 for _, err := range c.validateDependsOn(n, r.DependsOn, resources, modules) {
626 diags = diags.Append(err)
629 // Verify provisioners
630 for _, p := range r.Provisioners {
631 // This validation checks that there are no splat variables
632 // referencing ourself. This currently is not allowed.
634 for _, v := range p.ConnInfo.Variables {
635 rv, ok := v.(*ResourceVariable)
640 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
641 diags = diags.Append(fmt.Errorf(
642 "%s: connection info cannot contain splat variable referencing itself",
649 for _, v := range p.RawConfig.Variables {
650 rv, ok := v.(*ResourceVariable)
655 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
656 diags = diags.Append(fmt.Errorf(
657 "%s: connection info cannot contain splat variable referencing itself",
664 // Check for invalid when/onFailure values, though this should be
665 // picked up by the loader we check here just in case.
666 if p.When == ProvisionerWhenInvalid {
667 diags = diags.Append(fmt.Errorf(
668 "%s: provisioner 'when' value is invalid", n,
671 if p.OnFailure == ProvisionerOnFailureInvalid {
672 diags = diags.Append(fmt.Errorf(
673 "%s: provisioner 'on_failure' value is invalid", n,
678 // Verify ignore_changes contains valid entries
679 for _, v := range r.Lifecycle.IgnoreChanges {
680 if strings.Contains(v, "*") && v != "*" {
681 diags = diags.Append(fmt.Errorf(
682 "%s: ignore_changes does not support using a partial string together with a wildcard: %s",
688 // Verify ignore_changes has no interpolations
689 rc, err := NewRawConfig(map[string]interface{}{
690 "root": r.Lifecycle.IgnoreChanges,
693 diags = diags.Append(fmt.Errorf(
694 "%s: lifecycle ignore_changes error: %s",
697 } else if len(rc.Interpolations) > 0 {
698 diags = diags.Append(fmt.Errorf(
699 "%s: lifecycle ignore_changes cannot contain interpolations",
704 // If it is a data source then it can't have provisioners
705 if r.Mode == DataResourceMode {
706 if _, ok := r.RawConfig.Raw["provisioner"]; ok {
707 diags = diags.Append(fmt.Errorf(
708 "%s: data sources cannot have provisioners",
715 for source, vs := range vars {
716 for _, v := range vs {
717 rv, ok := v.(*ResourceVariable)
722 id := rv.ResourceId()
723 if _, ok := resources[id]; !ok {
724 diags = diags.Append(fmt.Errorf(
725 "%s: unknown resource '%s' referenced in variable %s",
735 // Check that all locals are valid
737 found := make(map[string]struct{})
738 for _, l := range c.Locals {
739 if _, ok := found[l.Name]; ok {
740 diags = diags.Append(fmt.Errorf(
741 "%s: duplicate local. local value names must be unique",
746 found[l.Name] = struct{}{}
748 for _, v := range l.RawConfig.Variables {
749 if _, ok := v.(*CountVariable); ok {
750 diags = diags.Append(fmt.Errorf(
751 "local %s: count variables are only valid within resources", l.Name,
758 // Check that all outputs are valid
760 found := make(map[string]struct{})
761 for _, o := range c.Outputs {
762 // Verify the output is new
763 if _, ok := found[o.Name]; ok {
764 diags = diags.Append(fmt.Errorf(
765 "output %q: an output of this name was already defined",
770 found[o.Name] = struct{}{}
772 var invalidKeys []string
773 valueKeyFound := false
774 for k := range o.RawConfig.Raw {
779 if k == "sensitive" {
780 if sensitive, ok := o.RawConfig.config[k].(bool); ok {
787 diags = diags.Append(fmt.Errorf(
788 "output %q: value for 'sensitive' must be boolean",
793 if k == "description" {
794 if desc, ok := o.RawConfig.config[k].(string); ok {
799 diags = diags.Append(fmt.Errorf(
800 "output %q: value for 'description' must be string",
805 invalidKeys = append(invalidKeys, k)
807 if len(invalidKeys) > 0 {
808 diags = diags.Append(fmt.Errorf(
809 "output %q: invalid keys: %s",
810 o.Name, strings.Join(invalidKeys, ", "),
814 diags = diags.Append(fmt.Errorf(
815 "output %q: missing required 'value' argument", o.Name,
819 for _, v := range o.RawConfig.Variables {
820 if _, ok := v.(*CountVariable); ok {
821 diags = diags.Append(fmt.Errorf(
822 "output %q: count variables are only valid within resources",
828 // Detect a common mistake of using a "count"ed resource in
829 // an output value without using the splat or index form.
830 // Prior to 0.11 this error was silently ignored, but outputs
831 // now have their errors checked like all other contexts.
833 // TODO: Remove this in 0.12.
834 for _, v := range o.RawConfig.Variables {
835 rv, ok := v.(*ResourceVariable)
840 // If the variable seems to be treating the referenced
841 // resource as a singleton (no count specified) then
842 // we'll check to make sure it is indeed a singleton.
843 // It's a warning if not.
845 if rv.Multi || rv.Index != 0 {
846 // This reference is treating the resource as a
847 // multi-resource, so the warning doesn't apply.
851 for _, r := range c.Resources {
852 if r.Id() != rv.ResourceId() {
856 // We test specifically for the raw string "1" here
857 // because we _do_ want to generate this warning if
858 // the user has provided an expression that happens
859 // to return 1 right now, to catch situations where
860 // a count might dynamically be set to something
861 // other than 1 and thus splat syntax is still needed
863 if r.RawCount != nil && r.RawCount.Raw != nil && r.RawCount.Raw["count"] != "1" && rv.Field != "count" {
864 diags = diags.Append(tfdiags.SimpleWarning(fmt.Sprintf(
865 "output %q: must use splat syntax to access %s attribute %q, because it has \"count\" set; use %s.*.%s to obtain a list of the attributes across all instances",
876 // Validate the self variable
877 for source, rc := range c.rawConfigs() {
878 // Ignore provisioners. This is a pretty brittle way to do this,
879 // but better than also repeating all the resources.
880 if strings.Contains(source, "provision") {
884 for _, v := range rc.Variables {
885 if _, ok := v.(*SelfVariable); ok {
886 diags = diags.Append(fmt.Errorf(
887 "%s: cannot contain self-reference %s",
897 // InterpolatedVariables is a helper that returns a mapping of all the interpolated
898 // variables within the configuration. This is used to verify references
899 // are valid in the Validate step.
900 func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable {
901 result := make(map[string][]InterpolatedVariable)
902 for source, rc := range c.rawConfigs() {
903 for _, v := range rc.Variables {
904 result[source] = append(result[source], v)
910 // rawConfigs returns all of the RawConfigs that are available keyed by
911 // a human-friendly source.
912 func (c *Config) rawConfigs() map[string]*RawConfig {
913 result := make(map[string]*RawConfig)
914 for _, m := range c.Modules {
915 source := fmt.Sprintf("module '%s'", m.Name)
916 result[source] = m.RawConfig
919 for _, pc := range c.ProviderConfigs {
920 source := fmt.Sprintf("provider config '%s'", pc.Name)
921 result[source] = pc.RawConfig
924 for _, rc := range c.Resources {
925 source := fmt.Sprintf("resource '%s'", rc.Id())
926 result[source+" count"] = rc.RawCount
927 result[source+" config"] = rc.RawConfig
929 for i, p := range rc.Provisioners {
930 subsource := fmt.Sprintf(
931 "%s provisioner %s (#%d)",
933 result[subsource] = p.RawConfig
937 for _, o := range c.Outputs {
938 source := fmt.Sprintf("output '%s'", o.Name)
939 result[source] = o.RawConfig
945 func (c *Config) validateDependsOn(
948 resources map[string]*Resource,
949 modules map[string]*Module) []error {
950 // Verify depends on points to resources that all exist
952 for _, d := range v {
953 // Check if we contain interpolations
954 rc, err := NewRawConfig(map[string]interface{}{
957 if err == nil && len(rc.Variables) > 0 {
958 errs = append(errs, fmt.Errorf(
959 "%s: depends on value cannot contain interpolations: %s",
964 // If it is a module, verify it is a module
965 if strings.HasPrefix(d, "module.") {
966 name := d[len("module."):]
967 if _, ok := modules[name]; !ok {
968 errs = append(errs, fmt.Errorf(
969 "%s: resource depends on non-existent module '%s'",
977 if _, ok := resources[d]; !ok {
978 errs = append(errs, fmt.Errorf(
979 "%s: resource depends on non-existent resource '%s'",
987 func (m *Module) mergerName() string {
991 func (m *Module) mergerMerge(other merger) merger {
992 m2 := other.(*Module)
995 result.Name = m2.Name
996 result.RawConfig = result.RawConfig.merge(m2.RawConfig)
999 result.Source = m2.Source
1005 func (o *Output) mergerName() string {
1009 func (o *Output) mergerMerge(m merger) merger {
1013 result.Name = o2.Name
1014 result.Description = o2.Description
1015 result.RawConfig = result.RawConfig.merge(o2.RawConfig)
1016 result.Sensitive = o2.Sensitive
1017 result.DependsOn = o2.DependsOn
1022 func (c *ProviderConfig) GoString() string {
1023 return fmt.Sprintf("*%#v", *c)
1026 func (c *ProviderConfig) FullName() string {
1031 return fmt.Sprintf("%s.%s", c.Name, c.Alias)
1034 func (c *ProviderConfig) mergerName() string {
1038 func (c *ProviderConfig) mergerMerge(m merger) merger {
1039 c2 := m.(*ProviderConfig)
1042 result.Name = c2.Name
1043 result.RawConfig = result.RawConfig.merge(c2.RawConfig)
1046 result.Alias = c2.Alias
1052 func (r *Resource) mergerName() string {
1056 func (r *Resource) mergerMerge(m merger) merger {
1060 result.Mode = r2.Mode
1061 result.Name = r2.Name
1062 result.Type = r2.Type
1063 result.RawConfig = result.RawConfig.merge(r2.RawConfig)
1065 if r2.RawCount.Value() != "1" {
1066 result.RawCount = r2.RawCount
1069 if len(r2.Provisioners) > 0 {
1070 result.Provisioners = r2.Provisioners
1076 // Merge merges two variables to create a new third variable.
1077 func (v *Variable) Merge(v2 *Variable) *Variable {
1078 // Shallow copy the variable
1081 // The names should be the same, but the second name always wins.
1082 result.Name = v2.Name
1084 if v2.DeclaredType != "" {
1085 result.DeclaredType = v2.DeclaredType
1087 if v2.Default != nil {
1088 result.Default = v2.Default
1090 if v2.Description != "" {
1091 result.Description = v2.Description
1097 var typeStringMap = map[string]VariableType{
1098 "string": VariableTypeString,
1099 "map": VariableTypeMap,
1100 "list": VariableTypeList,
1103 // Type returns the type of variable this is.
1104 func (v *Variable) Type() VariableType {
1105 if v.DeclaredType != "" {
1106 declaredType, ok := typeStringMap[v.DeclaredType]
1108 return VariableTypeUnknown
1114 return v.inferTypeFromDefault()
1117 // ValidateTypeAndDefault ensures that default variable value is compatible
1118 // with the declared type (if one exists), and that the type is one which is
1119 // known to Terraform
1120 func (v *Variable) ValidateTypeAndDefault() error {
1121 // If an explicit type is declared, ensure it is valid
1122 if v.DeclaredType != "" {
1123 if _, ok := typeStringMap[v.DeclaredType]; !ok {
1124 validTypes := []string{}
1125 for k := range typeStringMap {
1126 validTypes = append(validTypes, k)
1129 "Variable '%s' type must be one of [%s] - '%s' is not a valid type",
1131 strings.Join(validTypes, ", "),
1137 if v.DeclaredType == "" || v.Default == nil {
1141 if v.inferTypeFromDefault() != v.Type() {
1142 return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')",
1143 v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable())
1149 func (v *Variable) mergerName() string {
1153 func (v *Variable) mergerMerge(m merger) merger {
1154 return v.Merge(m.(*Variable))
1157 // Required tests whether a variable is required or not.
1158 func (v *Variable) Required() bool {
1159 return v.Default == nil
1162 // inferTypeFromDefault contains the logic for the old method of inferring
1163 // variable types - we can also use this for validating that the declared
1164 // type matches the type of the default value
1165 func (v *Variable) inferTypeFromDefault() VariableType {
1166 if v.Default == nil {
1167 return VariableTypeString
1171 if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil {
1173 return VariableTypeString
1176 var m map[string]interface{}
1177 if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil {
1179 return VariableTypeMap
1183 if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil {
1185 return VariableTypeList
1188 return VariableTypeUnknown
1191 func (m ResourceMode) Taintable() bool {
1193 case ManagedResourceMode:
1195 case DataResourceMode:
1198 panic(fmt.Errorf("unsupported ResourceMode value %s", m))