github.com/tomaszheflik/terraform@v0.7.3-0.20160827060421-32f990b41594/terraform/interpolate.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"regexp"
     8  	"sort"
     9  	"strings"
    10  	"sync"
    11  
    12  	"github.com/hashicorp/hil"
    13  	"github.com/hashicorp/hil/ast"
    14  	"github.com/hashicorp/terraform/config"
    15  	"github.com/hashicorp/terraform/config/module"
    16  	"github.com/hashicorp/terraform/flatmap"
    17  )
    18  
    19  const (
    20  	// VarEnvPrefix is the prefix of variables that are read from
    21  	// the environment to set variables here.
    22  	VarEnvPrefix = "TF_VAR_"
    23  )
    24  
    25  // Interpolater is the structure responsible for determining the values
    26  // for interpolations such as `aws_instance.foo.bar`.
    27  type Interpolater struct {
    28  	Operation          walkOperation
    29  	Module             *module.Tree
    30  	State              *State
    31  	StateLock          *sync.RWMutex
    32  	VariableValues     map[string]interface{}
    33  	VariableValuesLock *sync.Mutex
    34  }
    35  
    36  // InterpolationScope is the current scope of execution. This is required
    37  // since some variables which are interpolated are dependent on what we're
    38  // operating on and where we are.
    39  type InterpolationScope struct {
    40  	Path     []string
    41  	Resource *Resource
    42  }
    43  
    44  // Values returns the values for all the variables in the given map.
    45  func (i *Interpolater) Values(
    46  	scope *InterpolationScope,
    47  	vars map[string]config.InterpolatedVariable) (map[string]ast.Variable, error) {
    48  	result := make(map[string]ast.Variable, len(vars))
    49  
    50  	// Copy the default variables
    51  	if i.Module != nil && scope != nil {
    52  		mod := i.Module
    53  		if len(scope.Path) > 1 {
    54  			mod = i.Module.Child(scope.Path[1:])
    55  		}
    56  		for _, v := range mod.Config().Variables {
    57  			// Set default variables
    58  			if v.Default == nil {
    59  				continue
    60  			}
    61  
    62  			n := fmt.Sprintf("var.%s", v.Name)
    63  			variable, err := hil.InterfaceToVariable(v.Default)
    64  			if err != nil {
    65  				return nil, fmt.Errorf("invalid default map value for %s: %v", v.Name, v.Default)
    66  			}
    67  
    68  			result[n] = variable
    69  		}
    70  	}
    71  
    72  	for n, rawV := range vars {
    73  		var err error
    74  		switch v := rawV.(type) {
    75  		case *config.CountVariable:
    76  			err = i.valueCountVar(scope, n, v, result)
    77  		case *config.ModuleVariable:
    78  			err = i.valueModuleVar(scope, n, v, result)
    79  		case *config.PathVariable:
    80  			err = i.valuePathVar(scope, n, v, result)
    81  		case *config.ResourceVariable:
    82  			err = i.valueResourceVar(scope, n, v, result)
    83  		case *config.SelfVariable:
    84  			err = i.valueSelfVar(scope, n, v, result)
    85  		case *config.SimpleVariable:
    86  			err = i.valueSimpleVar(scope, n, v, result)
    87  		case *config.UserVariable:
    88  			err = i.valueUserVar(scope, n, v, result)
    89  		default:
    90  			err = fmt.Errorf("%s: unknown variable type: %T", n, rawV)
    91  		}
    92  
    93  		if err != nil {
    94  			return nil, err
    95  		}
    96  	}
    97  
    98  	return result, nil
    99  }
   100  
   101  func (i *Interpolater) valueCountVar(
   102  	scope *InterpolationScope,
   103  	n string,
   104  	v *config.CountVariable,
   105  	result map[string]ast.Variable) error {
   106  	switch v.Type {
   107  	case config.CountValueIndex:
   108  		if scope.Resource == nil {
   109  			return fmt.Errorf("%s: count.index is only valid within resources", n)
   110  		}
   111  		result[n] = ast.Variable{
   112  			Value: scope.Resource.CountIndex,
   113  			Type:  ast.TypeInt,
   114  		}
   115  		return nil
   116  	default:
   117  		return fmt.Errorf("%s: unknown count type: %#v", n, v.Type)
   118  	}
   119  }
   120  
   121  func unknownVariable() ast.Variable {
   122  	return ast.Variable{
   123  		Type:  ast.TypeString,
   124  		Value: config.UnknownVariableValue,
   125  	}
   126  }
   127  
   128  func (i *Interpolater) valueModuleVar(
   129  	scope *InterpolationScope,
   130  	n string,
   131  	v *config.ModuleVariable,
   132  	result map[string]ast.Variable) error {
   133  
   134  	// Build the path to the child module we want
   135  	path := make([]string, len(scope.Path), len(scope.Path)+1)
   136  	copy(path, scope.Path)
   137  	path = append(path, v.Name)
   138  
   139  	// Grab the lock so that if other interpolations are running or
   140  	// state is being modified, we'll be safe.
   141  	i.StateLock.RLock()
   142  	defer i.StateLock.RUnlock()
   143  
   144  	// Get the module where we're looking for the value
   145  	mod := i.State.ModuleByPath(path)
   146  	if mod == nil {
   147  		// If the module doesn't exist, then we can return an empty string.
   148  		// This happens usually only in Refresh() when we haven't populated
   149  		// a state. During validation, we semantically verify that all
   150  		// modules reference other modules, and graph ordering should
   151  		// ensure that the module is in the state, so if we reach this
   152  		// point otherwise it really is a panic.
   153  		result[n] = unknownVariable()
   154  	} else {
   155  		// Get the value from the outputs
   156  		if outputState, ok := mod.Outputs[v.Field]; ok {
   157  			output, err := hil.InterfaceToVariable(outputState.Value)
   158  			if err != nil {
   159  				return err
   160  			}
   161  			result[n] = output
   162  		} else {
   163  			// Same reasons as the comment above.
   164  			result[n] = unknownVariable()
   165  		}
   166  	}
   167  
   168  	return nil
   169  }
   170  
   171  func (i *Interpolater) valuePathVar(
   172  	scope *InterpolationScope,
   173  	n string,
   174  	v *config.PathVariable,
   175  	result map[string]ast.Variable) error {
   176  	switch v.Type {
   177  	case config.PathValueCwd:
   178  		wd, err := os.Getwd()
   179  		if err != nil {
   180  			return fmt.Errorf(
   181  				"Couldn't get cwd for var %s: %s",
   182  				v.FullKey(), err)
   183  		}
   184  
   185  		result[n] = ast.Variable{
   186  			Value: wd,
   187  			Type:  ast.TypeString,
   188  		}
   189  	case config.PathValueModule:
   190  		if t := i.Module.Child(scope.Path[1:]); t != nil {
   191  			result[n] = ast.Variable{
   192  				Value: t.Config().Dir,
   193  				Type:  ast.TypeString,
   194  			}
   195  		}
   196  	case config.PathValueRoot:
   197  		result[n] = ast.Variable{
   198  			Value: i.Module.Config().Dir,
   199  			Type:  ast.TypeString,
   200  		}
   201  	default:
   202  		return fmt.Errorf("%s: unknown path type: %#v", n, v.Type)
   203  	}
   204  
   205  	return nil
   206  
   207  }
   208  
   209  func (i *Interpolater) valueResourceVar(
   210  	scope *InterpolationScope,
   211  	n string,
   212  	v *config.ResourceVariable,
   213  	result map[string]ast.Variable) error {
   214  	// If we're computing all dynamic fields, then module vars count
   215  	// and we mark it as computed.
   216  	if i.Operation == walkValidate {
   217  		result[n] = ast.Variable{
   218  			Value: config.UnknownVariableValue,
   219  			Type:  ast.TypeString,
   220  		}
   221  		return nil
   222  	}
   223  
   224  	var variable *ast.Variable
   225  	var err error
   226  
   227  	if v.Multi && v.Index == -1 {
   228  		variable, err = i.computeResourceMultiVariable(scope, v)
   229  	} else {
   230  		variable, err = i.computeResourceVariable(scope, v)
   231  	}
   232  
   233  	if err != nil {
   234  		return err
   235  	}
   236  
   237  	if variable == nil {
   238  		// During the input walk we tolerate missing variables because
   239  		// we haven't yet had a chance to refresh state, so dynamic data may
   240  		// not yet be complete.
   241  		// If it truly is missing, we'll catch it on a later walk.
   242  		// This applies only to graph nodes that interpolate during the
   243  		// config walk, e.g. providers.
   244  		if i.Operation == walkInput {
   245  			result[n] = ast.Variable{
   246  				Value: config.UnknownVariableValue,
   247  				Type:  ast.TypeString,
   248  			}
   249  			return nil
   250  		}
   251  
   252  		return fmt.Errorf("variable %q is nil, but no error was reported", v.Name)
   253  	}
   254  
   255  	result[n] = *variable
   256  	return nil
   257  }
   258  
   259  func (i *Interpolater) valueSelfVar(
   260  	scope *InterpolationScope,
   261  	n string,
   262  	v *config.SelfVariable,
   263  	result map[string]ast.Variable) error {
   264  	if scope == nil || scope.Resource == nil {
   265  		return fmt.Errorf(
   266  			"%s: invalid scope, self variables are only valid on resources", n)
   267  	}
   268  	rv, err := config.NewResourceVariable(fmt.Sprintf(
   269  		"%s.%s.%d.%s",
   270  		scope.Resource.Type,
   271  		scope.Resource.Name,
   272  		scope.Resource.CountIndex,
   273  		v.Field))
   274  	if err != nil {
   275  		return err
   276  	}
   277  
   278  	return i.valueResourceVar(scope, n, rv, result)
   279  }
   280  
   281  func (i *Interpolater) valueSimpleVar(
   282  	scope *InterpolationScope,
   283  	n string,
   284  	v *config.SimpleVariable,
   285  	result map[string]ast.Variable) error {
   286  	// SimpleVars are never handled by Terraform's interpolator
   287  	result[n] = ast.Variable{
   288  		Value: config.UnknownVariableValue,
   289  		Type:  ast.TypeString,
   290  	}
   291  	return nil
   292  }
   293  
   294  func (i *Interpolater) valueUserVar(
   295  	scope *InterpolationScope,
   296  	n string,
   297  	v *config.UserVariable,
   298  	result map[string]ast.Variable) error {
   299  	i.VariableValuesLock.Lock()
   300  	defer i.VariableValuesLock.Unlock()
   301  	val, ok := i.VariableValues[v.Name]
   302  	if ok {
   303  		varValue, err := hil.InterfaceToVariable(val)
   304  		if err != nil {
   305  			return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
   306  				v.Name, val, err)
   307  		}
   308  		result[n] = varValue
   309  		return nil
   310  	}
   311  
   312  	if _, ok := result[n]; !ok && i.Operation == walkValidate {
   313  		result[n] = unknownVariable()
   314  		return nil
   315  	}
   316  
   317  	// Look up if we have any variables with this prefix because
   318  	// those are map overrides. Include those.
   319  	for k, val := range i.VariableValues {
   320  		if strings.HasPrefix(k, v.Name+".") {
   321  			keyComponents := strings.Split(k, ".")
   322  			overrideKey := keyComponents[len(keyComponents)-1]
   323  
   324  			mapInterface, ok := result["var."+v.Name]
   325  			if !ok {
   326  				return fmt.Errorf("override for non-existent variable: %s", v.Name)
   327  			}
   328  
   329  			mapVariable := mapInterface.Value.(map[string]ast.Variable)
   330  
   331  			varValue, err := hil.InterfaceToVariable(val)
   332  			if err != nil {
   333  				return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
   334  					v.Name, val, err)
   335  			}
   336  			mapVariable[overrideKey] = varValue
   337  		}
   338  	}
   339  
   340  	return nil
   341  }
   342  
   343  func (i *Interpolater) computeResourceVariable(
   344  	scope *InterpolationScope,
   345  	v *config.ResourceVariable) (*ast.Variable, error) {
   346  	id := v.ResourceId()
   347  	if v.Multi {
   348  		id = fmt.Sprintf("%s.%d", id, v.Index)
   349  	}
   350  
   351  	i.StateLock.RLock()
   352  	defer i.StateLock.RUnlock()
   353  
   354  	unknownVariable := unknownVariable()
   355  
   356  	// These variables must be declared early because of the use of GOTO
   357  	var isList bool
   358  	var isMap bool
   359  
   360  	// Get the information about this resource variable, and verify
   361  	// that it exists and such.
   362  	module, _, err := i.resourceVariableInfo(scope, v)
   363  	if err != nil {
   364  		return nil, err
   365  	}
   366  
   367  	// If we have no module in the state yet or count, return empty
   368  	if module == nil || len(module.Resources) == 0 {
   369  		return nil, nil
   370  	}
   371  
   372  	// Get the resource out from the state. We know the state exists
   373  	// at this point and if there is a state, we expect there to be a
   374  	// resource with the given name.
   375  	r, ok := module.Resources[id]
   376  	if !ok && v.Multi && v.Index == 0 {
   377  		r, ok = module.Resources[v.ResourceId()]
   378  	}
   379  	if !ok {
   380  		r = nil
   381  	}
   382  	if r == nil {
   383  		goto MISSING
   384  	}
   385  
   386  	if r.Primary == nil {
   387  		goto MISSING
   388  	}
   389  
   390  	if attr, ok := r.Primary.Attributes[v.Field]; ok {
   391  		return &ast.Variable{Type: ast.TypeString, Value: attr}, nil
   392  	}
   393  
   394  	// computed list or map attribute
   395  	_, isList = r.Primary.Attributes[v.Field+".#"]
   396  	_, isMap = r.Primary.Attributes[v.Field+".%"]
   397  	if isList || isMap {
   398  		variable, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
   399  		return &variable, err
   400  	}
   401  
   402  	// At apply time, we can't do the "maybe has it" check below
   403  	// that we need for plans since parent elements might be computed.
   404  	// Therefore, it is an error and we're missing the key.
   405  	//
   406  	// TODO: test by creating a state and configuration that is referencing
   407  	// a non-existent variable "foo.bar" where the state only has "foo"
   408  	// and verify plan works, but apply doesn't.
   409  	if i.Operation == walkApply || i.Operation == walkDestroy {
   410  		goto MISSING
   411  	}
   412  
   413  	// We didn't find the exact field, so lets separate the dots
   414  	// and see if anything along the way is a computed set. i.e. if
   415  	// we have "foo.0.bar" as the field, check to see if "foo" is
   416  	// a computed list. If so, then the whole thing is computed.
   417  	if parts := strings.Split(v.Field, "."); len(parts) > 1 {
   418  		for i := 1; i < len(parts); i++ {
   419  			// Lists and sets make this
   420  			key := fmt.Sprintf("%s.#", strings.Join(parts[:i], "."))
   421  			if attr, ok := r.Primary.Attributes[key]; ok {
   422  				return &ast.Variable{Type: ast.TypeString, Value: attr}, nil
   423  			}
   424  
   425  			// Maps make this
   426  			key = fmt.Sprintf("%s", strings.Join(parts[:i], "."))
   427  			if attr, ok := r.Primary.Attributes[key]; ok {
   428  				return &ast.Variable{Type: ast.TypeString, Value: attr}, nil
   429  			}
   430  		}
   431  	}
   432  
   433  MISSING:
   434  	// Validation for missing interpolations should happen at a higher
   435  	// semantic level. If we reached this point and don't have variables,
   436  	// just return the computed value.
   437  	if scope == nil && scope.Resource == nil {
   438  		return &unknownVariable, nil
   439  	}
   440  
   441  	// If the operation is refresh, it isn't an error for a value to
   442  	// be unknown. Instead, we return that the value is computed so
   443  	// that the graph can continue to refresh other nodes. It doesn't
   444  	// matter because the config isn't interpolated anyways.
   445  	//
   446  	// For a Destroy, we're also fine with computed values, since our goal is
   447  	// only to get destroy nodes for existing resources.
   448  	//
   449  	// For an input walk, computed values are okay to return because we're only
   450  	// looking for missing variables to prompt the user for.
   451  	if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput {
   452  		return &unknownVariable, nil
   453  	}
   454  
   455  	return nil, fmt.Errorf(
   456  		"Resource '%s' does not have attribute '%s' "+
   457  			"for variable '%s'",
   458  		id,
   459  		v.Field,
   460  		v.FullKey())
   461  }
   462  
   463  func (i *Interpolater) computeResourceMultiVariable(
   464  	scope *InterpolationScope,
   465  	v *config.ResourceVariable) (*ast.Variable, error) {
   466  	i.StateLock.RLock()
   467  	defer i.StateLock.RUnlock()
   468  
   469  	unknownVariable := unknownVariable()
   470  
   471  	// Get the information about this resource variable, and verify
   472  	// that it exists and such.
   473  	module, cr, err := i.resourceVariableInfo(scope, v)
   474  	if err != nil {
   475  		return nil, err
   476  	}
   477  
   478  	// Get the count so we know how many to iterate over
   479  	count, err := cr.Count()
   480  	if err != nil {
   481  		return nil, fmt.Errorf(
   482  			"Error reading %s count: %s",
   483  			v.ResourceId(),
   484  			err)
   485  	}
   486  
   487  	// If count is zero, we return an empty list
   488  	if count == 0 {
   489  		return &ast.Variable{Type: ast.TypeList, Value: []ast.Variable{}}, nil
   490  	}
   491  
   492  	// If we have no module in the state yet or count, return unknown
   493  	if module == nil || len(module.Resources) == 0 {
   494  		return &unknownVariable, nil
   495  	}
   496  
   497  	var values []interface{}
   498  	for j := 0; j < count; j++ {
   499  		id := fmt.Sprintf("%s.%d", v.ResourceId(), j)
   500  
   501  		// If we're dealing with only a single resource, then the
   502  		// ID doesn't have a trailing index.
   503  		if count == 1 {
   504  			id = v.ResourceId()
   505  		}
   506  
   507  		r, ok := module.Resources[id]
   508  		if !ok {
   509  			continue
   510  		}
   511  
   512  		if r.Primary == nil {
   513  			continue
   514  		}
   515  
   516  		if singleAttr, ok := r.Primary.Attributes[v.Field]; ok {
   517  			if singleAttr == config.UnknownVariableValue {
   518  				return &unknownVariable, nil
   519  			}
   520  
   521  			values = append(values, singleAttr)
   522  			continue
   523  		}
   524  
   525  		// computed list or map attribute
   526  		_, isList := r.Primary.Attributes[v.Field+".#"]
   527  		_, isMap := r.Primary.Attributes[v.Field+".%"]
   528  		if !(isList || isMap) {
   529  			continue
   530  		}
   531  		multiAttr, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
   532  		if err != nil {
   533  			return nil, err
   534  		}
   535  
   536  		if multiAttr == unknownVariable {
   537  			return &ast.Variable{Type: ast.TypeString, Value: ""}, nil
   538  		}
   539  
   540  		values = append(values, multiAttr)
   541  	}
   542  
   543  	if len(values) == 0 {
   544  		// If the operation is refresh, it isn't an error for a value to
   545  		// be unknown. Instead, we return that the value is computed so
   546  		// that the graph can continue to refresh other nodes. It doesn't
   547  		// matter because the config isn't interpolated anyways.
   548  		//
   549  		// For a Destroy, we're also fine with computed values, since our goal is
   550  		// only to get destroy nodes for existing resources.
   551  		//
   552  		// For an input walk, computed values are okay to return because we're only
   553  		// looking for missing variables to prompt the user for.
   554  		if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput {
   555  			return &unknownVariable, nil
   556  		}
   557  
   558  		return nil, fmt.Errorf(
   559  			"Resource '%s' does not have attribute '%s' "+
   560  				"for variable '%s'",
   561  			v.ResourceId(),
   562  			v.Field,
   563  			v.FullKey())
   564  	}
   565  
   566  	variable, err := hil.InterfaceToVariable(values)
   567  	return &variable, err
   568  }
   569  
   570  func (i *Interpolater) interpolateComplexTypeAttribute(
   571  	resourceID string,
   572  	attributes map[string]string) (ast.Variable, error) {
   573  
   574  	// We can now distinguish between lists and maps in state by the count field:
   575  	//    - lists (and by extension, sets) use the traditional .# notation
   576  	//    - maps use the newer .% notation
   577  	// Consequently here we can decide how to deal with the keys appropriately
   578  	// based on whether the type is a map of list.
   579  	if lengthAttr, isList := attributes[resourceID+".#"]; isList {
   580  		log.Printf("[DEBUG] Interpolating computed list element attribute %s (%s)",
   581  			resourceID, lengthAttr)
   582  
   583  		// In Terraform's internal dotted representation of list-like attributes, the
   584  		// ".#" count field is marked as unknown to indicate "this whole list is
   585  		// unknown". We must honor that meaning here so computed references can be
   586  		// treated properly during the plan phase.
   587  		if lengthAttr == config.UnknownVariableValue {
   588  			return unknownVariable(), nil
   589  		}
   590  
   591  		keys := make([]string, 0)
   592  		listElementKey := regexp.MustCompile("^" + resourceID + "\\.[0-9]+$")
   593  		for id := range attributes {
   594  			if listElementKey.MatchString(id) {
   595  				keys = append(keys, id)
   596  			}
   597  		}
   598  		sort.Strings(keys)
   599  
   600  		var members []string
   601  		for _, key := range keys {
   602  			members = append(members, attributes[key])
   603  		}
   604  
   605  		return hil.InterfaceToVariable(members)
   606  	}
   607  
   608  	if lengthAttr, isMap := attributes[resourceID+".%"]; isMap {
   609  		log.Printf("[DEBUG] Interpolating computed map element attribute %s (%s)",
   610  			resourceID, lengthAttr)
   611  
   612  		// In Terraform's internal dotted representation of map attributes, the
   613  		// ".%" count field is marked as unknown to indicate "this whole list is
   614  		// unknown". We must honor that meaning here so computed references can be
   615  		// treated properly during the plan phase.
   616  		if lengthAttr == config.UnknownVariableValue {
   617  			return unknownVariable(), nil
   618  		}
   619  
   620  		resourceFlatMap := make(map[string]string)
   621  		mapElementKey := regexp.MustCompile("^" + resourceID + "\\.([^%]+)$")
   622  		for id, val := range attributes {
   623  			if mapElementKey.MatchString(id) {
   624  				resourceFlatMap[id] = val
   625  			}
   626  		}
   627  
   628  		expanded := flatmap.Expand(resourceFlatMap, resourceID)
   629  		return hil.InterfaceToVariable(expanded)
   630  	}
   631  
   632  	return ast.Variable{}, fmt.Errorf("No complex type %s found", resourceID)
   633  }
   634  
   635  func (i *Interpolater) resourceVariableInfo(
   636  	scope *InterpolationScope,
   637  	v *config.ResourceVariable) (*ModuleState, *config.Resource, error) {
   638  	// Get the module tree that contains our current path. This is
   639  	// either the current module (path is empty) or a child.
   640  	modTree := i.Module
   641  	if len(scope.Path) > 1 {
   642  		modTree = i.Module.Child(scope.Path[1:])
   643  	}
   644  
   645  	// Get the resource from the configuration so we can verify
   646  	// that the resource is in the configuration and so we can access
   647  	// the configuration if we need to.
   648  	var cr *config.Resource
   649  	for _, r := range modTree.Config().Resources {
   650  		if r.Id() == v.ResourceId() {
   651  			cr = r
   652  			break
   653  		}
   654  	}
   655  	if cr == nil {
   656  		return nil, nil, fmt.Errorf(
   657  			"Resource '%s' not found for variable '%s'",
   658  			v.ResourceId(),
   659  			v.FullKey())
   660  	}
   661  
   662  	// Get the relevant module
   663  	module := i.State.ModuleByPath(scope.Path)
   664  	return module, cr, nil
   665  }