11 "github.com/hashicorp/hil"
12 "github.com/hashicorp/hil/ast"
13 "github.com/hashicorp/terraform/config"
14 "github.com/hashicorp/terraform/config/module"
15 "github.com/hashicorp/terraform/flatmap"
19 // VarEnvPrefix is the prefix of variables that are read from
20 // the environment to set variables here.
21 VarEnvPrefix = "TF_VAR_"
24 // Interpolater is the structure responsible for determining the values
25 // for interpolations such as `aws_instance.foo.bar`.
26 type Interpolater struct {
27 Operation walkOperation
31 StateLock *sync.RWMutex
32 VariableValues map[string]interface{}
33 VariableValuesLock *sync.Mutex
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 {
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) {
49 scope = &InterpolationScope{}
52 result := make(map[string]ast.Variable, len(vars))
54 // Copy the default variables
55 if i.Module != nil && scope != nil {
57 if len(scope.Path) > 1 {
58 mod = i.Module.Child(scope.Path[1:])
60 for _, v := range mod.Config().Variables {
61 // Set default variables
66 n := fmt.Sprintf("var.%s", v.Name)
67 variable, err := hil.InterfaceToVariable(v.Default)
69 return nil, fmt.Errorf("invalid default map value for %s: %v", v.Name, v.Default)
76 for n, rawV := range vars {
78 switch v := rawV.(type) {
79 case *config.CountVariable:
80 err = i.valueCountVar(scope, n, v, result)
81 case *config.ModuleVariable:
82 err = i.valueModuleVar(scope, n, v, result)
83 case *config.PathVariable:
84 err = i.valuePathVar(scope, n, v, result)
85 case *config.ResourceVariable:
86 err = i.valueResourceVar(scope, n, v, result)
87 case *config.SelfVariable:
88 err = i.valueSelfVar(scope, n, v, result)
89 case *config.SimpleVariable:
90 err = i.valueSimpleVar(scope, n, v, result)
91 case *config.TerraformVariable:
92 err = i.valueTerraformVar(scope, n, v, result)
93 case *config.UserVariable:
94 err = i.valueUserVar(scope, n, v, result)
96 err = fmt.Errorf("%s: unknown variable type: %T", n, rawV)
107 func (i *Interpolater) valueCountVar(
108 scope *InterpolationScope,
110 v *config.CountVariable,
111 result map[string]ast.Variable) error {
113 case config.CountValueIndex:
114 if scope.Resource == nil {
115 return fmt.Errorf("%s: count.index is only valid within resources", n)
117 result[n] = ast.Variable{
118 Value: scope.Resource.CountIndex,
123 return fmt.Errorf("%s: unknown count type: %#v", n, v.Type)
127 func unknownVariable() ast.Variable {
129 Type: ast.TypeUnknown,
130 Value: config.UnknownVariableValue,
134 func unknownValue() string {
135 return hil.UnknownValue
138 func (i *Interpolater) valueModuleVar(
139 scope *InterpolationScope,
141 v *config.ModuleVariable,
142 result map[string]ast.Variable) error {
144 // Build the path to the child module we want
145 path := make([]string, len(scope.Path), len(scope.Path)+1)
146 copy(path, scope.Path)
147 path = append(path, v.Name)
149 // Grab the lock so that if other interpolations are running or
150 // state is being modified, we'll be safe.
152 defer i.StateLock.RUnlock()
154 // Get the module where we're looking for the value
155 mod := i.State.ModuleByPath(path)
157 // If the module doesn't exist, then we can return an empty string.
158 // This happens usually only in Refresh() when we haven't populated
159 // a state. During validation, we semantically verify that all
160 // modules reference other modules, and graph ordering should
161 // ensure that the module is in the state, so if we reach this
162 // point otherwise it really is a panic.
163 result[n] = unknownVariable()
165 // During apply this is always an error
166 if i.Operation == walkApply {
168 "Couldn't find module %q for var: %s",
172 // Get the value from the outputs
173 if outputState, ok := mod.Outputs[v.Field]; ok {
174 output, err := hil.InterfaceToVariable(outputState.Value)
180 // Same reasons as the comment above.
181 result[n] = unknownVariable()
183 // During apply this is always an error
184 if i.Operation == walkApply {
186 "Couldn't find output %q for module var: %s",
187 v.Field, v.FullKey())
195 func (i *Interpolater) valuePathVar(
196 scope *InterpolationScope,
198 v *config.PathVariable,
199 result map[string]ast.Variable) error {
201 case config.PathValueCwd:
202 wd, err := os.Getwd()
205 "Couldn't get cwd for var %s: %s",
209 result[n] = ast.Variable{
211 Type: ast.TypeString,
213 case config.PathValueModule:
214 if t := i.Module.Child(scope.Path[1:]); t != nil {
215 result[n] = ast.Variable{
216 Value: t.Config().Dir,
217 Type: ast.TypeString,
220 case config.PathValueRoot:
221 result[n] = ast.Variable{
222 Value: i.Module.Config().Dir,
223 Type: ast.TypeString,
226 return fmt.Errorf("%s: unknown path type: %#v", n, v.Type)
233 func (i *Interpolater) valueResourceVar(
234 scope *InterpolationScope,
236 v *config.ResourceVariable,
237 result map[string]ast.Variable) error {
238 // If we're computing all dynamic fields, then module vars count
239 // and we mark it as computed.
240 if i.Operation == walkValidate {
241 result[n] = unknownVariable()
245 var variable *ast.Variable
248 if v.Multi && v.Index == -1 {
249 variable, err = i.computeResourceMultiVariable(scope, v)
251 variable, err = i.computeResourceVariable(scope, v)
259 // During the input walk we tolerate missing variables because
260 // we haven't yet had a chance to refresh state, so dynamic data may
261 // not yet be complete.
262 // If it truly is missing, we'll catch it on a later walk.
263 // This applies only to graph nodes that interpolate during the
264 // config walk, e.g. providers.
265 if i.Operation == walkInput || i.Operation == walkRefresh {
266 result[n] = unknownVariable()
270 return fmt.Errorf("variable %q is nil, but no error was reported", v.Name)
273 result[n] = *variable
277 func (i *Interpolater) valueSelfVar(
278 scope *InterpolationScope,
280 v *config.SelfVariable,
281 result map[string]ast.Variable) error {
282 if scope == nil || scope.Resource == nil {
284 "%s: invalid scope, self variables are only valid on resources", n)
287 rv, err := config.NewResourceVariable(fmt.Sprintf(
291 scope.Resource.CountIndex,
297 return i.valueResourceVar(scope, n, rv, result)
300 func (i *Interpolater) valueSimpleVar(
301 scope *InterpolationScope,
303 v *config.SimpleVariable,
304 result map[string]ast.Variable) error {
305 // This error message includes some information for people who
306 // relied on this for their template_file data sources. We should
307 // remove this at some point but there isn't any rush.
309 "invalid variable syntax: %q. Did you mean 'var.%s'? If this is part of inline `template` parameter\n"+
310 "then you must escape the interpolation with two dollar signs. For\n"+
311 "example: ${a} becomes $${a}.",
315 func (i *Interpolater) valueTerraformVar(
316 scope *InterpolationScope,
318 v *config.TerraformVariable,
319 result map[string]ast.Variable) error {
321 // "env" is supported for backward compatibility, but it's deprecated and
322 // so we won't advertise it as being allowed in the error message. It will
323 // be removed in a future version of Terraform.
324 if v.Field != "workspace" && v.Field != "env" {
326 "%s: only supported key for 'terraform.X' interpolations is 'workspace'", n)
331 "%s: internal error: nil Meta. Please report a bug.", n)
334 result[n] = ast.Variable{Type: ast.TypeString, Value: i.Meta.Env}
338 func (i *Interpolater) valueUserVar(
339 scope *InterpolationScope,
341 v *config.UserVariable,
342 result map[string]ast.Variable) error {
343 i.VariableValuesLock.Lock()
344 defer i.VariableValuesLock.Unlock()
345 val, ok := i.VariableValues[v.Name]
347 varValue, err := hil.InterfaceToVariable(val)
349 return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
356 if _, ok := result[n]; !ok && i.Operation == walkValidate {
357 result[n] = unknownVariable()
361 // Look up if we have any variables with this prefix because
362 // those are map overrides. Include those.
363 for k, val := range i.VariableValues {
364 if strings.HasPrefix(k, v.Name+".") {
365 keyComponents := strings.Split(k, ".")
366 overrideKey := keyComponents[len(keyComponents)-1]
368 mapInterface, ok := result["var."+v.Name]
370 return fmt.Errorf("override for non-existent variable: %s", v.Name)
373 mapVariable := mapInterface.Value.(map[string]ast.Variable)
375 varValue, err := hil.InterfaceToVariable(val)
377 return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
380 mapVariable[overrideKey] = varValue
387 func (i *Interpolater) computeResourceVariable(
388 scope *InterpolationScope,
389 v *config.ResourceVariable) (*ast.Variable, error) {
392 id = fmt.Sprintf("%s.%d", id, v.Index)
396 defer i.StateLock.RUnlock()
398 unknownVariable := unknownVariable()
400 // These variables must be declared early because of the use of GOTO
404 // Get the information about this resource variable, and verify
405 // that it exists and such.
406 module, cr, err := i.resourceVariableInfo(scope, v)
411 // If we're requesting "count" its a special variable that we grab
412 // directly from the config itself.
413 if v.Field == "count" {
416 count, err = cr.Count()
418 count, err = i.resourceCountMax(module, cr, v)
421 return nil, fmt.Errorf(
422 "Error reading %s count: %s",
427 return &ast.Variable{Type: ast.TypeInt, Value: count}, nil
430 // Get the resource out from the state. We know the state exists
431 // at this point and if there is a state, we expect there to be a
432 // resource with the given name.
434 if module != nil && len(module.Resources) > 0 {
436 r, ok = module.Resources[id]
437 if !ok && v.Multi && v.Index == 0 {
438 r, ok = module.Resources[v.ResourceId()]
444 if r == nil || r.Primary == nil {
445 if i.Operation == walkApply || i.Operation == walkPlan {
446 return nil, fmt.Errorf(
447 "Resource '%s' not found for variable '%s'",
452 // If we have no module in the state yet or count, return empty.
453 // NOTE(@mitchellh): I actually don't know why this is here. During
454 // a refactor I kept this here to maintain the same behavior, but
455 // I'm not sure why its here.
456 if module == nil || len(module.Resources) == 0 {
463 if attr, ok := r.Primary.Attributes[v.Field]; ok {
464 v, err := hil.InterfaceToVariable(attr)
468 // computed list or map attribute
469 _, isList = r.Primary.Attributes[v.Field+".#"]
470 _, isMap = r.Primary.Attributes[v.Field+".%"]
472 variable, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
473 return &variable, err
476 // At apply time, we can't do the "maybe has it" check below
477 // that we need for plans since parent elements might be computed.
478 // Therefore, it is an error and we're missing the key.
480 // TODO: test by creating a state and configuration that is referencing
481 // a non-existent variable "foo.bar" where the state only has "foo"
482 // and verify plan works, but apply doesn't.
483 if i.Operation == walkApply || i.Operation == walkDestroy {
487 // We didn't find the exact field, so lets separate the dots
488 // and see if anything along the way is a computed set. i.e. if
489 // we have "foo.0.bar" as the field, check to see if "foo" is
490 // a computed list. If so, then the whole thing is computed.
491 if parts := strings.Split(v.Field, "."); len(parts) > 1 {
492 for i := 1; i < len(parts); i++ {
493 // Lists and sets make this
494 key := fmt.Sprintf("%s.#", strings.Join(parts[:i], "."))
495 if attr, ok := r.Primary.Attributes[key]; ok {
496 v, err := hil.InterfaceToVariable(attr)
501 key = fmt.Sprintf("%s", strings.Join(parts[:i], "."))
502 if attr, ok := r.Primary.Attributes[key]; ok {
503 v, err := hil.InterfaceToVariable(attr)
510 // Validation for missing interpolations should happen at a higher
511 // semantic level. If we reached this point and don't have variables,
512 // just return the computed value.
513 if scope == nil && scope.Resource == nil {
514 return &unknownVariable, nil
517 // If the operation is refresh, it isn't an error for a value to
518 // be unknown. Instead, we return that the value is computed so
519 // that the graph can continue to refresh other nodes. It doesn't
520 // matter because the config isn't interpolated anyways.
522 // For a Destroy, we're also fine with computed values, since our goal is
523 // only to get destroy nodes for existing resources.
525 // For an input walk, computed values are okay to return because we're only
526 // looking for missing variables to prompt the user for.
527 if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkInput {
528 return &unknownVariable, nil
531 return nil, fmt.Errorf(
532 "Resource '%s' does not have attribute '%s' "+
539 func (i *Interpolater) computeResourceMultiVariable(
540 scope *InterpolationScope,
541 v *config.ResourceVariable) (*ast.Variable, error) {
543 defer i.StateLock.RUnlock()
545 unknownVariable := unknownVariable()
547 // If we're only looking for input, we don't need to expand a
548 // multi-variable. This prevents us from encountering things that should be
549 // known but aren't because the state has yet to be refreshed.
550 if i.Operation == walkInput {
551 return &unknownVariable, nil
554 // Get the information about this resource variable, and verify
555 // that it exists and such.
556 module, cr, err := i.resourceVariableInfo(scope, v)
561 // Get the keys for all the resources that are created for this resource
562 countMax, err := i.resourceCountMax(module, cr, v)
567 // If count is zero, we return an empty list
569 return &ast.Variable{Type: ast.TypeList, Value: []ast.Variable{}}, nil
572 // If we have no module in the state yet or count, return unknown
573 if module == nil || len(module.Resources) == 0 {
574 return &unknownVariable, nil
577 var values []interface{}
578 for idx := 0; idx < countMax; idx++ {
579 id := fmt.Sprintf("%s.%d", v.ResourceId(), idx)
581 // ID doesn't have a trailing index. We try both here, but if a value
582 // without a trailing index is found we prefer that. This choice
583 // is for legacy reasons: older versions of TF preferred it.
584 if id == v.ResourceId()+".0" {
585 potential := v.ResourceId()
586 if _, ok := module.Resources[potential]; ok {
591 r, ok := module.Resources[id]
596 if r.Primary == nil {
600 if singleAttr, ok := r.Primary.Attributes[v.Field]; ok {
601 values = append(values, singleAttr)
605 // computed list or map attribute
606 _, isList := r.Primary.Attributes[v.Field+".#"]
607 _, isMap := r.Primary.Attributes[v.Field+".%"]
608 if !(isList || isMap) {
611 multiAttr, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
616 values = append(values, multiAttr)
619 if len(values) == 0 {
620 // If the operation is refresh, it isn't an error for a value to
621 // be unknown. Instead, we return that the value is computed so
622 // that the graph can continue to refresh other nodes. It doesn't
623 // matter because the config isn't interpolated anyways.
625 // For a Destroy, we're also fine with computed values, since our goal is
626 // only to get destroy nodes for existing resources.
628 // For an input walk, computed values are okay to return because we're only
629 // looking for missing variables to prompt the user for.
630 if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput {
631 return &unknownVariable, nil
634 return nil, fmt.Errorf(
635 "Resource '%s' does not have attribute '%s' "+
642 variable, err := hil.InterfaceToVariable(values)
643 return &variable, err
646 func (i *Interpolater) interpolateComplexTypeAttribute(
648 attributes map[string]string) (ast.Variable, error) {
650 // We can now distinguish between lists and maps in state by the count field:
651 // - lists (and by extension, sets) use the traditional .# notation
652 // - maps use the newer .% notation
653 // Consequently here we can decide how to deal with the keys appropriately
654 // based on whether the type is a map of list.
655 if lengthAttr, isList := attributes[resourceID+".#"]; isList {
656 log.Printf("[DEBUG] Interpolating computed list element attribute %s (%s)",
657 resourceID, lengthAttr)
659 // In Terraform's internal dotted representation of list-like attributes, the
660 // ".#" count field is marked as unknown to indicate "this whole list is
661 // unknown". We must honor that meaning here so computed references can be
662 // treated properly during the plan phase.
663 if lengthAttr == config.UnknownVariableValue {
664 return unknownVariable(), nil
667 expanded := flatmap.Expand(attributes, resourceID)
668 return hil.InterfaceToVariable(expanded)
671 if lengthAttr, isMap := attributes[resourceID+".%"]; isMap {
672 log.Printf("[DEBUG] Interpolating computed map element attribute %s (%s)",
673 resourceID, lengthAttr)
675 // In Terraform's internal dotted representation of map attributes, the
676 // ".%" count field is marked as unknown to indicate "this whole list is
677 // unknown". We must honor that meaning here so computed references can be
678 // treated properly during the plan phase.
679 if lengthAttr == config.UnknownVariableValue {
680 return unknownVariable(), nil
683 expanded := flatmap.Expand(attributes, resourceID)
684 return hil.InterfaceToVariable(expanded)
687 return ast.Variable{}, fmt.Errorf("No complex type %s found", resourceID)
690 func (i *Interpolater) resourceVariableInfo(
691 scope *InterpolationScope,
692 v *config.ResourceVariable) (*ModuleState, *config.Resource, error) {
693 // Get the module tree that contains our current path. This is
694 // either the current module (path is empty) or a child.
696 if len(scope.Path) > 1 {
697 modTree = i.Module.Child(scope.Path[1:])
700 // Get the resource from the configuration so we can verify
701 // that the resource is in the configuration and so we can access
702 // the configuration if we need to.
703 var cr *config.Resource
704 for _, r := range modTree.Config().Resources {
705 if r.Id() == v.ResourceId() {
711 // Get the relevant module
712 module := i.State.ModuleByPath(scope.Path)
713 return module, cr, nil
716 func (i *Interpolater) resourceCountMax(
719 v *config.ResourceVariable) (int, error) {
722 // If we're NOT applying, then we assume we can read the count
723 // from the state. Plan and so on may not have any state yet so
724 // we do a full interpolation.
725 if i.Operation != walkApply {
730 count, err := cr.Count()
738 // If we have no module state in the apply walk, that suggests we've hit
739 // a rather awkward edge-case: the resource this variable refers to
740 // has count = 0 and is the only resource processed so far on this walk,
741 // and so we've ended up not creating any resource states yet. We don't
742 // create a module state until the first resource is written into it,
743 // so the module state doesn't exist when we get here.
745 // In this case we act as we would if we had been passed a module
746 // with an empty resource state map.
751 // We need to determine the list of resource keys to get values from.
752 // This needs to be sorted so the order is deterministic. We used to
753 // use "cr.Count()" but that doesn't work if the count is interpolated
754 // and we can't guarantee that so we instead depend on the state.
756 for k, _ := range ms.Resources {
757 // Get the index number for this resource
760 // If the key is the id, then its just 0 (no explicit index)
762 } else if strings.HasPrefix(k, id+".") {
763 // Grab the index number out of the state
764 index = k[len(id+"."):]
765 if idx := strings.IndexRune(index, '.'); idx >= 0 {
770 // If there was no index then this resource didn't match
771 // the one we're looking for, exit.
776 // Turn the index into an int
777 raw, err := strconv.ParseInt(index, 0, 0)
779 return 0, fmt.Errorf(
780 "%s: error parsing index %q as int: %s",
784 // Keep track of this index if its the max
785 if new := int(raw); new > max {
790 // If we never found any matching resources in the state, we
796 // The result value is "max+1" because we're returning the
797 // max COUNT, not the max INDEX, and we zero-index.