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