github.com/jzbruno/terraform@v0.10.3-0.20180104230435-18975d727047/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, err
   235  	}
   236  
   237  	return int(v), nil
   238  }
   239  
   240  // A unique identifier for this resource.
   241  func (r *Resource) Id() string {
   242  	switch r.Mode {
   243  	case ManagedResourceMode:
   244  		return fmt.Sprintf("%s.%s", r.Type, r.Name)
   245  	case DataResourceMode:
   246  		return fmt.Sprintf("data.%s.%s", r.Type, r.Name)
   247  	default:
   248  		panic(fmt.Errorf("unknown resource mode %s", r.Mode))
   249  	}
   250  }
   251  
   252  // ProviderFullName returns the full name of the provider for this resource,
   253  // which may either be specified explicitly using the "provider" meta-argument
   254  // or implied by the prefix on the resource type name.
   255  func (r *Resource) ProviderFullName() string {
   256  	return ResourceProviderFullName(r.Type, r.Provider)
   257  }
   258  
   259  // ResourceProviderFullName returns the full (dependable) name of the
   260  // provider for a hypothetical resource with the given resource type and
   261  // explicit provider string. If the explicit provider string is empty then
   262  // the provider name is inferred from the resource type name.
   263  func ResourceProviderFullName(resourceType, explicitProvider string) string {
   264  	if explicitProvider != "" {
   265  		// check for an explicit provider name, or return the original
   266  		parts := strings.SplitAfter(explicitProvider, "provider.")
   267  		return parts[len(parts)-1]
   268  	}
   269  
   270  	idx := strings.IndexRune(resourceType, '_')
   271  	if idx == -1 {
   272  		// If no underscores, the resource name is assumed to be
   273  		// also the provider name, e.g. if the provider exposes
   274  		// only a single resource of each type.
   275  		return resourceType
   276  	}
   277  
   278  	return resourceType[:idx]
   279  }
   280  
   281  // Validate does some basic semantic checking of the configuration.
   282  func (c *Config) Validate() tfdiags.Diagnostics {
   283  	if c == nil {
   284  		return nil
   285  	}
   286  
   287  	var diags tfdiags.Diagnostics
   288  
   289  	for _, k := range c.unknownKeys {
   290  		diags = diags.Append(
   291  			fmt.Errorf("Unknown root level key: %s", k),
   292  		)
   293  	}
   294  
   295  	// Validate the Terraform config
   296  	if tf := c.Terraform; tf != nil {
   297  		errs := c.Terraform.Validate()
   298  		for _, err := range errs {
   299  			diags = diags.Append(err)
   300  		}
   301  	}
   302  
   303  	vars := c.InterpolatedVariables()
   304  	varMap := make(map[string]*Variable)
   305  	for _, v := range c.Variables {
   306  		if _, ok := varMap[v.Name]; ok {
   307  			diags = diags.Append(fmt.Errorf(
   308  				"Variable '%s': duplicate found. Variable names must be unique.",
   309  				v.Name,
   310  			))
   311  		}
   312  
   313  		varMap[v.Name] = v
   314  	}
   315  
   316  	for k, _ := range varMap {
   317  		if !NameRegexp.MatchString(k) {
   318  			diags = diags.Append(fmt.Errorf(
   319  				"variable %q: variable name must match regular expression %s",
   320  				k, NameRegexp,
   321  			))
   322  		}
   323  	}
   324  
   325  	for _, v := range c.Variables {
   326  		if v.Type() == VariableTypeUnknown {
   327  			diags = diags.Append(fmt.Errorf(
   328  				"Variable '%s': must be a string or a map",
   329  				v.Name,
   330  			))
   331  			continue
   332  		}
   333  
   334  		interp := false
   335  		fn := func(n ast.Node) (interface{}, error) {
   336  			// LiteralNode is a literal string (outside of a ${ ... } sequence).
   337  			// interpolationWalker skips most of these. but in particular it
   338  			// visits those that have escaped sequences (like $${foo}) as a
   339  			// signal that *some* processing is required on this string. For
   340  			// our purposes here though, this is fine and not an interpolation.
   341  			if _, ok := n.(*ast.LiteralNode); !ok {
   342  				interp = true
   343  			}
   344  			return "", nil
   345  		}
   346  
   347  		w := &interpolationWalker{F: fn}
   348  		if v.Default != nil {
   349  			if err := reflectwalk.Walk(v.Default, w); err == nil {
   350  				if interp {
   351  					diags = diags.Append(fmt.Errorf(
   352  						"variable %q: default may not contain interpolations",
   353  						v.Name,
   354  					))
   355  				}
   356  			}
   357  		}
   358  	}
   359  
   360  	// Check for references to user variables that do not actually
   361  	// exist and record those errors.
   362  	for source, vs := range vars {
   363  		for _, v := range vs {
   364  			uv, ok := v.(*UserVariable)
   365  			if !ok {
   366  				continue
   367  			}
   368  
   369  			if _, ok := varMap[uv.Name]; !ok {
   370  				diags = diags.Append(fmt.Errorf(
   371  					"%s: unknown variable referenced: '%s'; define it with a 'variable' block",
   372  					source,
   373  					uv.Name,
   374  				))
   375  			}
   376  		}
   377  	}
   378  
   379  	// Check that all count variables are valid.
   380  	for source, vs := range vars {
   381  		for _, rawV := range vs {
   382  			switch v := rawV.(type) {
   383  			case *CountVariable:
   384  				if v.Type == CountValueInvalid {
   385  					diags = diags.Append(fmt.Errorf(
   386  						"%s: invalid count variable: %s",
   387  						source,
   388  						v.FullKey(),
   389  					))
   390  				}
   391  			case *PathVariable:
   392  				if v.Type == PathValueInvalid {
   393  					diags = diags.Append(fmt.Errorf(
   394  						"%s: invalid path variable: %s",
   395  						source,
   396  						v.FullKey(),
   397  					))
   398  				}
   399  			}
   400  		}
   401  	}
   402  
   403  	// Check that providers aren't declared multiple times and that their
   404  	// version constraints, where present, are syntactically valid.
   405  	providerSet := make(map[string]bool)
   406  	for _, p := range c.ProviderConfigs {
   407  		name := p.FullName()
   408  		if _, ok := providerSet[name]; ok {
   409  			diags = diags.Append(fmt.Errorf(
   410  				"provider.%s: multiple configurations present; only one configuration is allowed per provider",
   411  				name,
   412  			))
   413  			continue
   414  		}
   415  
   416  		if p.Version != "" {
   417  			_, err := discovery.ConstraintStr(p.Version).Parse()
   418  			if err != nil {
   419  				diags = diags.Append(&hcl2.Diagnostic{
   420  					Severity: hcl2.DiagError,
   421  					Summary:  "Invalid provider version constraint",
   422  					Detail: fmt.Sprintf(
   423  						"The value %q given for provider.%s is not a valid version constraint.",
   424  						p.Version, name,
   425  					),
   426  					// TODO: include a "Subject" source reference in here,
   427  					// once the config loader is able to retain source
   428  					// location information.
   429  				})
   430  			}
   431  		}
   432  
   433  		providerSet[name] = true
   434  	}
   435  
   436  	// Check that all references to modules are valid
   437  	modules := make(map[string]*Module)
   438  	dupped := make(map[string]struct{})
   439  	for _, m := range c.Modules {
   440  		// Check for duplicates
   441  		if _, ok := modules[m.Id()]; ok {
   442  			if _, ok := dupped[m.Id()]; !ok {
   443  				dupped[m.Id()] = struct{}{}
   444  
   445  				diags = diags.Append(fmt.Errorf(
   446  					"module %q: module repeated multiple times",
   447  					m.Id(),
   448  				))
   449  			}
   450  
   451  			// Already seen this module, just skip it
   452  			continue
   453  		}
   454  
   455  		modules[m.Id()] = m
   456  
   457  		// Check that the source has no interpolations
   458  		rc, err := NewRawConfig(map[string]interface{}{
   459  			"root": m.Source,
   460  		})
   461  		if err != nil {
   462  			diags = diags.Append(fmt.Errorf(
   463  				"module %q: module source error: %s",
   464  				m.Id(), err,
   465  			))
   466  		} else if len(rc.Interpolations) > 0 {
   467  			diags = diags.Append(fmt.Errorf(
   468  				"module %q: module source cannot contain interpolations",
   469  				m.Id(),
   470  			))
   471  		}
   472  
   473  		// Check that the name matches our regexp
   474  		if !NameRegexp.Match([]byte(m.Name)) {
   475  			diags = diags.Append(fmt.Errorf(
   476  				"module %q: module name must be a letter or underscore followed by only letters, numbers, dashes, and underscores",
   477  				m.Id(),
   478  			))
   479  		}
   480  
   481  		// Check that the configuration can all be strings, lists or maps
   482  		raw := make(map[string]interface{})
   483  		for k, v := range m.RawConfig.Raw {
   484  			var strVal string
   485  			if err := hilmapstructure.WeakDecode(v, &strVal); err == nil {
   486  				raw[k] = strVal
   487  				continue
   488  			}
   489  
   490  			var mapVal map[string]interface{}
   491  			if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil {
   492  				raw[k] = mapVal
   493  				continue
   494  			}
   495  
   496  			var sliceVal []interface{}
   497  			if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil {
   498  				raw[k] = sliceVal
   499  				continue
   500  			}
   501  
   502  			diags = diags.Append(fmt.Errorf(
   503  				"module %q: argument %s must have a string, list, or map value",
   504  				m.Id(), k,
   505  			))
   506  		}
   507  
   508  		// Check for invalid count variables
   509  		for _, v := range m.RawConfig.Variables {
   510  			switch v.(type) {
   511  			case *CountVariable:
   512  				diags = diags.Append(fmt.Errorf(
   513  					"module %q: count variables are only valid within resources",
   514  					m.Name,
   515  				))
   516  			case *SelfVariable:
   517  				diags = diags.Append(fmt.Errorf(
   518  					"module %q: self variables are only valid within resources",
   519  					m.Name,
   520  				))
   521  			}
   522  		}
   523  
   524  		// Update the raw configuration to only contain the string values
   525  		m.RawConfig, err = NewRawConfig(raw)
   526  		if err != nil {
   527  			diags = diags.Append(fmt.Errorf(
   528  				"%s: can't initialize configuration: %s",
   529  				m.Id(), err,
   530  			))
   531  		}
   532  
   533  		// check that all named providers actually exist
   534  		for _, p := range m.Providers {
   535  			if !providerSet[p] {
   536  				diags = diags.Append(fmt.Errorf(
   537  					"module %q: cannot pass non-existent provider %q",
   538  					m.Name, p,
   539  				))
   540  			}
   541  		}
   542  
   543  	}
   544  	dupped = nil
   545  
   546  	// Check that all variables for modules reference modules that
   547  	// exist.
   548  	for source, vs := range vars {
   549  		for _, v := range vs {
   550  			mv, ok := v.(*ModuleVariable)
   551  			if !ok {
   552  				continue
   553  			}
   554  
   555  			if _, ok := modules[mv.Name]; !ok {
   556  				diags = diags.Append(fmt.Errorf(
   557  					"%s: unknown module referenced: %s",
   558  					source, mv.Name,
   559  				))
   560  			}
   561  		}
   562  	}
   563  
   564  	// Check that all references to resources are valid
   565  	resources := make(map[string]*Resource)
   566  	dupped = make(map[string]struct{})
   567  	for _, r := range c.Resources {
   568  		if _, ok := resources[r.Id()]; ok {
   569  			if _, ok := dupped[r.Id()]; !ok {
   570  				dupped[r.Id()] = struct{}{}
   571  
   572  				diags = diags.Append(fmt.Errorf(
   573  					"%s: resource repeated multiple times",
   574  					r.Id(),
   575  				))
   576  			}
   577  		}
   578  
   579  		resources[r.Id()] = r
   580  	}
   581  	dupped = nil
   582  
   583  	// Validate resources
   584  	for n, r := range resources {
   585  		// Verify count variables
   586  		for _, v := range r.RawCount.Variables {
   587  			switch v.(type) {
   588  			case *CountVariable:
   589  				diags = diags.Append(fmt.Errorf(
   590  					"%s: resource count can't reference count variable: %s",
   591  					n, v.FullKey(),
   592  				))
   593  			case *SimpleVariable:
   594  				diags = diags.Append(fmt.Errorf(
   595  					"%s: resource count can't reference variable: %s",
   596  					n, v.FullKey(),
   597  				))
   598  
   599  			// Good
   600  			case *ModuleVariable:
   601  			case *ResourceVariable:
   602  			case *TerraformVariable:
   603  			case *UserVariable:
   604  			case *LocalVariable:
   605  
   606  			default:
   607  				diags = diags.Append(fmt.Errorf(
   608  					"Internal error. Unknown type in count var in %s: %T",
   609  					n, v,
   610  				))
   611  			}
   612  		}
   613  
   614  		if !r.RawCount.couldBeInteger() {
   615  			diags = diags.Append(fmt.Errorf(
   616  				"%s: resource count must be an integer", n,
   617  			))
   618  		}
   619  		r.RawCount.init()
   620  
   621  		// Validate DependsOn
   622  		for _, err := range c.validateDependsOn(n, r.DependsOn, resources, modules) {
   623  			diags = diags.Append(err)
   624  		}
   625  
   626  		// Verify provisioners
   627  		for _, p := range r.Provisioners {
   628  			// This validation checks that there are no splat variables
   629  			// referencing ourself. This currently is not allowed.
   630  
   631  			for _, v := range p.ConnInfo.Variables {
   632  				rv, ok := v.(*ResourceVariable)
   633  				if !ok {
   634  					continue
   635  				}
   636  
   637  				if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
   638  					diags = diags.Append(fmt.Errorf(
   639  						"%s: connection info cannot contain splat variable referencing itself",
   640  						n,
   641  					))
   642  					break
   643  				}
   644  			}
   645  
   646  			for _, v := range p.RawConfig.Variables {
   647  				rv, ok := v.(*ResourceVariable)
   648  				if !ok {
   649  					continue
   650  				}
   651  
   652  				if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
   653  					diags = diags.Append(fmt.Errorf(
   654  						"%s: connection info cannot contain splat variable referencing itself",
   655  						n,
   656  					))
   657  					break
   658  				}
   659  			}
   660  
   661  			// Check for invalid when/onFailure values, though this should be
   662  			// picked up by the loader we check here just in case.
   663  			if p.When == ProvisionerWhenInvalid {
   664  				diags = diags.Append(fmt.Errorf(
   665  					"%s: provisioner 'when' value is invalid", n,
   666  				))
   667  			}
   668  			if p.OnFailure == ProvisionerOnFailureInvalid {
   669  				diags = diags.Append(fmt.Errorf(
   670  					"%s: provisioner 'on_failure' value is invalid", n,
   671  				))
   672  			}
   673  		}
   674  
   675  		// Verify ignore_changes contains valid entries
   676  		for _, v := range r.Lifecycle.IgnoreChanges {
   677  			if strings.Contains(v, "*") && v != "*" {
   678  				diags = diags.Append(fmt.Errorf(
   679  					"%s: ignore_changes does not support using a partial string together with a wildcard: %s",
   680  					n, v,
   681  				))
   682  			}
   683  		}
   684  
   685  		// Verify ignore_changes has no interpolations
   686  		rc, err := NewRawConfig(map[string]interface{}{
   687  			"root": r.Lifecycle.IgnoreChanges,
   688  		})
   689  		if err != nil {
   690  			diags = diags.Append(fmt.Errorf(
   691  				"%s: lifecycle ignore_changes error: %s",
   692  				n, err,
   693  			))
   694  		} else if len(rc.Interpolations) > 0 {
   695  			diags = diags.Append(fmt.Errorf(
   696  				"%s: lifecycle ignore_changes cannot contain interpolations",
   697  				n,
   698  			))
   699  		}
   700  
   701  		// If it is a data source then it can't have provisioners
   702  		if r.Mode == DataResourceMode {
   703  			if _, ok := r.RawConfig.Raw["provisioner"]; ok {
   704  				diags = diags.Append(fmt.Errorf(
   705  					"%s: data sources cannot have provisioners",
   706  					n,
   707  				))
   708  			}
   709  		}
   710  	}
   711  
   712  	for source, vs := range vars {
   713  		for _, v := range vs {
   714  			rv, ok := v.(*ResourceVariable)
   715  			if !ok {
   716  				continue
   717  			}
   718  
   719  			id := rv.ResourceId()
   720  			if _, ok := resources[id]; !ok {
   721  				diags = diags.Append(fmt.Errorf(
   722  					"%s: unknown resource '%s' referenced in variable %s",
   723  					source,
   724  					id,
   725  					rv.FullKey(),
   726  				))
   727  				continue
   728  			}
   729  		}
   730  	}
   731  
   732  	// Check that all locals are valid
   733  	{
   734  		found := make(map[string]struct{})
   735  		for _, l := range c.Locals {
   736  			if _, ok := found[l.Name]; ok {
   737  				diags = diags.Append(fmt.Errorf(
   738  					"%s: duplicate local. local value names must be unique",
   739  					l.Name,
   740  				))
   741  				continue
   742  			}
   743  			found[l.Name] = struct{}{}
   744  
   745  			for _, v := range l.RawConfig.Variables {
   746  				if _, ok := v.(*CountVariable); ok {
   747  					diags = diags.Append(fmt.Errorf(
   748  						"local %s: count variables are only valid within resources", l.Name,
   749  					))
   750  				}
   751  			}
   752  		}
   753  	}
   754  
   755  	// Check that all outputs are valid
   756  	{
   757  		found := make(map[string]struct{})
   758  		for _, o := range c.Outputs {
   759  			// Verify the output is new
   760  			if _, ok := found[o.Name]; ok {
   761  				diags = diags.Append(fmt.Errorf(
   762  					"output %q: an output of this name was already defined",
   763  					o.Name,
   764  				))
   765  				continue
   766  			}
   767  			found[o.Name] = struct{}{}
   768  
   769  			var invalidKeys []string
   770  			valueKeyFound := false
   771  			for k := range o.RawConfig.Raw {
   772  				if k == "value" {
   773  					valueKeyFound = true
   774  					continue
   775  				}
   776  				if k == "sensitive" {
   777  					if sensitive, ok := o.RawConfig.config[k].(bool); ok {
   778  						if sensitive {
   779  							o.Sensitive = true
   780  						}
   781  						continue
   782  					}
   783  
   784  					diags = diags.Append(fmt.Errorf(
   785  						"output %q: value for 'sensitive' must be boolean",
   786  						o.Name,
   787  					))
   788  					continue
   789  				}
   790  				if k == "description" {
   791  					if desc, ok := o.RawConfig.config[k].(string); ok {
   792  						o.Description = desc
   793  						continue
   794  					}
   795  
   796  					diags = diags.Append(fmt.Errorf(
   797  						"output %q: value for 'description' must be string",
   798  						o.Name,
   799  					))
   800  					continue
   801  				}
   802  				invalidKeys = append(invalidKeys, k)
   803  			}
   804  			if len(invalidKeys) > 0 {
   805  				diags = diags.Append(fmt.Errorf(
   806  					"output %q: invalid keys: %s",
   807  					o.Name, strings.Join(invalidKeys, ", "),
   808  				))
   809  			}
   810  			if !valueKeyFound {
   811  				diags = diags.Append(fmt.Errorf(
   812  					"output %q: missing required 'value' argument", o.Name,
   813  				))
   814  			}
   815  
   816  			for _, v := range o.RawConfig.Variables {
   817  				if _, ok := v.(*CountVariable); ok {
   818  					diags = diags.Append(fmt.Errorf(
   819  						"output %q: count variables are only valid within resources",
   820  						o.Name,
   821  					))
   822  				}
   823  			}
   824  
   825  			// Detect a common mistake of using a "count"ed resource in
   826  			// an output value without using the splat or index form.
   827  			// Prior to 0.11 this error was silently ignored, but outputs
   828  			// now have their errors checked like all other contexts.
   829  			//
   830  			// TODO: Remove this in 0.12.
   831  			for _, v := range o.RawConfig.Variables {
   832  				rv, ok := v.(*ResourceVariable)
   833  				if !ok {
   834  					continue
   835  				}
   836  
   837  				// If the variable seems to be treating the referenced
   838  				// resource as a singleton (no count specified) then
   839  				// we'll check to make sure it is indeed a singleton.
   840  				// It's a warning if not.
   841  
   842  				if rv.Multi || rv.Index != 0 {
   843  					// This reference is treating the resource as a
   844  					// multi-resource, so the warning doesn't apply.
   845  					continue
   846  				}
   847  
   848  				for _, r := range c.Resources {
   849  					if r.Id() != rv.ResourceId() {
   850  						continue
   851  					}
   852  
   853  					// We test specifically for the raw string "1" here
   854  					// because we _do_ want to generate this warning if
   855  					// the user has provided an expression that happens
   856  					// to return 1 right now, to catch situations where
   857  					// a count might dynamically be set to something
   858  					// other than 1 and thus splat syntax is still needed
   859  					// to be safe.
   860  					if r.RawCount != nil && r.RawCount.Raw != nil && r.RawCount.Raw["count"] != "1" && rv.Field != "count" {
   861  						diags = diags.Append(tfdiags.SimpleWarning(fmt.Sprintf(
   862  							"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",
   863  							o.Name,
   864  							r.Id(), rv.Field,
   865  							r.Id(), rv.Field,
   866  						)))
   867  					}
   868  				}
   869  			}
   870  		}
   871  	}
   872  
   873  	// Validate the self variable
   874  	for source, rc := range c.rawConfigs() {
   875  		// Ignore provisioners. This is a pretty brittle way to do this,
   876  		// but better than also repeating all the resources.
   877  		if strings.Contains(source, "provision") {
   878  			continue
   879  		}
   880  
   881  		for _, v := range rc.Variables {
   882  			if _, ok := v.(*SelfVariable); ok {
   883  				diags = diags.Append(fmt.Errorf(
   884  					"%s: cannot contain self-reference %s",
   885  					source, v.FullKey(),
   886  				))
   887  			}
   888  		}
   889  	}
   890  
   891  	return diags
   892  }
   893  
   894  // InterpolatedVariables is a helper that returns a mapping of all the interpolated
   895  // variables within the configuration. This is used to verify references
   896  // are valid in the Validate step.
   897  func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable {
   898  	result := make(map[string][]InterpolatedVariable)
   899  	for source, rc := range c.rawConfigs() {
   900  		for _, v := range rc.Variables {
   901  			result[source] = append(result[source], v)
   902  		}
   903  	}
   904  	return result
   905  }
   906  
   907  // rawConfigs returns all of the RawConfigs that are available keyed by
   908  // a human-friendly source.
   909  func (c *Config) rawConfigs() map[string]*RawConfig {
   910  	result := make(map[string]*RawConfig)
   911  	for _, m := range c.Modules {
   912  		source := fmt.Sprintf("module '%s'", m.Name)
   913  		result[source] = m.RawConfig
   914  	}
   915  
   916  	for _, pc := range c.ProviderConfigs {
   917  		source := fmt.Sprintf("provider config '%s'", pc.Name)
   918  		result[source] = pc.RawConfig
   919  	}
   920  
   921  	for _, rc := range c.Resources {
   922  		source := fmt.Sprintf("resource '%s'", rc.Id())
   923  		result[source+" count"] = rc.RawCount
   924  		result[source+" config"] = rc.RawConfig
   925  
   926  		for i, p := range rc.Provisioners {
   927  			subsource := fmt.Sprintf(
   928  				"%s provisioner %s (#%d)",
   929  				source, p.Type, i+1)
   930  			result[subsource] = p.RawConfig
   931  		}
   932  	}
   933  
   934  	for _, o := range c.Outputs {
   935  		source := fmt.Sprintf("output '%s'", o.Name)
   936  		result[source] = o.RawConfig
   937  	}
   938  
   939  	return result
   940  }
   941  
   942  func (c *Config) validateDependsOn(
   943  	n string,
   944  	v []string,
   945  	resources map[string]*Resource,
   946  	modules map[string]*Module) []error {
   947  	// Verify depends on points to resources that all exist
   948  	var errs []error
   949  	for _, d := range v {
   950  		// Check if we contain interpolations
   951  		rc, err := NewRawConfig(map[string]interface{}{
   952  			"value": d,
   953  		})
   954  		if err == nil && len(rc.Variables) > 0 {
   955  			errs = append(errs, fmt.Errorf(
   956  				"%s: depends on value cannot contain interpolations: %s",
   957  				n, d))
   958  			continue
   959  		}
   960  
   961  		// If it is a module, verify it is a module
   962  		if strings.HasPrefix(d, "module.") {
   963  			name := d[len("module."):]
   964  			if _, ok := modules[name]; !ok {
   965  				errs = append(errs, fmt.Errorf(
   966  					"%s: resource depends on non-existent module '%s'",
   967  					n, name))
   968  			}
   969  
   970  			continue
   971  		}
   972  
   973  		// Check resources
   974  		if _, ok := resources[d]; !ok {
   975  			errs = append(errs, fmt.Errorf(
   976  				"%s: resource depends on non-existent resource '%s'",
   977  				n, d))
   978  		}
   979  	}
   980  
   981  	return errs
   982  }
   983  
   984  func (m *Module) mergerName() string {
   985  	return m.Id()
   986  }
   987  
   988  func (m *Module) mergerMerge(other merger) merger {
   989  	m2 := other.(*Module)
   990  
   991  	result := *m
   992  	result.Name = m2.Name
   993  	result.RawConfig = result.RawConfig.merge(m2.RawConfig)
   994  
   995  	if m2.Source != "" {
   996  		result.Source = m2.Source
   997  	}
   998  
   999  	return &result
  1000  }
  1001  
  1002  func (o *Output) mergerName() string {
  1003  	return o.Name
  1004  }
  1005  
  1006  func (o *Output) mergerMerge(m merger) merger {
  1007  	o2 := m.(*Output)
  1008  
  1009  	result := *o
  1010  	result.Name = o2.Name
  1011  	result.Description = o2.Description
  1012  	result.RawConfig = result.RawConfig.merge(o2.RawConfig)
  1013  	result.Sensitive = o2.Sensitive
  1014  	result.DependsOn = o2.DependsOn
  1015  
  1016  	return &result
  1017  }
  1018  
  1019  func (c *ProviderConfig) GoString() string {
  1020  	return fmt.Sprintf("*%#v", *c)
  1021  }
  1022  
  1023  func (c *ProviderConfig) FullName() string {
  1024  	if c.Alias == "" {
  1025  		return c.Name
  1026  	}
  1027  
  1028  	return fmt.Sprintf("%s.%s", c.Name, c.Alias)
  1029  }
  1030  
  1031  func (c *ProviderConfig) mergerName() string {
  1032  	return c.Name
  1033  }
  1034  
  1035  func (c *ProviderConfig) mergerMerge(m merger) merger {
  1036  	c2 := m.(*ProviderConfig)
  1037  
  1038  	result := *c
  1039  	result.Name = c2.Name
  1040  	result.RawConfig = result.RawConfig.merge(c2.RawConfig)
  1041  
  1042  	if c2.Alias != "" {
  1043  		result.Alias = c2.Alias
  1044  	}
  1045  
  1046  	return &result
  1047  }
  1048  
  1049  func (r *Resource) mergerName() string {
  1050  	return r.Id()
  1051  }
  1052  
  1053  func (r *Resource) mergerMerge(m merger) merger {
  1054  	r2 := m.(*Resource)
  1055  
  1056  	result := *r
  1057  	result.Mode = r2.Mode
  1058  	result.Name = r2.Name
  1059  	result.Type = r2.Type
  1060  	result.RawConfig = result.RawConfig.merge(r2.RawConfig)
  1061  
  1062  	if r2.RawCount.Value() != "1" {
  1063  		result.RawCount = r2.RawCount
  1064  	}
  1065  
  1066  	if len(r2.Provisioners) > 0 {
  1067  		result.Provisioners = r2.Provisioners
  1068  	}
  1069  
  1070  	return &result
  1071  }
  1072  
  1073  // Merge merges two variables to create a new third variable.
  1074  func (v *Variable) Merge(v2 *Variable) *Variable {
  1075  	// Shallow copy the variable
  1076  	result := *v
  1077  
  1078  	// The names should be the same, but the second name always wins.
  1079  	result.Name = v2.Name
  1080  
  1081  	if v2.DeclaredType != "" {
  1082  		result.DeclaredType = v2.DeclaredType
  1083  	}
  1084  	if v2.Default != nil {
  1085  		result.Default = v2.Default
  1086  	}
  1087  	if v2.Description != "" {
  1088  		result.Description = v2.Description
  1089  	}
  1090  
  1091  	return &result
  1092  }
  1093  
  1094  var typeStringMap = map[string]VariableType{
  1095  	"string": VariableTypeString,
  1096  	"map":    VariableTypeMap,
  1097  	"list":   VariableTypeList,
  1098  }
  1099  
  1100  // Type returns the type of variable this is.
  1101  func (v *Variable) Type() VariableType {
  1102  	if v.DeclaredType != "" {
  1103  		declaredType, ok := typeStringMap[v.DeclaredType]
  1104  		if !ok {
  1105  			return VariableTypeUnknown
  1106  		}
  1107  
  1108  		return declaredType
  1109  	}
  1110  
  1111  	return v.inferTypeFromDefault()
  1112  }
  1113  
  1114  // ValidateTypeAndDefault ensures that default variable value is compatible
  1115  // with the declared type (if one exists), and that the type is one which is
  1116  // known to Terraform
  1117  func (v *Variable) ValidateTypeAndDefault() error {
  1118  	// If an explicit type is declared, ensure it is valid
  1119  	if v.DeclaredType != "" {
  1120  		if _, ok := typeStringMap[v.DeclaredType]; !ok {
  1121  			validTypes := []string{}
  1122  			for k := range typeStringMap {
  1123  				validTypes = append(validTypes, k)
  1124  			}
  1125  			return fmt.Errorf(
  1126  				"Variable '%s' type must be one of [%s] - '%s' is not a valid type",
  1127  				v.Name,
  1128  				strings.Join(validTypes, ", "),
  1129  				v.DeclaredType,
  1130  			)
  1131  		}
  1132  	}
  1133  
  1134  	if v.DeclaredType == "" || v.Default == nil {
  1135  		return nil
  1136  	}
  1137  
  1138  	if v.inferTypeFromDefault() != v.Type() {
  1139  		return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')",
  1140  			v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable())
  1141  	}
  1142  
  1143  	return nil
  1144  }
  1145  
  1146  func (v *Variable) mergerName() string {
  1147  	return v.Name
  1148  }
  1149  
  1150  func (v *Variable) mergerMerge(m merger) merger {
  1151  	return v.Merge(m.(*Variable))
  1152  }
  1153  
  1154  // Required tests whether a variable is required or not.
  1155  func (v *Variable) Required() bool {
  1156  	return v.Default == nil
  1157  }
  1158  
  1159  // inferTypeFromDefault contains the logic for the old method of inferring
  1160  // variable types - we can also use this for validating that the declared
  1161  // type matches the type of the default value
  1162  func (v *Variable) inferTypeFromDefault() VariableType {
  1163  	if v.Default == nil {
  1164  		return VariableTypeString
  1165  	}
  1166  
  1167  	var s string
  1168  	if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil {
  1169  		v.Default = s
  1170  		return VariableTypeString
  1171  	}
  1172  
  1173  	var m map[string]interface{}
  1174  	if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil {
  1175  		v.Default = m
  1176  		return VariableTypeMap
  1177  	}
  1178  
  1179  	var l []interface{}
  1180  	if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil {
  1181  		v.Default = l
  1182  		return VariableTypeList
  1183  	}
  1184  
  1185  	return VariableTypeUnknown
  1186  }
  1187  
  1188  func (m ResourceMode) Taintable() bool {
  1189  	switch m {
  1190  	case ManagedResourceMode:
  1191  		return true
  1192  	case DataResourceMode:
  1193  		return false
  1194  	default:
  1195  		panic(fmt.Errorf("unsupported ResourceMode value %s", m))
  1196  	}
  1197  }