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 {
320 if v.Field != "env" {
322 "%s: only supported key for 'terraform.X' interpolations is 'env'", n)
327 "%s: internal error: nil Meta. Please report a bug.", n)
330 result[n] = ast.Variable{Type: ast.TypeString, Value: i.Meta.Env}
334 func (i *Interpolater) valueUserVar(
335 scope *InterpolationScope,
337 v *config.UserVariable,
338 result map[string]ast.Variable) error {
339 i.VariableValuesLock.Lock()
340 defer i.VariableValuesLock.Unlock()
341 val, ok := i.VariableValues[v.Name]
343 varValue, err := hil.InterfaceToVariable(val)
345 return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
352 if _, ok := result[n]; !ok && i.Operation == walkValidate {
353 result[n] = unknownVariable()
357 // Look up if we have any variables with this prefix because
358 // those are map overrides. Include those.
359 for k, val := range i.VariableValues {
360 if strings.HasPrefix(k, v.Name+".") {
361 keyComponents := strings.Split(k, ".")
362 overrideKey := keyComponents[len(keyComponents)-1]
364 mapInterface, ok := result["var."+v.Name]
366 return fmt.Errorf("override for non-existent variable: %s", v.Name)
369 mapVariable := mapInterface.Value.(map[string]ast.Variable)
371 varValue, err := hil.InterfaceToVariable(val)
373 return fmt.Errorf("cannot convert %s value %q to an ast.Variable for interpolation: %s",
376 mapVariable[overrideKey] = varValue
383 func (i *Interpolater) computeResourceVariable(
384 scope *InterpolationScope,
385 v *config.ResourceVariable) (*ast.Variable, error) {
388 id = fmt.Sprintf("%s.%d", id, v.Index)
392 defer i.StateLock.RUnlock()
394 unknownVariable := unknownVariable()
396 // These variables must be declared early because of the use of GOTO
400 // Get the information about this resource variable, and verify
401 // that it exists and such.
402 module, cr, err := i.resourceVariableInfo(scope, v)
407 // If we're requesting "count" its a special variable that we grab
408 // directly from the config itself.
409 if v.Field == "count" {
412 count, err = cr.Count()
414 count, err = i.resourceCountMax(module, cr, v)
417 return nil, fmt.Errorf(
418 "Error reading %s count: %s",
423 return &ast.Variable{Type: ast.TypeInt, Value: count}, nil
426 // Get the resource out from the state. We know the state exists
427 // at this point and if there is a state, we expect there to be a
428 // resource with the given name.
430 if module != nil && len(module.Resources) > 0 {
432 r, ok = module.Resources[id]
433 if !ok && v.Multi && v.Index == 0 {
434 r, ok = module.Resources[v.ResourceId()]
440 if r == nil || r.Primary == nil {
441 if i.Operation == walkApply || i.Operation == walkPlan {
442 return nil, fmt.Errorf(
443 "Resource '%s' not found for variable '%s'",
448 // If we have no module in the state yet or count, return empty.
449 // NOTE(@mitchellh): I actually don't know why this is here. During
450 // a refactor I kept this here to maintain the same behavior, but
451 // I'm not sure why its here.
452 if module == nil || len(module.Resources) == 0 {
459 if attr, ok := r.Primary.Attributes[v.Field]; ok {
460 v, err := hil.InterfaceToVariable(attr)
464 // computed list or map attribute
465 _, isList = r.Primary.Attributes[v.Field+".#"]
466 _, isMap = r.Primary.Attributes[v.Field+".%"]
468 variable, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
469 return &variable, err
472 // At apply time, we can't do the "maybe has it" check below
473 // that we need for plans since parent elements might be computed.
474 // Therefore, it is an error and we're missing the key.
476 // TODO: test by creating a state and configuration that is referencing
477 // a non-existent variable "foo.bar" where the state only has "foo"
478 // and verify plan works, but apply doesn't.
479 if i.Operation == walkApply || i.Operation == walkDestroy {
483 // We didn't find the exact field, so lets separate the dots
484 // and see if anything along the way is a computed set. i.e. if
485 // we have "foo.0.bar" as the field, check to see if "foo" is
486 // a computed list. If so, then the whole thing is computed.
487 if parts := strings.Split(v.Field, "."); len(parts) > 1 {
488 for i := 1; i < len(parts); i++ {
489 // Lists and sets make this
490 key := fmt.Sprintf("%s.#", strings.Join(parts[:i], "."))
491 if attr, ok := r.Primary.Attributes[key]; ok {
492 v, err := hil.InterfaceToVariable(attr)
497 key = fmt.Sprintf("%s", strings.Join(parts[:i], "."))
498 if attr, ok := r.Primary.Attributes[key]; ok {
499 v, err := hil.InterfaceToVariable(attr)
506 // Validation for missing interpolations should happen at a higher
507 // semantic level. If we reached this point and don't have variables,
508 // just return the computed value.
509 if scope == nil && scope.Resource == nil {
510 return &unknownVariable, nil
513 // If the operation is refresh, it isn't an error for a value to
514 // be unknown. Instead, we return that the value is computed so
515 // that the graph can continue to refresh other nodes. It doesn't
516 // matter because the config isn't interpolated anyways.
518 // For a Destroy, we're also fine with computed values, since our goal is
519 // only to get destroy nodes for existing resources.
521 // For an input walk, computed values are okay to return because we're only
522 // looking for missing variables to prompt the user for.
523 if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkInput {
524 return &unknownVariable, nil
527 return nil, fmt.Errorf(
528 "Resource '%s' does not have attribute '%s' "+
535 func (i *Interpolater) computeResourceMultiVariable(
536 scope *InterpolationScope,
537 v *config.ResourceVariable) (*ast.Variable, error) {
539 defer i.StateLock.RUnlock()
541 unknownVariable := unknownVariable()
543 // If we're only looking for input, we don't need to expand a
544 // multi-variable. This prevents us from encountering things that should be
545 // known but aren't because the state has yet to be refreshed.
546 if i.Operation == walkInput {
547 return &unknownVariable, nil
550 // Get the information about this resource variable, and verify
551 // that it exists and such.
552 module, cr, err := i.resourceVariableInfo(scope, v)
557 // Get the keys for all the resources that are created for this resource
558 countMax, err := i.resourceCountMax(module, cr, v)
563 // If count is zero, we return an empty list
565 return &ast.Variable{Type: ast.TypeList, Value: []ast.Variable{}}, nil
568 // If we have no module in the state yet or count, return unknown
569 if module == nil || len(module.Resources) == 0 {
570 return &unknownVariable, nil
573 var values []interface{}
574 for idx := 0; idx < countMax; idx++ {
575 id := fmt.Sprintf("%s.%d", v.ResourceId(), idx)
577 // ID doesn't have a trailing index. We try both here, but if a value
578 // without a trailing index is found we prefer that. This choice
579 // is for legacy reasons: older versions of TF preferred it.
580 if id == v.ResourceId()+".0" {
581 potential := v.ResourceId()
582 if _, ok := module.Resources[potential]; ok {
587 r, ok := module.Resources[id]
592 if r.Primary == nil {
596 if singleAttr, ok := r.Primary.Attributes[v.Field]; ok {
597 values = append(values, singleAttr)
601 // computed list or map attribute
602 _, isList := r.Primary.Attributes[v.Field+".#"]
603 _, isMap := r.Primary.Attributes[v.Field+".%"]
604 if !(isList || isMap) {
607 multiAttr, err := i.interpolateComplexTypeAttribute(v.Field, r.Primary.Attributes)
612 values = append(values, multiAttr)
615 if len(values) == 0 {
616 // If the operation is refresh, it isn't an error for a value to
617 // be unknown. Instead, we return that the value is computed so
618 // that the graph can continue to refresh other nodes. It doesn't
619 // matter because the config isn't interpolated anyways.
621 // For a Destroy, we're also fine with computed values, since our goal is
622 // only to get destroy nodes for existing resources.
624 // For an input walk, computed values are okay to return because we're only
625 // looking for missing variables to prompt the user for.
626 if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput {
627 return &unknownVariable, nil
630 return nil, fmt.Errorf(
631 "Resource '%s' does not have attribute '%s' "+
638 variable, err := hil.InterfaceToVariable(values)
639 return &variable, err
642 func (i *Interpolater) interpolateComplexTypeAttribute(
644 attributes map[string]string) (ast.Variable, error) {
646 // We can now distinguish between lists and maps in state by the count field:
647 // - lists (and by extension, sets) use the traditional .# notation
648 // - maps use the newer .% notation
649 // Consequently here we can decide how to deal with the keys appropriately
650 // based on whether the type is a map of list.
651 if lengthAttr, isList := attributes[resourceID+".#"]; isList {
652 log.Printf("[DEBUG] Interpolating computed list element attribute %s (%s)",
653 resourceID, lengthAttr)
655 // In Terraform's internal dotted representation of list-like attributes, the
656 // ".#" count field is marked as unknown to indicate "this whole list is
657 // unknown". We must honor that meaning here so computed references can be
658 // treated properly during the plan phase.
659 if lengthAttr == config.UnknownVariableValue {
660 return unknownVariable(), nil
663 expanded := flatmap.Expand(attributes, resourceID)
664 return hil.InterfaceToVariable(expanded)
667 if lengthAttr, isMap := attributes[resourceID+".%"]; isMap {
668 log.Printf("[DEBUG] Interpolating computed map element attribute %s (%s)",
669 resourceID, lengthAttr)
671 // In Terraform's internal dotted representation of map attributes, the
672 // ".%" count field is marked as unknown to indicate "this whole list is
673 // unknown". We must honor that meaning here so computed references can be
674 // treated properly during the plan phase.
675 if lengthAttr == config.UnknownVariableValue {
676 return unknownVariable(), nil
679 expanded := flatmap.Expand(attributes, resourceID)
680 return hil.InterfaceToVariable(expanded)
683 return ast.Variable{}, fmt.Errorf("No complex type %s found", resourceID)
686 func (i *Interpolater) resourceVariableInfo(
687 scope *InterpolationScope,
688 v *config.ResourceVariable) (*ModuleState, *config.Resource, error) {
689 // Get the module tree that contains our current path. This is
690 // either the current module (path is empty) or a child.
692 if len(scope.Path) > 1 {
693 modTree = i.Module.Child(scope.Path[1:])
696 // Get the resource from the configuration so we can verify
697 // that the resource is in the configuration and so we can access
698 // the configuration if we need to.
699 var cr *config.Resource
700 for _, r := range modTree.Config().Resources {
701 if r.Id() == v.ResourceId() {
707 // Get the relevant module
708 module := i.State.ModuleByPath(scope.Path)
709 return module, cr, nil
712 func (i *Interpolater) resourceCountMax(
715 v *config.ResourceVariable) (int, error) {
718 // If we're NOT applying, then we assume we can read the count
719 // from the state. Plan and so on may not have any state yet so
720 // we do a full interpolation.
721 if i.Operation != walkApply {
726 count, err := cr.Count()
734 // We need to determine the list of resource keys to get values from.
735 // This needs to be sorted so the order is deterministic. We used to
736 // use "cr.Count()" but that doesn't work if the count is interpolated
737 // and we can't guarantee that so we instead depend on the state.
739 for k, _ := range ms.Resources {
740 // Get the index number for this resource
743 // If the key is the id, then its just 0 (no explicit index)
745 } else if strings.HasPrefix(k, id+".") {
746 // Grab the index number out of the state
747 index = k[len(id+"."):]
748 if idx := strings.IndexRune(index, '.'); idx >= 0 {
753 // If there was no index then this resource didn't match
754 // the one we're looking for, exit.
759 // Turn the index into an int
760 raw, err := strconv.ParseInt(index, 0, 0)
762 return 0, fmt.Errorf(
763 "%s: error parsing index %q as int: %s",
767 // Keep track of this index if its the max
768 if new := int(raw); new > max {
773 // If we never found any matching resources in the state, we
779 // The result value is "max+1" because we're returning the
780 // max COUNT, not the max INDEX, and we zero-index.