github.com/greysond/terraform@v0.8.5-0.20170124173113-439b5507bbe9/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  	"github.com/hashicorp/go-multierror"
    12  	"github.com/hashicorp/go-version"
    13  	"github.com/hashicorp/hil"
    14  	"github.com/hashicorp/hil/ast"
    15  	"github.com/hashicorp/terraform/helper/hilmapstructure"
    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  	Outputs         []*Output
    38  
    39  	// The fields below can be filled in by loaders for validation
    40  	// purposes.
    41  	unknownKeys []string
    42  }
    43  
    44  // Terraform is the Terraform meta-configuration that can be present
    45  // in configuration files for configuring Terraform itself.
    46  type Terraform struct {
    47  	RequiredVersion string `hcl:"required_version"` // Required Terraform version (constraint)
    48  }
    49  
    50  // AtlasConfig is the configuration for building in HashiCorp's Atlas.
    51  type AtlasConfig struct {
    52  	Name    string
    53  	Include []string
    54  	Exclude []string
    55  }
    56  
    57  // Module is a module used within a configuration.
    58  //
    59  // This does not represent a module itself, this represents a module
    60  // call-site within an existing configuration.
    61  type Module struct {
    62  	Name      string
    63  	Source    string
    64  	RawConfig *RawConfig
    65  }
    66  
    67  // ProviderConfig is the configuration for a resource provider.
    68  //
    69  // For example, Terraform needs to set the AWS access keys for the AWS
    70  // resource provider.
    71  type ProviderConfig struct {
    72  	Name      string
    73  	Alias     string
    74  	RawConfig *RawConfig
    75  }
    76  
    77  // A resource represents a single Terraform resource in the configuration.
    78  // A Terraform resource is something that supports some or all of the
    79  // usual "create, read, update, delete" operations, depending on
    80  // the given Mode.
    81  type Resource struct {
    82  	Mode         ResourceMode // which operations the resource supports
    83  	Name         string
    84  	Type         string
    85  	RawCount     *RawConfig
    86  	RawConfig    *RawConfig
    87  	Provisioners []*Provisioner
    88  	Provider     string
    89  	DependsOn    []string
    90  	Lifecycle    ResourceLifecycle
    91  }
    92  
    93  // Copy returns a copy of this Resource. Helpful for avoiding shared
    94  // config pointers across multiple pieces of the graph that need to do
    95  // interpolation.
    96  func (r *Resource) Copy() *Resource {
    97  	n := &Resource{
    98  		Mode:         r.Mode,
    99  		Name:         r.Name,
   100  		Type:         r.Type,
   101  		RawCount:     r.RawCount.Copy(),
   102  		RawConfig:    r.RawConfig.Copy(),
   103  		Provisioners: make([]*Provisioner, 0, len(r.Provisioners)),
   104  		Provider:     r.Provider,
   105  		DependsOn:    make([]string, len(r.DependsOn)),
   106  		Lifecycle:    *r.Lifecycle.Copy(),
   107  	}
   108  	for _, p := range r.Provisioners {
   109  		n.Provisioners = append(n.Provisioners, p.Copy())
   110  	}
   111  	copy(n.DependsOn, r.DependsOn)
   112  	return n
   113  }
   114  
   115  // ResourceLifecycle is used to store the lifecycle tuning parameters
   116  // to allow customized behavior
   117  type ResourceLifecycle struct {
   118  	CreateBeforeDestroy bool     `mapstructure:"create_before_destroy"`
   119  	PreventDestroy      bool     `mapstructure:"prevent_destroy"`
   120  	IgnoreChanges       []string `mapstructure:"ignore_changes"`
   121  }
   122  
   123  // Copy returns a copy of this ResourceLifecycle
   124  func (r *ResourceLifecycle) Copy() *ResourceLifecycle {
   125  	n := &ResourceLifecycle{
   126  		CreateBeforeDestroy: r.CreateBeforeDestroy,
   127  		PreventDestroy:      r.PreventDestroy,
   128  		IgnoreChanges:       make([]string, len(r.IgnoreChanges)),
   129  	}
   130  	copy(n.IgnoreChanges, r.IgnoreChanges)
   131  	return n
   132  }
   133  
   134  // Provisioner is a configured provisioner step on a resource.
   135  type Provisioner struct {
   136  	Type      string
   137  	RawConfig *RawConfig
   138  	ConnInfo  *RawConfig
   139  }
   140  
   141  // Copy returns a copy of this Provisioner
   142  func (p *Provisioner) Copy() *Provisioner {
   143  	return &Provisioner{
   144  		Type:      p.Type,
   145  		RawConfig: p.RawConfig.Copy(),
   146  		ConnInfo:  p.ConnInfo.Copy(),
   147  	}
   148  }
   149  
   150  // Variable is a variable defined within the configuration.
   151  type Variable struct {
   152  	Name         string
   153  	DeclaredType string `mapstructure:"type"`
   154  	Default      interface{}
   155  	Description  string
   156  }
   157  
   158  // Output is an output defined within the configuration. An output is
   159  // resulting data that is highlighted by Terraform when finished. An
   160  // output marked Sensitive will be output in a masked form following
   161  // application, but will still be available in state.
   162  type Output struct {
   163  	Name        string
   164  	DependsOn   []string
   165  	Description string
   166  	Sensitive   bool
   167  	RawConfig   *RawConfig
   168  }
   169  
   170  // VariableType is the type of value a variable is holding, and returned
   171  // by the Type() function on variables.
   172  type VariableType byte
   173  
   174  const (
   175  	VariableTypeUnknown VariableType = iota
   176  	VariableTypeString
   177  	VariableTypeList
   178  	VariableTypeMap
   179  )
   180  
   181  func (v VariableType) Printable() string {
   182  	switch v {
   183  	case VariableTypeString:
   184  		return "string"
   185  	case VariableTypeMap:
   186  		return "map"
   187  	case VariableTypeList:
   188  		return "list"
   189  	default:
   190  		return "unknown"
   191  	}
   192  }
   193  
   194  // ProviderConfigName returns the name of the provider configuration in
   195  // the given mapping that maps to the proper provider configuration
   196  // for this resource.
   197  func ProviderConfigName(t string, pcs []*ProviderConfig) string {
   198  	lk := ""
   199  	for _, v := range pcs {
   200  		k := v.Name
   201  		if strings.HasPrefix(t, k) && len(k) > len(lk) {
   202  			lk = k
   203  		}
   204  	}
   205  
   206  	return lk
   207  }
   208  
   209  // A unique identifier for this module.
   210  func (r *Module) Id() string {
   211  	return fmt.Sprintf("%s", r.Name)
   212  }
   213  
   214  // Count returns the count of this resource.
   215  func (r *Resource) Count() (int, error) {
   216  	v, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0)
   217  	if err != nil {
   218  		return 0, err
   219  	}
   220  
   221  	return int(v), nil
   222  }
   223  
   224  // A unique identifier for this resource.
   225  func (r *Resource) Id() string {
   226  	switch r.Mode {
   227  	case ManagedResourceMode:
   228  		return fmt.Sprintf("%s.%s", r.Type, r.Name)
   229  	case DataResourceMode:
   230  		return fmt.Sprintf("data.%s.%s", r.Type, r.Name)
   231  	default:
   232  		panic(fmt.Errorf("unknown resource mode %s", r.Mode))
   233  	}
   234  }
   235  
   236  // Validate does some basic semantic checking of the configuration.
   237  func (c *Config) Validate() error {
   238  	if c == nil {
   239  		return nil
   240  	}
   241  
   242  	var errs []error
   243  
   244  	for _, k := range c.unknownKeys {
   245  		errs = append(errs, fmt.Errorf(
   246  			"Unknown root level key: %s", k))
   247  	}
   248  
   249  	// Validate the Terraform config
   250  	if tf := c.Terraform; tf != nil {
   251  		if raw := tf.RequiredVersion; raw != "" {
   252  			// Check that the value has no interpolations
   253  			rc, err := NewRawConfig(map[string]interface{}{
   254  				"root": raw,
   255  			})
   256  			if err != nil {
   257  				errs = append(errs, fmt.Errorf(
   258  					"terraform.required_version: %s", err))
   259  			} else if len(rc.Interpolations) > 0 {
   260  				errs = append(errs, fmt.Errorf(
   261  					"terraform.required_version: cannot contain interpolations"))
   262  			} else {
   263  				// Check it is valid
   264  				_, err := version.NewConstraint(raw)
   265  				if err != nil {
   266  					errs = append(errs, fmt.Errorf(
   267  						"terraform.required_version: invalid syntax: %s", err))
   268  				}
   269  			}
   270  		}
   271  	}
   272  
   273  	vars := c.InterpolatedVariables()
   274  	varMap := make(map[string]*Variable)
   275  	for _, v := range c.Variables {
   276  		if _, ok := varMap[v.Name]; ok {
   277  			errs = append(errs, fmt.Errorf(
   278  				"Variable '%s': duplicate found. Variable names must be unique.",
   279  				v.Name))
   280  		}
   281  
   282  		varMap[v.Name] = v
   283  	}
   284  
   285  	for k, _ := range varMap {
   286  		if !NameRegexp.MatchString(k) {
   287  			errs = append(errs, fmt.Errorf(
   288  				"variable %q: variable name must match regular expresion %s",
   289  				k, NameRegexp))
   290  		}
   291  	}
   292  
   293  	for _, v := range c.Variables {
   294  		if v.Type() == VariableTypeUnknown {
   295  			errs = append(errs, fmt.Errorf(
   296  				"Variable '%s': must be a string or a map",
   297  				v.Name))
   298  			continue
   299  		}
   300  
   301  		interp := false
   302  		fn := func(ast.Node) (interface{}, error) {
   303  			interp = true
   304  			return "", nil
   305  		}
   306  
   307  		w := &interpolationWalker{F: fn}
   308  		if v.Default != nil {
   309  			if err := reflectwalk.Walk(v.Default, w); err == nil {
   310  				if interp {
   311  					errs = append(errs, fmt.Errorf(
   312  						"Variable '%s': cannot contain interpolations",
   313  						v.Name))
   314  				}
   315  			}
   316  		}
   317  	}
   318  
   319  	// Check for references to user variables that do not actually
   320  	// exist and record those errors.
   321  	for source, vs := range vars {
   322  		for _, v := range vs {
   323  			uv, ok := v.(*UserVariable)
   324  			if !ok {
   325  				continue
   326  			}
   327  
   328  			if _, ok := varMap[uv.Name]; !ok {
   329  				errs = append(errs, fmt.Errorf(
   330  					"%s: unknown variable referenced: '%s'. define it with 'variable' blocks",
   331  					source,
   332  					uv.Name))
   333  			}
   334  		}
   335  	}
   336  
   337  	// Check that all count variables are valid.
   338  	for source, vs := range vars {
   339  		for _, rawV := range vs {
   340  			switch v := rawV.(type) {
   341  			case *CountVariable:
   342  				if v.Type == CountValueInvalid {
   343  					errs = append(errs, fmt.Errorf(
   344  						"%s: invalid count variable: %s",
   345  						source,
   346  						v.FullKey()))
   347  				}
   348  			case *PathVariable:
   349  				if v.Type == PathValueInvalid {
   350  					errs = append(errs, fmt.Errorf(
   351  						"%s: invalid path variable: %s",
   352  						source,
   353  						v.FullKey()))
   354  				}
   355  			}
   356  		}
   357  	}
   358  
   359  	// Check that providers aren't declared multiple times.
   360  	providerSet := make(map[string]struct{})
   361  	for _, p := range c.ProviderConfigs {
   362  		name := p.FullName()
   363  		if _, ok := providerSet[name]; ok {
   364  			errs = append(errs, fmt.Errorf(
   365  				"provider.%s: declared multiple times, you can only declare a provider once",
   366  				name))
   367  			continue
   368  		}
   369  
   370  		providerSet[name] = struct{}{}
   371  	}
   372  
   373  	// Check that all references to modules are valid
   374  	modules := make(map[string]*Module)
   375  	dupped := make(map[string]struct{})
   376  	for _, m := range c.Modules {
   377  		// Check for duplicates
   378  		if _, ok := modules[m.Id()]; ok {
   379  			if _, ok := dupped[m.Id()]; !ok {
   380  				dupped[m.Id()] = struct{}{}
   381  
   382  				errs = append(errs, fmt.Errorf(
   383  					"%s: module repeated multiple times",
   384  					m.Id()))
   385  			}
   386  
   387  			// Already seen this module, just skip it
   388  			continue
   389  		}
   390  
   391  		modules[m.Id()] = m
   392  
   393  		// Check that the source has no interpolations
   394  		rc, err := NewRawConfig(map[string]interface{}{
   395  			"root": m.Source,
   396  		})
   397  		if err != nil {
   398  			errs = append(errs, fmt.Errorf(
   399  				"%s: module source error: %s",
   400  				m.Id(), err))
   401  		} else if len(rc.Interpolations) > 0 {
   402  			errs = append(errs, fmt.Errorf(
   403  				"%s: module source cannot contain interpolations",
   404  				m.Id()))
   405  		}
   406  
   407  		// Check that the name matches our regexp
   408  		if !NameRegexp.Match([]byte(m.Name)) {
   409  			errs = append(errs, fmt.Errorf(
   410  				"%s: module name can only contain letters, numbers, "+
   411  					"dashes, and underscores",
   412  				m.Id()))
   413  		}
   414  
   415  		// Check that the configuration can all be strings, lists or maps
   416  		raw := make(map[string]interface{})
   417  		for k, v := range m.RawConfig.Raw {
   418  			var strVal string
   419  			if err := hilmapstructure.WeakDecode(v, &strVal); err == nil {
   420  				raw[k] = strVal
   421  				continue
   422  			}
   423  
   424  			var mapVal map[string]interface{}
   425  			if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil {
   426  				raw[k] = mapVal
   427  				continue
   428  			}
   429  
   430  			var sliceVal []interface{}
   431  			if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil {
   432  				raw[k] = sliceVal
   433  				continue
   434  			}
   435  
   436  			errs = append(errs, fmt.Errorf(
   437  				"%s: variable %s must be a string, list or map value",
   438  				m.Id(), k))
   439  		}
   440  
   441  		// Check for invalid count variables
   442  		for _, v := range m.RawConfig.Variables {
   443  			switch v.(type) {
   444  			case *CountVariable:
   445  				errs = append(errs, fmt.Errorf(
   446  					"%s: count variables are only valid within resources", m.Name))
   447  			case *SelfVariable:
   448  				errs = append(errs, fmt.Errorf(
   449  					"%s: self variables are only valid within resources", m.Name))
   450  			}
   451  		}
   452  
   453  		// Update the raw configuration to only contain the string values
   454  		m.RawConfig, err = NewRawConfig(raw)
   455  		if err != nil {
   456  			errs = append(errs, fmt.Errorf(
   457  				"%s: can't initialize configuration: %s",
   458  				m.Id(), err))
   459  		}
   460  	}
   461  	dupped = nil
   462  
   463  	// Check that all variables for modules reference modules that
   464  	// exist.
   465  	for source, vs := range vars {
   466  		for _, v := range vs {
   467  			mv, ok := v.(*ModuleVariable)
   468  			if !ok {
   469  				continue
   470  			}
   471  
   472  			if _, ok := modules[mv.Name]; !ok {
   473  				errs = append(errs, fmt.Errorf(
   474  					"%s: unknown module referenced: %s",
   475  					source,
   476  					mv.Name))
   477  			}
   478  		}
   479  	}
   480  
   481  	// Check that all references to resources are valid
   482  	resources := make(map[string]*Resource)
   483  	dupped = make(map[string]struct{})
   484  	for _, r := range c.Resources {
   485  		if _, ok := resources[r.Id()]; ok {
   486  			if _, ok := dupped[r.Id()]; !ok {
   487  				dupped[r.Id()] = struct{}{}
   488  
   489  				errs = append(errs, fmt.Errorf(
   490  					"%s: resource repeated multiple times",
   491  					r.Id()))
   492  			}
   493  		}
   494  
   495  		resources[r.Id()] = r
   496  	}
   497  	dupped = nil
   498  
   499  	// Validate resources
   500  	for n, r := range resources {
   501  		// Verify count variables
   502  		for _, v := range r.RawCount.Variables {
   503  			switch v.(type) {
   504  			case *CountVariable:
   505  				errs = append(errs, fmt.Errorf(
   506  					"%s: resource count can't reference count variable: %s",
   507  					n,
   508  					v.FullKey()))
   509  			case *ModuleVariable:
   510  				errs = append(errs, fmt.Errorf(
   511  					"%s: resource count can't reference module variable: %s",
   512  					n,
   513  					v.FullKey()))
   514  			case *ResourceVariable:
   515  				errs = append(errs, fmt.Errorf(
   516  					"%s: resource count can't reference resource variable: %s",
   517  					n,
   518  					v.FullKey()))
   519  			case *SimpleVariable:
   520  				errs = append(errs, fmt.Errorf(
   521  					"%s: resource count can't reference variable: %s",
   522  					n,
   523  					v.FullKey()))
   524  			case *UserVariable:
   525  				// Good
   526  			default:
   527  				panic(fmt.Sprintf("Unknown type in count var in %s: %T", n, v))
   528  			}
   529  		}
   530  
   531  		// Interpolate with a fixed number to verify that its a number.
   532  		r.RawCount.interpolate(func(root ast.Node) (interface{}, error) {
   533  			// Execute the node but transform the AST so that it returns
   534  			// a fixed value of "5" for all interpolations.
   535  			result, err := hil.Eval(
   536  				hil.FixedValueTransform(
   537  					root, &ast.LiteralNode{Value: "5", Typex: ast.TypeString}),
   538  				nil)
   539  			if err != nil {
   540  				return "", err
   541  			}
   542  
   543  			return result.Value, nil
   544  		})
   545  		_, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0)
   546  		if err != nil {
   547  			errs = append(errs, fmt.Errorf(
   548  				"%s: resource count must be an integer",
   549  				n))
   550  		}
   551  		r.RawCount.init()
   552  
   553  		// Validate DependsOn
   554  		errs = append(errs, c.validateDependsOn(n, r.DependsOn, resources, modules)...)
   555  
   556  		// Verify provisioners don't contain any splats
   557  		for _, p := range r.Provisioners {
   558  			// This validation checks that there are now splat variables
   559  			// referencing ourself. This currently is not allowed.
   560  
   561  			for _, v := range p.ConnInfo.Variables {
   562  				rv, ok := v.(*ResourceVariable)
   563  				if !ok {
   564  					continue
   565  				}
   566  
   567  				if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
   568  					errs = append(errs, fmt.Errorf(
   569  						"%s: connection info cannot contain splat variable "+
   570  							"referencing itself", n))
   571  					break
   572  				}
   573  			}
   574  
   575  			for _, v := range p.RawConfig.Variables {
   576  				rv, ok := v.(*ResourceVariable)
   577  				if !ok {
   578  					continue
   579  				}
   580  
   581  				if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name {
   582  					errs = append(errs, fmt.Errorf(
   583  						"%s: connection info cannot contain splat variable "+
   584  							"referencing itself", n))
   585  					break
   586  				}
   587  			}
   588  		}
   589  
   590  		// Verify ignore_changes contains valid entries
   591  		for _, v := range r.Lifecycle.IgnoreChanges {
   592  			if strings.Contains(v, "*") && v != "*" {
   593  				errs = append(errs, fmt.Errorf(
   594  					"%s: ignore_changes does not support using a partial string "+
   595  						"together with a wildcard: %s", n, v))
   596  			}
   597  		}
   598  
   599  		// Verify ignore_changes has no interpolations
   600  		rc, err := NewRawConfig(map[string]interface{}{
   601  			"root": r.Lifecycle.IgnoreChanges,
   602  		})
   603  		if err != nil {
   604  			errs = append(errs, fmt.Errorf(
   605  				"%s: lifecycle ignore_changes error: %s",
   606  				n, err))
   607  		} else if len(rc.Interpolations) > 0 {
   608  			errs = append(errs, fmt.Errorf(
   609  				"%s: lifecycle ignore_changes cannot contain interpolations",
   610  				n))
   611  		}
   612  
   613  		// If it is a data source then it can't have provisioners
   614  		if r.Mode == DataResourceMode {
   615  			if _, ok := r.RawConfig.Raw["provisioner"]; ok {
   616  				errs = append(errs, fmt.Errorf(
   617  					"%s: data sources cannot have provisioners",
   618  					n))
   619  			}
   620  		}
   621  	}
   622  
   623  	for source, vs := range vars {
   624  		for _, v := range vs {
   625  			rv, ok := v.(*ResourceVariable)
   626  			if !ok {
   627  				continue
   628  			}
   629  
   630  			id := rv.ResourceId()
   631  			if _, ok := resources[id]; !ok {
   632  				errs = append(errs, fmt.Errorf(
   633  					"%s: unknown resource '%s' referenced in variable %s",
   634  					source,
   635  					id,
   636  					rv.FullKey()))
   637  				continue
   638  			}
   639  		}
   640  	}
   641  
   642  	// Check that all outputs are valid
   643  	{
   644  		found := make(map[string]struct{})
   645  		for _, o := range c.Outputs {
   646  			// Verify the output is new
   647  			if _, ok := found[o.Name]; ok {
   648  				errs = append(errs, fmt.Errorf(
   649  					"%s: duplicate output. output names must be unique.",
   650  					o.Name))
   651  				continue
   652  			}
   653  			found[o.Name] = struct{}{}
   654  
   655  			var invalidKeys []string
   656  			valueKeyFound := false
   657  			for k := range o.RawConfig.Raw {
   658  				if k == "value" {
   659  					valueKeyFound = true
   660  					continue
   661  				}
   662  				if k == "sensitive" {
   663  					if sensitive, ok := o.RawConfig.config[k].(bool); ok {
   664  						if sensitive {
   665  							o.Sensitive = true
   666  						}
   667  						continue
   668  					}
   669  
   670  					errs = append(errs, fmt.Errorf(
   671  						"%s: value for 'sensitive' must be boolean",
   672  						o.Name))
   673  					continue
   674  				}
   675  				if k == "description" {
   676  					if desc, ok := o.RawConfig.config[k].(string); ok {
   677  						o.Description = desc
   678  						continue
   679  					}
   680  
   681  					errs = append(errs, fmt.Errorf(
   682  						"%s: value for 'description' must be string",
   683  						o.Name))
   684  					continue
   685  				}
   686  				invalidKeys = append(invalidKeys, k)
   687  			}
   688  			if len(invalidKeys) > 0 {
   689  				errs = append(errs, fmt.Errorf(
   690  					"%s: output has invalid keys: %s",
   691  					o.Name, strings.Join(invalidKeys, ", ")))
   692  			}
   693  			if !valueKeyFound {
   694  				errs = append(errs, fmt.Errorf(
   695  					"%s: output is missing required 'value' key", o.Name))
   696  			}
   697  
   698  			for _, v := range o.RawConfig.Variables {
   699  				if _, ok := v.(*CountVariable); ok {
   700  					errs = append(errs, fmt.Errorf(
   701  						"%s: count variables are only valid within resources", o.Name))
   702  				}
   703  			}
   704  		}
   705  	}
   706  
   707  	// Check that all variables are in the proper context
   708  	for source, rc := range c.rawConfigs() {
   709  		walker := &interpolationWalker{
   710  			ContextF: c.validateVarContextFn(source, &errs),
   711  		}
   712  		if err := reflectwalk.Walk(rc.Raw, walker); err != nil {
   713  			errs = append(errs, fmt.Errorf(
   714  				"%s: error reading config: %s", source, err))
   715  		}
   716  	}
   717  
   718  	// Validate the self variable
   719  	for source, rc := range c.rawConfigs() {
   720  		// Ignore provisioners. This is a pretty brittle way to do this,
   721  		// but better than also repeating all the resources.
   722  		if strings.Contains(source, "provision") {
   723  			continue
   724  		}
   725  
   726  		for _, v := range rc.Variables {
   727  			if _, ok := v.(*SelfVariable); ok {
   728  				errs = append(errs, fmt.Errorf(
   729  					"%s: cannot contain self-reference %s", source, v.FullKey()))
   730  			}
   731  		}
   732  	}
   733  
   734  	if len(errs) > 0 {
   735  		return &multierror.Error{Errors: errs}
   736  	}
   737  
   738  	return nil
   739  }
   740  
   741  // InterpolatedVariables is a helper that returns a mapping of all the interpolated
   742  // variables within the configuration. This is used to verify references
   743  // are valid in the Validate step.
   744  func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable {
   745  	result := make(map[string][]InterpolatedVariable)
   746  	for source, rc := range c.rawConfigs() {
   747  		for _, v := range rc.Variables {
   748  			result[source] = append(result[source], v)
   749  		}
   750  	}
   751  	return result
   752  }
   753  
   754  // rawConfigs returns all of the RawConfigs that are available keyed by
   755  // a human-friendly source.
   756  func (c *Config) rawConfigs() map[string]*RawConfig {
   757  	result := make(map[string]*RawConfig)
   758  	for _, m := range c.Modules {
   759  		source := fmt.Sprintf("module '%s'", m.Name)
   760  		result[source] = m.RawConfig
   761  	}
   762  
   763  	for _, pc := range c.ProviderConfigs {
   764  		source := fmt.Sprintf("provider config '%s'", pc.Name)
   765  		result[source] = pc.RawConfig
   766  	}
   767  
   768  	for _, rc := range c.Resources {
   769  		source := fmt.Sprintf("resource '%s'", rc.Id())
   770  		result[source+" count"] = rc.RawCount
   771  		result[source+" config"] = rc.RawConfig
   772  
   773  		for i, p := range rc.Provisioners {
   774  			subsource := fmt.Sprintf(
   775  				"%s provisioner %s (#%d)",
   776  				source, p.Type, i+1)
   777  			result[subsource] = p.RawConfig
   778  		}
   779  	}
   780  
   781  	for _, o := range c.Outputs {
   782  		source := fmt.Sprintf("output '%s'", o.Name)
   783  		result[source] = o.RawConfig
   784  	}
   785  
   786  	return result
   787  }
   788  
   789  func (c *Config) validateVarContextFn(
   790  	source string, errs *[]error) interpolationWalkerContextFunc {
   791  	return func(loc reflectwalk.Location, node ast.Node) {
   792  		// If we're in a slice element, then its fine, since you can do
   793  		// anything in there.
   794  		if loc == reflectwalk.SliceElem {
   795  			return
   796  		}
   797  
   798  		// Otherwise, let's check if there is a splat resource variable
   799  		// at the top level in here. We do this by doing a transform that
   800  		// replaces everything with a noop node unless its a variable
   801  		// access or concat. This should turn the AST into a flat tree
   802  		// of Concat(Noop, ...). If there are any variables left that are
   803  		// multi-access, then its still broken.
   804  		node = node.Accept(func(n ast.Node) ast.Node {
   805  			// If it is a concat or variable access, we allow it.
   806  			switch n.(type) {
   807  			case *ast.Output:
   808  				return n
   809  			case *ast.VariableAccess:
   810  				return n
   811  			}
   812  
   813  			// Otherwise, noop
   814  			return &noopNode{}
   815  		})
   816  
   817  		vars, err := DetectVariables(node)
   818  		if err != nil {
   819  			// Ignore it since this will be caught during parse. This
   820  			// actually probably should never happen by the time this
   821  			// is called, but its okay.
   822  			return
   823  		}
   824  
   825  		for _, v := range vars {
   826  			rv, ok := v.(*ResourceVariable)
   827  			if !ok {
   828  				return
   829  			}
   830  
   831  			if rv.Multi && rv.Index == -1 {
   832  				*errs = append(*errs, fmt.Errorf(
   833  					"%s: use of the splat ('*') operator must be wrapped in a list declaration",
   834  					source))
   835  			}
   836  		}
   837  	}
   838  }
   839  
   840  func (c *Config) validateDependsOn(
   841  	n string,
   842  	v []string,
   843  	resources map[string]*Resource,
   844  	modules map[string]*Module) []error {
   845  	// Verify depends on points to resources that all exist
   846  	var errs []error
   847  	for _, d := range v {
   848  		// Check if we contain interpolations
   849  		rc, err := NewRawConfig(map[string]interface{}{
   850  			"value": d,
   851  		})
   852  		if err == nil && len(rc.Variables) > 0 {
   853  			errs = append(errs, fmt.Errorf(
   854  				"%s: depends on value cannot contain interpolations: %s",
   855  				n, d))
   856  			continue
   857  		}
   858  
   859  		// If it is a module, verify it is a module
   860  		if strings.HasPrefix(d, "module.") {
   861  			name := d[len("module."):]
   862  			if _, ok := modules[name]; !ok {
   863  				errs = append(errs, fmt.Errorf(
   864  					"%s: resource depends on non-existent module '%s'",
   865  					n, name))
   866  			}
   867  
   868  			continue
   869  		}
   870  
   871  		// Check resources
   872  		if _, ok := resources[d]; !ok {
   873  			errs = append(errs, fmt.Errorf(
   874  				"%s: resource depends on non-existent resource '%s'",
   875  				n, d))
   876  		}
   877  	}
   878  
   879  	return errs
   880  }
   881  
   882  func (m *Module) mergerName() string {
   883  	return m.Id()
   884  }
   885  
   886  func (m *Module) mergerMerge(other merger) merger {
   887  	m2 := other.(*Module)
   888  
   889  	result := *m
   890  	result.Name = m2.Name
   891  	result.RawConfig = result.RawConfig.merge(m2.RawConfig)
   892  
   893  	if m2.Source != "" {
   894  		result.Source = m2.Source
   895  	}
   896  
   897  	return &result
   898  }
   899  
   900  func (o *Output) mergerName() string {
   901  	return o.Name
   902  }
   903  
   904  func (o *Output) mergerMerge(m merger) merger {
   905  	o2 := m.(*Output)
   906  
   907  	result := *o
   908  	result.Name = o2.Name
   909  	result.Description = o2.Description
   910  	result.RawConfig = result.RawConfig.merge(o2.RawConfig)
   911  	result.Sensitive = o2.Sensitive
   912  	result.DependsOn = o2.DependsOn
   913  
   914  	return &result
   915  }
   916  
   917  func (c *ProviderConfig) GoString() string {
   918  	return fmt.Sprintf("*%#v", *c)
   919  }
   920  
   921  func (c *ProviderConfig) FullName() string {
   922  	if c.Alias == "" {
   923  		return c.Name
   924  	}
   925  
   926  	return fmt.Sprintf("%s.%s", c.Name, c.Alias)
   927  }
   928  
   929  func (c *ProviderConfig) mergerName() string {
   930  	return c.Name
   931  }
   932  
   933  func (c *ProviderConfig) mergerMerge(m merger) merger {
   934  	c2 := m.(*ProviderConfig)
   935  
   936  	result := *c
   937  	result.Name = c2.Name
   938  	result.RawConfig = result.RawConfig.merge(c2.RawConfig)
   939  
   940  	if c2.Alias != "" {
   941  		result.Alias = c2.Alias
   942  	}
   943  
   944  	return &result
   945  }
   946  
   947  func (r *Resource) mergerName() string {
   948  	return r.Id()
   949  }
   950  
   951  func (r *Resource) mergerMerge(m merger) merger {
   952  	r2 := m.(*Resource)
   953  
   954  	result := *r
   955  	result.Mode = r2.Mode
   956  	result.Name = r2.Name
   957  	result.Type = r2.Type
   958  	result.RawConfig = result.RawConfig.merge(r2.RawConfig)
   959  
   960  	if r2.RawCount.Value() != "1" {
   961  		result.RawCount = r2.RawCount
   962  	}
   963  
   964  	if len(r2.Provisioners) > 0 {
   965  		result.Provisioners = r2.Provisioners
   966  	}
   967  
   968  	return &result
   969  }
   970  
   971  // Merge merges two variables to create a new third variable.
   972  func (v *Variable) Merge(v2 *Variable) *Variable {
   973  	// Shallow copy the variable
   974  	result := *v
   975  
   976  	// The names should be the same, but the second name always wins.
   977  	result.Name = v2.Name
   978  
   979  	if v2.DeclaredType != "" {
   980  		result.DeclaredType = v2.DeclaredType
   981  	}
   982  	if v2.Default != nil {
   983  		result.Default = v2.Default
   984  	}
   985  	if v2.Description != "" {
   986  		result.Description = v2.Description
   987  	}
   988  
   989  	return &result
   990  }
   991  
   992  var typeStringMap = map[string]VariableType{
   993  	"string": VariableTypeString,
   994  	"map":    VariableTypeMap,
   995  	"list":   VariableTypeList,
   996  }
   997  
   998  // Type returns the type of variable this is.
   999  func (v *Variable) Type() VariableType {
  1000  	if v.DeclaredType != "" {
  1001  		declaredType, ok := typeStringMap[v.DeclaredType]
  1002  		if !ok {
  1003  			return VariableTypeUnknown
  1004  		}
  1005  
  1006  		return declaredType
  1007  	}
  1008  
  1009  	return v.inferTypeFromDefault()
  1010  }
  1011  
  1012  // ValidateTypeAndDefault ensures that default variable value is compatible
  1013  // with the declared type (if one exists), and that the type is one which is
  1014  // known to Terraform
  1015  func (v *Variable) ValidateTypeAndDefault() error {
  1016  	// If an explicit type is declared, ensure it is valid
  1017  	if v.DeclaredType != "" {
  1018  		if _, ok := typeStringMap[v.DeclaredType]; !ok {
  1019  			return fmt.Errorf("Variable '%s' must be of type string or map - '%s' is not a valid type", v.Name, v.DeclaredType)
  1020  		}
  1021  	}
  1022  
  1023  	if v.DeclaredType == "" || v.Default == nil {
  1024  		return nil
  1025  	}
  1026  
  1027  	if v.inferTypeFromDefault() != v.Type() {
  1028  		return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')",
  1029  			v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable())
  1030  	}
  1031  
  1032  	return nil
  1033  }
  1034  
  1035  func (v *Variable) mergerName() string {
  1036  	return v.Name
  1037  }
  1038  
  1039  func (v *Variable) mergerMerge(m merger) merger {
  1040  	return v.Merge(m.(*Variable))
  1041  }
  1042  
  1043  // Required tests whether a variable is required or not.
  1044  func (v *Variable) Required() bool {
  1045  	return v.Default == nil
  1046  }
  1047  
  1048  // inferTypeFromDefault contains the logic for the old method of inferring
  1049  // variable types - we can also use this for validating that the declared
  1050  // type matches the type of the default value
  1051  func (v *Variable) inferTypeFromDefault() VariableType {
  1052  	if v.Default == nil {
  1053  		return VariableTypeString
  1054  	}
  1055  
  1056  	var s string
  1057  	if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil {
  1058  		v.Default = s
  1059  		return VariableTypeString
  1060  	}
  1061  
  1062  	var m map[string]interface{}
  1063  	if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil {
  1064  		v.Default = m
  1065  		return VariableTypeMap
  1066  	}
  1067  
  1068  	var l []interface{}
  1069  	if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil {
  1070  		v.Default = l
  1071  		return VariableTypeList
  1072  	}
  1073  
  1074  	return VariableTypeUnknown
  1075  }
  1076  
  1077  func (m ResourceMode) Taintable() bool {
  1078  	switch m {
  1079  	case ManagedResourceMode:
  1080  		return true
  1081  	case DataResourceMode:
  1082  		return false
  1083  	default:
  1084  		panic(fmt.Errorf("unsupported ResourceMode value %s", m))
  1085  	}
  1086  }