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