github.com/partitio/terraform@v0.11.12-beta1/config/config.go (about)

     1  // The config package is responsible for loading and validating the
     2  // configuration.
     3  package config
     4  
     5  import (
     6  	"fmt"
     7  	"regexp"
     8  	"strconv"
     9  	"strings"
    10  
    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"
    17  )
    18  
    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`)
    22  
    23  // Config is the configuration that comes from loading a collection
    24  // of Terraform templates.
    25  type Config struct {
    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.
    29  	Dir string
    30  
    31  	Terraform       *Terraform
    32  	Atlas           *AtlasConfig
    33  	Modules         []*Module
    34  	ProviderConfigs []*ProviderConfig
    35  	Resources       []*Resource
    36  	Variables       []*Variable
    37  	Locals          []*Local
    38  	Outputs         []*Output
    39  
    40  	// The fields below can be filled in by loaders for validation
    41  	// purposes.
    42  	unknownKeys []string
    43  }
    44  
    45  // AtlasConfig is the configuration for building in HashiCorp's Atlas.
    46  type AtlasConfig struct {
    47  	Name    string
    48  	Include []string
    49  	Exclude []string
    50  }
    51  
    52  // Module is a module used within a configuration.
    53  //
    54  // This does not represent a module itself, this represents a module
    55  // call-site within an existing configuration.
    56  type Module struct {
    57  	Name      string
    58  	Source    string
    59  	Version   string
    60  	Providers map[string]string
    61  	RawConfig *RawConfig
    62  }
    63  
    64  // ProviderConfig is the configuration for a resource provider.
    65  //
    66  // For example, Terraform needs to set the AWS access keys for the AWS
    67  // resource provider.
    68  type ProviderConfig struct {
    69  	Name      string
    70  	Alias     string
    71  	Version   string
    72  	RawConfig *RawConfig
    73  }
    74  
    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
    78  // the given Mode.
    79  type Resource struct {
    80  	Mode         ResourceMode // which operations the resource supports
    81  	Name         string
    82  	Type         string
    83  	RawCount     *RawConfig
    84  	RawConfig    *RawConfig
    85  	Provisioners []*Provisioner
    86  	Provider     string
    87  	DependsOn    []string
    88  	Lifecycle    ResourceLifecycle
    89  }
    90  
    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
    93  // interpolation.
    94  func (r *Resource) Copy() *Resource {
    95  	n := &Resource{
    96  		Mode:         r.Mode,
    97  		Name:         r.Name,
    98  		Type:         r.Type,
    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(),
   105  	}
   106  	for _, p := range r.Provisioners {
   107  		n.Provisioners = append(n.Provisioners, p.Copy())
   108  	}
   109  	copy(n.DependsOn, r.DependsOn)
   110  	return n
   111  }
   112  
   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"`
   119  }
   120  
   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)),
   127  	}
   128  	copy(n.IgnoreChanges, r.IgnoreChanges)
   129  	return n
   130  }
   131  
   132  // Provisioner is a configured provisioner step on a resource.
   133  type Provisioner struct {
   134  	Type      string
   135  	RawConfig *RawConfig
   136  	ConnInfo  *RawConfig
   137  
   138  	When      ProvisionerWhen
   139  	OnFailure ProvisionerOnFailure
   140  }
   141  
   142  // Copy returns a copy of this Provisioner
   143  func (p *Provisioner) Copy() *Provisioner {
   144  	return &Provisioner{
   145  		Type:      p.Type,
   146  		RawConfig: p.RawConfig.Copy(),
   147  		ConnInfo:  p.ConnInfo.Copy(),
   148  		When:      p.When,
   149  		OnFailure: p.OnFailure,
   150  	}
   151  }
   152  
   153  // Variable is a module argument defined within the configuration.
   154  type Variable struct {
   155  	Name         string
   156  	DeclaredType string `mapstructure:"type"`
   157  	Default      interface{}
   158  	Description  string
   159  }
   160  
   161  // Local is a local value defined within the configuration.
   162  type Local struct {
   163  	Name      string
   164  	RawConfig *RawConfig
   165  }
   166  
   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.
   171  type Output struct {
   172  	Name        string
   173  	DependsOn   []string
   174  	Description string
   175  	Sensitive   bool
   176  	RawConfig   *RawConfig
   177  }
   178  
   179  // VariableType is the type of value a variable is holding, and returned
   180  // by the Type() function on variables.
   181  type VariableType byte
   182  
   183  const (
   184  	VariableTypeUnknown VariableType = iota
   185  	VariableTypeString
   186  	VariableTypeList
   187  	VariableTypeMap
   188  )
   189  
   190  func (v VariableType) Printable() string {
   191  	switch v {
   192  	case VariableTypeString:
   193  		return "string"
   194  	case VariableTypeMap:
   195  		return "map"
   196  	case VariableTypeList:
   197  		return "list"
   198  	default:
   199  		return "unknown"
   200  	}
   201  }
   202  
   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 {
   207  	lk := ""
   208  	for _, v := range pcs {
   209  		k := v.Name
   210  		if strings.HasPrefix(t, k) && len(k) > len(lk) {
   211  			lk = k
   212  		}
   213  	}
   214  
   215  	return lk
   216  }
   217  
   218  // A unique identifier for this module.
   219  func (r *Module) Id() string {
   220  	return fmt.Sprintf("%s", r.Name)
   221  }
   222  
   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)
   227  	if !ok {
   228  		return 0, fmt.Errorf(
   229  			"expected count to be a string or int, got %T", raw)
   230  	}
   231  
   232  	v, err := strconv.ParseInt(count, 0, 0)
   233  	if err != nil {
   234  		return 0, fmt.Errorf(
   235  			"cannot parse %q as an integer",
   236  			count,
   237  		)
   238  	}
   239  
   240  	return int(v), nil
   241  }
   242  
   243  // A unique identifier for this resource.
   244  func (r *Resource) Id() string {
   245  	switch r.Mode {
   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)
   250  	default:
   251  		panic(fmt.Errorf("unknown resource mode %s", r.Mode))
   252  	}
   253  }
   254  
   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)
   260  }
   261  
   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]
   271  	}
   272  
   273  	idx := strings.IndexRune(resourceType, '_')
   274  	if idx == -1 {
   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.
   278  		return resourceType
   279  	}
   280  
   281  	return resourceType[:idx]
   282  }
   283  
   284  // Validate does some basic semantic checking of the configuration.
   285  func (c *Config) Validate() tfdiags.Diagnostics {
   286  	if c == nil {
   287  		return nil
   288  	}
   289  
   290  	var diags tfdiags.Diagnostics
   291  
   292  	for _, k := range c.unknownKeys {
   293  		diags = diags.Append(
   294  			fmt.Errorf("Unknown root level key: %s", k),
   295  		)
   296  	}
   297  
   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)
   303  		}
   304  	}
   305  
   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.",
   312  				v.Name,
   313  			))
   314  		}
   315  
   316  		varMap[v.Name] = v
   317  	}
   318  
   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",
   323  				k, NameRegexp,
   324  			))
   325  		}
   326  	}
   327  
   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",
   332  				v.Name,
   333  			))
   334  			continue
   335  		}
   336  
   337  		interp := false
   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 {
   345  				interp = true
   346  			}
   347  			return "", nil
   348  		}
   349  
   350  		w := &interpolationWalker{F: fn}
   351  		if v.Default != nil {
   352  			if err := reflectwalk.Walk(v.Default, w); err == nil {
   353  				if interp {
   354  					diags = diags.Append(fmt.Errorf(
   355  						"variable %q: default may not contain interpolations",
   356  						v.Name,
   357  					))
   358  				}
   359  			}
   360  		}
   361  	}
   362  
   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)
   368  			if !ok {
   369  				continue
   370  			}
   371  
   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",
   375  					source,
   376  					uv.Name,
   377  				))
   378  			}
   379  		}
   380  	}
   381  
   382  	// Check that all count variables are valid.
   383  	for source, vs := range vars {
   384  		for _, rawV := range vs {
   385  			switch v := rawV.(type) {
   386  			case *CountVariable:
   387  				if v.Type == CountValueInvalid {
   388  					diags = diags.Append(fmt.Errorf(
   389  						"%s: invalid count variable: %s",
   390  						source,
   391  						v.FullKey(),
   392  					))
   393  				}
   394  			case *PathVariable:
   395  				if v.Type == PathValueInvalid {
   396  					diags = diags.Append(fmt.Errorf(
   397  						"%s: invalid path variable: %s",
   398  						source,
   399  						v.FullKey(),
   400  					))
   401  				}
   402  			}
   403  		}
   404  	}
   405  
   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 {
   410  		name := p.FullName()
   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",
   414  				name,
   415  			))
   416  			continue
   417  		}
   418  
   419  		if p.Version != "" {
   420  			_, err := discovery.ConstraintStr(p.Version).Parse()
   421  			if err != nil {
   422  				diags = diags.Append(&hcl2.Diagnostic{
   423  					Severity: hcl2.DiagError,
   424  					Summary:  "Invalid provider version constraint",
   425  					Detail: fmt.Sprintf(
   426  						"The value %q given for provider.%s is not a valid version constraint.",
   427  						p.Version, name,
   428  					),
   429  					// TODO: include a "Subject" source reference in here,
   430  					// once the config loader is able to retain source
   431  					// location information.
   432  				})
   433  			}
   434  		}
   435  
   436  		providerSet[name] = true
   437  	}
   438  
   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{}{}
   447  
   448  				diags = diags.Append(fmt.Errorf(
   449  					"module %q: module repeated multiple times",
   450  					m.Id(),
   451  				))
   452  			}
   453  
   454  			// Already seen this module, just skip it
   455  			continue
   456  		}
   457  
   458  		modules[m.Id()] = m
   459  
   460  		// Check that the source has no interpolations
   461  		rc, err := NewRawConfig(map[string]interface{}{
   462  			"root": m.Source,
   463  		})
   464  		if err != nil {
   465  			diags = diags.Append(fmt.Errorf(
   466  				"module %q: module source error: %s",
   467  				m.Id(), err,
   468  			))
   469  		} else if len(rc.Interpolations) > 0 {
   470  			diags = diags.Append(fmt.Errorf(
   471  				"module %q: module source cannot contain interpolations",
   472  				m.Id(),
   473  			))
   474  		}
   475  
   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",
   480  				m.Id(),
   481  			))
   482  		}
   483  
   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 {
   487  			var strVal string
   488  			if err := hilmapstructure.WeakDecode(v, &strVal); err == nil {
   489  				raw[k] = strVal
   490  				continue
   491  			}
   492  
   493  			var mapVal map[string]interface{}
   494  			if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil {
   495  				raw[k] = mapVal
   496  				continue
   497  			}
   498  
   499  			var sliceVal []interface{}
   500  			if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil {
   501  				raw[k] = sliceVal
   502  				continue
   503  			}
   504  
   505  			diags = diags.Append(fmt.Errorf(
   506  				"module %q: argument %s must have a string, list, or map value",
   507  				m.Id(), k,
   508  			))
   509  		}
   510  
   511  		// Check for invalid count variables
   512  		for _, v := range m.RawConfig.Variables {
   513  			switch v.(type) {
   514  			case *CountVariable:
   515  				diags = diags.Append(fmt.Errorf(
   516  					"module %q: count variables are only valid within resources",
   517  					m.Name,
   518  				))
   519  			case *SelfVariable:
   520  				diags = diags.Append(fmt.Errorf(
   521  					"module %q: self variables are only valid within resources",
   522  					m.Name,
   523  				))
   524  			}
   525  		}
   526  
   527  		// Update the raw configuration to only contain the string values
   528  		m.RawConfig, err = NewRawConfig(raw)
   529  		if err != nil {
   530  			diags = diags.Append(fmt.Errorf(
   531  				"%s: can't initialize configuration: %s",
   532  				m.Id(), err,
   533  			))
   534  		}
   535  
   536  		// check that all named providers actually exist
   537  		for _, p := range m.Providers {
   538  			if !providerSet[p] {
   539  				diags = diags.Append(fmt.Errorf(
   540  					"module %q: cannot pass non-existent provider %q",
   541  					m.Name, p,
   542  				))
   543  			}
   544  		}
   545  
   546  	}
   547  	dupped = nil
   548  
   549  	// Check that all variables for modules reference modules that
   550  	// exist.
   551  	for source, vs := range vars {
   552  		for _, v := range vs {
   553  			mv, ok := v.(*ModuleVariable)
   554  			if !ok {
   555  				continue
   556  			}
   557  
   558  			if _, ok := modules[mv.Name]; !ok {
   559  				diags = diags.Append(fmt.Errorf(
   560  					"%s: unknown module referenced: %s",
   561  					source, mv.Name,
   562  				))
   563  			}
   564  		}
   565  	}
   566  
   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{}{}
   574  
   575  				diags = diags.Append(fmt.Errorf(
   576  					"%s: resource repeated multiple times",
   577  					r.Id(),
   578  				))
   579  			}
   580  		}
   581  
   582  		resources[r.Id()] = r
   583  	}
   584  	dupped = nil
   585  
   586  	// Validate resources
   587  	for n, r := range resources {
   588  		// Verify count variables
   589  		for _, v := range r.RawCount.Variables {
   590  			switch v.(type) {
   591  			case *CountVariable:
   592  				diags = diags.Append(fmt.Errorf(
   593  					"%s: resource count can't reference count variable: %s",
   594  					n, v.FullKey(),
   595  				))
   596  			case *SimpleVariable:
   597  				diags = diags.Append(fmt.Errorf(
   598  					"%s: resource count can't reference variable: %s",
   599  					n, v.FullKey(),
   600  				))
   601  
   602  			// Good
   603  			case *ModuleVariable:
   604  			case *ResourceVariable:
   605  			case *TerraformVariable:
   606  			case *UserVariable:
   607  			case *LocalVariable:
   608  
   609  			default:
   610  				diags = diags.Append(fmt.Errorf(
   611  					"Internal error. Unknown type in count var in %s: %T",
   612  					n, v,
   613  				))
   614  			}
   615  		}
   616  
   617  		if !r.RawCount.couldBeInteger() {
   618  			diags = diags.Append(fmt.Errorf(
   619  				"%s: resource count must be an integer", n,
   620  			))
   621  		}
   622  		r.RawCount.init()
   623  
   624  		// Validate DependsOn
   625  		for _, err := range c.validateDependsOn(n, r.DependsOn, resources, modules) {
   626  			diags = diags.Append(err)
   627  		}
   628  
   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.
   633  
   634  			for _, v := range p.ConnInfo.Variables {
   635  				rv, ok := v.(*ResourceVariable)
   636  				if !ok {
   637  					continue
   638  				}
   639  
   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",
   643  						n,
   644  					))
   645  					break
   646  				}
   647  			}
   648  
   649  			for _, v := range p.RawConfig.Variables {
   650  				rv, ok := v.(*ResourceVariable)
   651  				if !ok {
   652  					continue
   653  				}
   654  
   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",
   658  						n,
   659  					))
   660  					break
   661  				}
   662  			}
   663  
   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,
   669  				))
   670  			}
   671  			if p.OnFailure == ProvisionerOnFailureInvalid {
   672  				diags = diags.Append(fmt.Errorf(
   673  					"%s: provisioner 'on_failure' value is invalid", n,
   674  				))
   675  			}
   676  		}
   677  
   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",
   683  					n, v,
   684  				))
   685  			}
   686  		}
   687  
   688  		// Verify ignore_changes has no interpolations
   689  		rc, err := NewRawConfig(map[string]interface{}{
   690  			"root": r.Lifecycle.IgnoreChanges,
   691  		})
   692  		if err != nil {
   693  			diags = diags.Append(fmt.Errorf(
   694  				"%s: lifecycle ignore_changes error: %s",
   695  				n, err,
   696  			))
   697  		} else if len(rc.Interpolations) > 0 {
   698  			diags = diags.Append(fmt.Errorf(
   699  				"%s: lifecycle ignore_changes cannot contain interpolations",
   700  				n,
   701  			))
   702  		}
   703  
   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",
   709  					n,
   710  				))
   711  			}
   712  		}
   713  	}
   714  
   715  	for source, vs := range vars {
   716  		for _, v := range vs {
   717  			rv, ok := v.(*ResourceVariable)
   718  			if !ok {
   719  				continue
   720  			}
   721  
   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",
   726  					source,
   727  					id,
   728  					rv.FullKey(),
   729  				))
   730  				continue
   731  			}
   732  		}
   733  	}
   734  
   735  	// Check that all locals are valid
   736  	{
   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",
   742  					l.Name,
   743  				))
   744  				continue
   745  			}
   746  			found[l.Name] = struct{}{}
   747  
   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,
   752  					))
   753  				}
   754  			}
   755  		}
   756  	}
   757  
   758  	// Check that all outputs are valid
   759  	{
   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",
   766  					o.Name,
   767  				))
   768  				continue
   769  			}
   770  			found[o.Name] = struct{}{}
   771  
   772  			var invalidKeys []string
   773  			valueKeyFound := false
   774  			for k := range o.RawConfig.Raw {
   775  				if k == "value" {
   776  					valueKeyFound = true
   777  					continue
   778  				}
   779  				if k == "sensitive" {
   780  					if sensitive, ok := o.RawConfig.config[k].(bool); ok {
   781  						if sensitive {
   782  							o.Sensitive = true
   783  						}
   784  						continue
   785  					}
   786  
   787  					diags = diags.Append(fmt.Errorf(
   788  						"output %q: value for 'sensitive' must be boolean",
   789  						o.Name,
   790  					))
   791  					continue
   792  				}
   793  				if k == "description" {
   794  					if desc, ok := o.RawConfig.config[k].(string); ok {
   795  						o.Description = desc
   796  						continue
   797  					}
   798  
   799  					diags = diags.Append(fmt.Errorf(
   800  						"output %q: value for 'description' must be string",
   801  						o.Name,
   802  					))
   803  					continue
   804  				}
   805  				invalidKeys = append(invalidKeys, k)
   806  			}
   807  			if len(invalidKeys) > 0 {
   808  				diags = diags.Append(fmt.Errorf(
   809  					"output %q: invalid keys: %s",
   810  					o.Name, strings.Join(invalidKeys, ", "),
   811  				))
   812  			}
   813  			if !valueKeyFound {
   814  				diags = diags.Append(fmt.Errorf(
   815  					"output %q: missing required 'value' argument", o.Name,
   816  				))
   817  			}
   818  
   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",
   823  						o.Name,
   824  					))
   825  				}
   826  			}
   827  
   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.
   832  			//
   833  			// TODO: Remove this in 0.12.
   834  			for _, v := range o.RawConfig.Variables {
   835  				rv, ok := v.(*ResourceVariable)
   836  				if !ok {
   837  					continue
   838  				}
   839  
   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.
   844  
   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.
   848  					continue
   849  				}
   850  
   851  				for _, r := range c.Resources {
   852  					if r.Id() != rv.ResourceId() {
   853  						continue
   854  					}
   855  
   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
   862  					// to be safe.
   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",
   866  							o.Name,
   867  							r.Id(), rv.Field,
   868  							r.Id(), rv.Field,
   869  						)))
   870  					}
   871  				}
   872  			}
   873  		}
   874  	}
   875  
   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") {
   881  			continue
   882  		}
   883  
   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",
   888  					source, v.FullKey(),
   889  				))
   890  			}
   891  		}
   892  	}
   893  
   894  	return diags
   895  }
   896  
   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)
   905  		}
   906  	}
   907  	return result
   908  }
   909  
   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
   917  	}
   918  
   919  	for _, pc := range c.ProviderConfigs {
   920  		source := fmt.Sprintf("provider config '%s'", pc.Name)
   921  		result[source] = pc.RawConfig
   922  	}
   923  
   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
   928  
   929  		for i, p := range rc.Provisioners {
   930  			subsource := fmt.Sprintf(
   931  				"%s provisioner %s (#%d)",
   932  				source, p.Type, i+1)
   933  			result[subsource] = p.RawConfig
   934  		}
   935  	}
   936  
   937  	for _, o := range c.Outputs {
   938  		source := fmt.Sprintf("output '%s'", o.Name)
   939  		result[source] = o.RawConfig
   940  	}
   941  
   942  	return result
   943  }
   944  
   945  func (c *Config) validateDependsOn(
   946  	n string,
   947  	v []string,
   948  	resources map[string]*Resource,
   949  	modules map[string]*Module) []error {
   950  	// Verify depends on points to resources that all exist
   951  	var errs []error
   952  	for _, d := range v {
   953  		// Check if we contain interpolations
   954  		rc, err := NewRawConfig(map[string]interface{}{
   955  			"value": d,
   956  		})
   957  		if err == nil && len(rc.Variables) > 0 {
   958  			errs = append(errs, fmt.Errorf(
   959  				"%s: depends on value cannot contain interpolations: %s",
   960  				n, d))
   961  			continue
   962  		}
   963  
   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'",
   970  					n, name))
   971  			}
   972  
   973  			continue
   974  		}
   975  
   976  		// Check resources
   977  		if _, ok := resources[d]; !ok {
   978  			errs = append(errs, fmt.Errorf(
   979  				"%s: resource depends on non-existent resource '%s'",
   980  				n, d))
   981  		}
   982  	}
   983  
   984  	return errs
   985  }
   986  
   987  func (m *Module) mergerName() string {
   988  	return m.Id()
   989  }
   990  
   991  func (m *Module) mergerMerge(other merger) merger {
   992  	m2 := other.(*Module)
   993  
   994  	result := *m
   995  	result.Name = m2.Name
   996  	result.RawConfig = result.RawConfig.merge(m2.RawConfig)
   997  
   998  	if m2.Source != "" {
   999  		result.Source = m2.Source
  1000  	}
  1001  
  1002  	return &result
  1003  }
  1004  
  1005  func (o *Output) mergerName() string {
  1006  	return o.Name
  1007  }
  1008  
  1009  func (o *Output) mergerMerge(m merger) merger {
  1010  	o2 := m.(*Output)
  1011  
  1012  	result := *o
  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
  1018  
  1019  	return &result
  1020  }
  1021  
  1022  func (c *ProviderConfig) GoString() string {
  1023  	return fmt.Sprintf("*%#v", *c)
  1024  }
  1025  
  1026  func (c *ProviderConfig) FullName() string {
  1027  	if c.Alias == "" {
  1028  		return c.Name
  1029  	}
  1030  
  1031  	return fmt.Sprintf("%s.%s", c.Name, c.Alias)
  1032  }
  1033  
  1034  func (c *ProviderConfig) mergerName() string {
  1035  	return c.Name
  1036  }
  1037  
  1038  func (c *ProviderConfig) mergerMerge(m merger) merger {
  1039  	c2 := m.(*ProviderConfig)
  1040  
  1041  	result := *c
  1042  	result.Name = c2.Name
  1043  	result.RawConfig = result.RawConfig.merge(c2.RawConfig)
  1044  
  1045  	if c2.Alias != "" {
  1046  		result.Alias = c2.Alias
  1047  	}
  1048  
  1049  	return &result
  1050  }
  1051  
  1052  func (r *Resource) mergerName() string {
  1053  	return r.Id()
  1054  }
  1055  
  1056  func (r *Resource) mergerMerge(m merger) merger {
  1057  	r2 := m.(*Resource)
  1058  
  1059  	result := *r
  1060  	result.Mode = r2.Mode
  1061  	result.Name = r2.Name
  1062  	result.Type = r2.Type
  1063  	result.RawConfig = result.RawConfig.merge(r2.RawConfig)
  1064  
  1065  	if r2.RawCount.Value() != "1" {
  1066  		result.RawCount = r2.RawCount
  1067  	}
  1068  
  1069  	if len(r2.Provisioners) > 0 {
  1070  		result.Provisioners = r2.Provisioners
  1071  	}
  1072  
  1073  	return &result
  1074  }
  1075  
  1076  // Merge merges two variables to create a new third variable.
  1077  func (v *Variable) Merge(v2 *Variable) *Variable {
  1078  	// Shallow copy the variable
  1079  	result := *v
  1080  
  1081  	// The names should be the same, but the second name always wins.
  1082  	result.Name = v2.Name
  1083  
  1084  	if v2.DeclaredType != "" {
  1085  		result.DeclaredType = v2.DeclaredType
  1086  	}
  1087  	if v2.Default != nil {
  1088  		result.Default = v2.Default
  1089  	}
  1090  	if v2.Description != "" {
  1091  		result.Description = v2.Description
  1092  	}
  1093  
  1094  	return &result
  1095  }
  1096  
  1097  var typeStringMap = map[string]VariableType{
  1098  	"string": VariableTypeString,
  1099  	"map":    VariableTypeMap,
  1100  	"list":   VariableTypeList,
  1101  }
  1102  
  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]
  1107  		if !ok {
  1108  			return VariableTypeUnknown
  1109  		}
  1110  
  1111  		return declaredType
  1112  	}
  1113  
  1114  	return v.inferTypeFromDefault()
  1115  }
  1116  
  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)
  1127  			}
  1128  			return fmt.Errorf(
  1129  				"Variable '%s' type must be one of [%s] - '%s' is not a valid type",
  1130  				v.Name,
  1131  				strings.Join(validTypes, ", "),
  1132  				v.DeclaredType,
  1133  			)
  1134  		}
  1135  	}
  1136  
  1137  	if v.DeclaredType == "" || v.Default == nil {
  1138  		return nil
  1139  	}
  1140  
  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())
  1144  	}
  1145  
  1146  	return nil
  1147  }
  1148  
  1149  func (v *Variable) mergerName() string {
  1150  	return v.Name
  1151  }
  1152  
  1153  func (v *Variable) mergerMerge(m merger) merger {
  1154  	return v.Merge(m.(*Variable))
  1155  }
  1156  
  1157  // Required tests whether a variable is required or not.
  1158  func (v *Variable) Required() bool {
  1159  	return v.Default == nil
  1160  }
  1161  
  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
  1168  	}
  1169  
  1170  	var s string
  1171  	if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil {
  1172  		v.Default = s
  1173  		return VariableTypeString
  1174  	}
  1175  
  1176  	var m map[string]interface{}
  1177  	if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil {
  1178  		v.Default = m
  1179  		return VariableTypeMap
  1180  	}
  1181  
  1182  	var l []interface{}
  1183  	if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil {
  1184  		v.Default = l
  1185  		return VariableTypeList
  1186  	}
  1187  
  1188  	return VariableTypeUnknown
  1189  }
  1190  
  1191  func (m ResourceMode) Taintable() bool {
  1192  	switch m {
  1193  	case ManagedResourceMode:
  1194  		return true
  1195  	case DataResourceMode:
  1196  		return false
  1197  	default:
  1198  		panic(fmt.Errorf("unsupported ResourceMode value %s", m))
  1199  	}
  1200  }