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