github.com/tam7t/terraform@v0.7.0-rc2.0.20160705125922-be2469a05c5e/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  	var values []string
   497  	for j := 0; j < count; j++ {
   498  		id := fmt.Sprintf("%s.%d", v.ResourceId(), j)
   499  
   500  		// If we're dealing with only a single resource, then the
   501  		// ID doesn't have a trailing index.
   502  		if count == 1 {
   503  			id = v.ResourceId()
   504  		}
   505  
   506  		r, ok := module.Resources[id]
   507  		if !ok {
   508  			continue
   509  		}
   510  
   511  		if r.Primary == nil {
   512  			continue
   513  		}
   514  
   515  		if singleAttr, ok := r.Primary.Attributes[v.Field]; ok {
   516  			if singleAttr == config.UnknownVariableValue {
   517  				return &unknownVariable, nil
   518  			}
   519  
   520  			values = append(values, singleAttr)
   521  			continue
   522  		}
   523  
   524  		// computed list attribute
   525  		_, ok = r.Primary.Attributes[v.Field+".#"]
   526  		if !ok {
   527  			continue
   528  		}
   529  		multiAttr, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
   530  		if err != nil {
   531  			return nil, err
   532  		}
   533  
   534  		if multiAttr == unknownVariable {
   535  			return &ast.Variable{Type: ast.TypeString, Value: ""}, nil
   536  		}
   537  
   538  		for _, element := range multiAttr.Value.([]ast.Variable) {
   539  			strVal := element.Value.(string)
   540  			if strVal == config.UnknownVariableValue {
   541  				return &unknownVariable, nil
   542  			}
   543  
   544  			values = append(values, strVal)
   545  		}
   546  	}
   547  
   548  	if len(values) == 0 {
   549  		// If the operation is refresh, it isn't an error for a value to
   550  		// be unknown. Instead, we return that the value is computed so
   551  		// that the graph can continue to refresh other nodes. It doesn't
   552  		// matter because the config isn't interpolated anyways.
   553  		//
   554  		// For a Destroy, we're also fine with computed values, since our goal is
   555  		// only to get destroy nodes for existing resources.
   556  		//
   557  		// For an input walk, computed values are okay to return because we're only
   558  		// looking for missing variables to prompt the user for.
   559  		if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput {
   560  			return &unknownVariable, nil
   561  		}
   562  
   563  		return nil, fmt.Errorf(
   564  			"Resource '%s' does not have attribute '%s' "+
   565  				"for variable '%s'",
   566  			v.ResourceId(),
   567  			v.Field,
   568  			v.FullKey())
   569  	}
   570  
   571  	variable, err := hil.InterfaceToVariable(values)
   572  	return &variable, err
   573  }
   574  
   575  func (i *Interpolater) interpolateComplexTypeAttribute(
   576  	resourceID string,
   577  	attributes map[string]string) (ast.Variable, error) {
   578  
   579  	// We can now distinguish between lists and maps in state by the count field:
   580  	//    - lists (and by extension, sets) use the traditional .# notation
   581  	//    - maps use the newer .% notation
   582  	// Consequently here we can decide how to deal with the keys appropriately
   583  	// based on whether the type is a map of list.
   584  	if lengthAttr, isList := attributes[resourceID+".#"]; isList {
   585  		log.Printf("[DEBUG] Interpolating computed list element attribute %s (%s)",
   586  			resourceID, lengthAttr)
   587  
   588  		// In Terraform's internal dotted representation of list-like attributes, the
   589  		// ".#" count field is marked as unknown to indicate "this whole list is
   590  		// unknown". We must honor that meaning here so computed references can be
   591  		// treated properly during the plan phase.
   592  		if lengthAttr == config.UnknownVariableValue {
   593  			return unknownVariable(), nil
   594  		}
   595  
   596  		keys := make([]string, 0)
   597  		listElementKey := regexp.MustCompile("^" + resourceID + "\\.[0-9]+$")
   598  		for id, _ := range attributes {
   599  			if listElementKey.MatchString(id) {
   600  				keys = append(keys, id)
   601  			}
   602  		}
   603  		sort.Strings(keys)
   604  
   605  		var members []string
   606  		for _, key := range keys {
   607  			members = append(members, attributes[key])
   608  		}
   609  
   610  		return hil.InterfaceToVariable(members)
   611  	}
   612  
   613  	if lengthAttr, isMap := attributes[resourceID+".%"]; isMap {
   614  		log.Printf("[DEBUG] Interpolating computed map element attribute %s (%s)",
   615  			resourceID, lengthAttr)
   616  
   617  		// In Terraform's internal dotted representation of map attributes, the
   618  		// ".%" count field is marked as unknown to indicate "this whole list is
   619  		// unknown". We must honor that meaning here so computed references can be
   620  		// treated properly during the plan phase.
   621  		if lengthAttr == config.UnknownVariableValue {
   622  			return unknownVariable(), nil
   623  		}
   624  
   625  		resourceFlatMap := make(map[string]string)
   626  		mapElementKey := regexp.MustCompile("^" + resourceID + "\\.([^%]+)$")
   627  		for id, val := range attributes {
   628  			if mapElementKey.MatchString(id) {
   629  				resourceFlatMap[id] = val
   630  			}
   631  		}
   632  
   633  		expanded := flatmap.Expand(resourceFlatMap, resourceID)
   634  		return hil.InterfaceToVariable(expanded)
   635  	}
   636  
   637  	return ast.Variable{}, fmt.Errorf("No complex type %s found", resourceID)
   638  }
   639  
   640  func (i *Interpolater) resourceVariableInfo(
   641  	scope *InterpolationScope,
   642  	v *config.ResourceVariable) (*ModuleState, *config.Resource, error) {
   643  	// Get the module tree that contains our current path. This is
   644  	// either the current module (path is empty) or a child.
   645  	modTree := i.Module
   646  	if len(scope.Path) > 1 {
   647  		modTree = i.Module.Child(scope.Path[1:])
   648  	}
   649  
   650  	// Get the resource from the configuration so we can verify
   651  	// that the resource is in the configuration and so we can access
   652  	// the configuration if we need to.
   653  	var cr *config.Resource
   654  	for _, r := range modTree.Config().Resources {
   655  		if r.Id() == v.ResourceId() {
   656  			cr = r
   657  			break
   658  		}
   659  	}
   660  	if cr == nil {
   661  		return nil, nil, fmt.Errorf(
   662  			"Resource '%s' not found for variable '%s'",
   663  			v.ResourceId(),
   664  			v.FullKey())
   665  	}
   666  
   667  	// Get the relevant module
   668  	module := i.State.ModuleByPath(scope.Path)
   669  	return module, cr, nil
   670  }