terraform/internal/lang/eval.go

453 lines
16 KiB
Go
Raw Normal View History

package lang
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/ext/dynblock"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/configs/configschema"
"github.com/hashicorp/terraform/internal/instances"
"github.com/hashicorp/terraform/internal/lang/blocktoattr"
"github.com/hashicorp/terraform/internal/tfdiags"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
// ExpandBlock expands any "dynamic" blocks present in the given body. The
// result is a body with those blocks expanded, ready to be evaluated with
// EvalBlock.
//
// If the returned diagnostics contains errors then the result may be
// incomplete or invalid.
func (s *Scope) ExpandBlock(body hcl.Body, schema *configschema.Block) (hcl.Body, tfdiags.Diagnostics) {
spec := schema.DecoderSpec()
traversals := dynblock.ExpandVariablesHCLDec(body, spec)
refs, diags := References(traversals)
ctx, ctxDiags := s.EvalContext(refs)
diags = diags.Append(ctxDiags)
return dynblock.Expand(body, ctx), diags
}
// EvalBlock evaluates the given body using the given block schema and returns
// a cty object value representing its contents. The type of the result conforms
// to the implied type of the given schema.
//
// This function does not automatically expand "dynamic" blocks within the
// body. If that is desired, first call the ExpandBlock method to obtain
// an expanded body to pass to this method.
//
// If the returned diagnostics contains errors then the result may be
// incomplete or invalid.
func (s *Scope) EvalBlock(body hcl.Body, schema *configschema.Block) (cty.Value, tfdiags.Diagnostics) {
spec := schema.DecoderSpec()
refs, diags := ReferencesInBlock(body, schema)
ctx, ctxDiags := s.EvalContext(refs)
diags = diags.Append(ctxDiags)
core: Static-validate resource references against schemas In the initial move to HCL2 we started relying only on full expression evaluation to catch attribute errors, but that's not sufficient for resource attributes in practice because during validation we can't know yet whether a resource reference evaluates to a single object or to a list of objects (if count is set). To address this, here we reinstate some static validation of resource references by analyzing directly the reference objects, disregarding any instance index if present, and produce errors if the remaining subsequent traversal steps do not correspond to items within the resource type schema. This also allows us to produce some more specialized error messages for certain situations. In particular, we can recognize a reference like aws_instance.foo.count, which in 0.11 and prior was a weird special case for determining the count value of a resource block, and offer a helpful error showing the new length(aws_instance.foo) usage pattern. This eventually delegates to the static traversal validation logic that was added to the configschema package in a previous commit, which also includes some specialized error messages that distinguish between attributes and block types in the schema so that the errors relate more directly to constructs the user can see in the configuration. In future we could potentially move more of the checks from the dynamic schema construction step to the static validation step, but resources are the reference type that most needs this immediately due to the ambiguity caused by the instance indexing syntax. We can safely refactor other reference types to be statically validated in later releases. This is verified by two pre-existing context validate tests which we temporarily disabled during earlier work (now re-enabled) and also by a new validate test aimed specifically at the special case for the "count" attribute.
2018-11-21 02:25:05 +01:00
if diags.HasErrors() {
// We'll stop early if we found problems in the references, because
// it's likely evaluation will produce redundant copies of the same errors.
return cty.UnknownVal(schema.ImpliedType()), diags
}
// HACK: In order to remain compatible with some assumptions made in
// Terraform v0.11 and earlier about the approximate equivalence of
// attribute vs. block syntax, we do a just-in-time fixup here to allow
// any attribute in the schema that has a list-of-objects or set-of-objects
// kind to potentially be populated instead by one or more nested blocks
// whose type is the attribute name.
body = blocktoattr.FixUpBlockAttrs(body, schema)
val, evalDiags := hcldec.Decode(body, spec, ctx)
diags = diags.Append(evalDiags)
return val, diags
}
// EvalSelfBlock evaluates the given body only within the scope of the provided
// object and instance key data. References to the object must use self, and the
// key data will only contain count.index or each.key. The static values for
// terraform and path will also be available in this context.
func (s *Scope) EvalSelfBlock(body hcl.Body, self cty.Value, schema *configschema.Block, keyData instances.RepetitionData) (cty.Value, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
spec := schema.DecoderSpec()
vals := make(map[string]cty.Value)
vals["self"] = self
if !keyData.CountIndex.IsNull() {
vals["count"] = cty.ObjectVal(map[string]cty.Value{
"index": keyData.CountIndex,
})
}
if !keyData.EachKey.IsNull() {
vals["each"] = cty.ObjectVal(map[string]cty.Value{
"key": keyData.EachKey,
})
}
refs, refDiags := References(hcldec.Variables(body, spec))
diags = diags.Append(refDiags)
terraformAttrs := map[string]cty.Value{}
pathAttrs := map[string]cty.Value{}
// We could always load the static values for Path and Terraform values,
// but we want to parse the references so that we can get source ranges for
// user diagnostics.
for _, ref := range refs {
// we already loaded the self value
if ref.Subject == addrs.Self {
continue
}
switch subj := ref.Subject.(type) {
case addrs.PathAttr:
val, valDiags := normalizeRefValue(s.Data.GetPathAttr(subj, ref.SourceRange))
diags = diags.Append(valDiags)
pathAttrs[subj.Name] = val
case addrs.TerraformAttr:
val, valDiags := normalizeRefValue(s.Data.GetTerraformAttr(subj, ref.SourceRange))
diags = diags.Append(valDiags)
terraformAttrs[subj.Name] = val
case addrs.CountAttr, addrs.ForEachAttr:
// each and count have already been handled.
default:
// This should have been caught in validation, but point the user
// to the correct location in case something slipped through.
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: `Invalid reference`,
Detail: fmt.Sprintf("The reference to %q is not valid in this context", ref.Subject),
Subject: ref.SourceRange.ToHCL().Ptr(),
})
}
}
vals["path"] = cty.ObjectVal(pathAttrs)
vals["terraform"] = cty.ObjectVal(terraformAttrs)
ctx := &hcl.EvalContext{
Variables: vals,
Functions: s.Functions(),
}
val, decDiags := hcldec.Decode(body, schema.DecoderSpec(), ctx)
diags = diags.Append(decDiags)
return val, diags
}
// EvalExpr evaluates a single expression in the receiving context and returns
// the resulting value. The value will be converted to the given type before
// it is returned if possible, or else an error diagnostic will be produced
// describing the conversion error.
//
// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion
// and just obtain the returned value directly.
//
// If the returned diagnostics contains errors then the result may be
// incomplete, but will always be of the requested type.
func (s *Scope) EvalExpr(expr hcl.Expression, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) {
refs, diags := ReferencesInExpr(expr)
ctx, ctxDiags := s.EvalContext(refs)
diags = diags.Append(ctxDiags)
core: Static-validate resource references against schemas In the initial move to HCL2 we started relying only on full expression evaluation to catch attribute errors, but that's not sufficient for resource attributes in practice because during validation we can't know yet whether a resource reference evaluates to a single object or to a list of objects (if count is set). To address this, here we reinstate some static validation of resource references by analyzing directly the reference objects, disregarding any instance index if present, and produce errors if the remaining subsequent traversal steps do not correspond to items within the resource type schema. This also allows us to produce some more specialized error messages for certain situations. In particular, we can recognize a reference like aws_instance.foo.count, which in 0.11 and prior was a weird special case for determining the count value of a resource block, and offer a helpful error showing the new length(aws_instance.foo) usage pattern. This eventually delegates to the static traversal validation logic that was added to the configschema package in a previous commit, which also includes some specialized error messages that distinguish between attributes and block types in the schema so that the errors relate more directly to constructs the user can see in the configuration. In future we could potentially move more of the checks from the dynamic schema construction step to the static validation step, but resources are the reference type that most needs this immediately due to the ambiguity caused by the instance indexing syntax. We can safely refactor other reference types to be statically validated in later releases. This is verified by two pre-existing context validate tests which we temporarily disabled during earlier work (now re-enabled) and also by a new validate test aimed specifically at the special case for the "count" attribute.
2018-11-21 02:25:05 +01:00
if diags.HasErrors() {
// We'll stop early if we found problems in the references, because
// it's likely evaluation will produce redundant copies of the same errors.
return cty.UnknownVal(wantType), diags
}
val, evalDiags := expr.Value(ctx)
diags = diags.Append(evalDiags)
if wantType != cty.DynamicPseudoType {
var convErr error
val, convErr = convert.Convert(val, wantType)
if convErr != nil {
val = cty.UnknownVal(wantType)
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Incorrect value type",
Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)),
Subject: expr.Range().Ptr(),
Expression: expr,
EvalContext: ctx,
})
}
}
return val, diags
}
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
// EvalReference evaluates the given reference in the receiving scope and
// returns the resulting value. The value will be converted to the given type before
// it is returned if possible, or else an error diagnostic will be produced
// describing the conversion error.
//
// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion
// and just obtain the returned value directly.
//
// If the returned diagnostics contains errors then the result may be
// incomplete, but will always be of the requested type.
func (s *Scope) EvalReference(ref *addrs.Reference, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
// We cheat a bit here and just build an EvalContext for our requested
// reference with the "self" address overridden, and then pull the "self"
// result out of it to return.
ctx, ctxDiags := s.evalContext([]*addrs.Reference{ref}, ref.Subject)
diags = diags.Append(ctxDiags)
val := ctx.Variables["self"]
if val == cty.NilVal {
val = cty.DynamicVal
}
var convErr error
val, convErr = convert.Convert(val, wantType)
if convErr != nil {
val = cty.UnknownVal(wantType)
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Incorrect value type",
Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)),
Subject: ref.SourceRange.ToHCL().Ptr(),
})
}
return val, diags
}
// EvalContext constructs a HCL expression evaluation context whose variable
// scope contains sufficient values to satisfy the given set of references.
//
// Most callers should prefer to use the evaluation helper methods that
// this type offers, but this is here for less common situations where the
// caller will handle the evaluation calls itself.
func (s *Scope) EvalContext(refs []*addrs.Reference) (*hcl.EvalContext, tfdiags.Diagnostics) {
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
return s.evalContext(refs, s.SelfAddr)
}
func (s *Scope) evalContext(refs []*addrs.Reference, selfAddr addrs.Referenceable) (*hcl.EvalContext, tfdiags.Diagnostics) {
if s == nil {
panic("attempt to construct EvalContext for nil Scope")
}
var diags tfdiags.Diagnostics
vals := make(map[string]cty.Value)
funcs := s.Functions()
ctx := &hcl.EvalContext{
Variables: vals,
Functions: funcs,
}
if len(refs) == 0 {
// Easy path for common case where there are no references at all.
return ctx, diags
}
core: Static-validate resource references against schemas In the initial move to HCL2 we started relying only on full expression evaluation to catch attribute errors, but that's not sufficient for resource attributes in practice because during validation we can't know yet whether a resource reference evaluates to a single object or to a list of objects (if count is set). To address this, here we reinstate some static validation of resource references by analyzing directly the reference objects, disregarding any instance index if present, and produce errors if the remaining subsequent traversal steps do not correspond to items within the resource type schema. This also allows us to produce some more specialized error messages for certain situations. In particular, we can recognize a reference like aws_instance.foo.count, which in 0.11 and prior was a weird special case for determining the count value of a resource block, and offer a helpful error showing the new length(aws_instance.foo) usage pattern. This eventually delegates to the static traversal validation logic that was added to the configschema package in a previous commit, which also includes some specialized error messages that distinguish between attributes and block types in the schema so that the errors relate more directly to constructs the user can see in the configuration. In future we could potentially move more of the checks from the dynamic schema construction step to the static validation step, but resources are the reference type that most needs this immediately due to the ambiguity caused by the instance indexing syntax. We can safely refactor other reference types to be statically validated in later releases. This is verified by two pre-existing context validate tests which we temporarily disabled during earlier work (now re-enabled) and also by a new validate test aimed specifically at the special case for the "count" attribute.
2018-11-21 02:25:05 +01:00
// First we'll do static validation of the references. This catches things
// early that might otherwise not get caught due to unknown values being
// present in the scope during planning.
if staticDiags := s.Data.StaticValidateReferences(refs, selfAddr); staticDiags.HasErrors() {
diags = diags.Append(staticDiags)
return ctx, diags
}
// The reference set we are given has not been de-duped, and so there can
// be redundant requests in it for two reasons:
// - The same item is referenced multiple times
// - Both an item and that item's container are separately referenced.
// We will still visit every reference here and ask our data source for
// it, since that allows us to gather a full set of any errors and
// warnings, but once we've gathered all the data we'll then skip anything
// that's redundant in the process of populating our values map.
dataResources := map[string]map[string]cty.Value{}
managedResources := map[string]map[string]cty.Value{}
wholeModules := map[string]cty.Value{}
inputVariables := map[string]cty.Value{}
localValues := map[string]cty.Value{}
pathAttrs := map[string]cty.Value{}
terraformAttrs := map[string]cty.Value{}
countAttrs := map[string]cty.Value{}
2019-06-12 17:07:32 +02:00
forEachAttrs := map[string]cty.Value{}
var self cty.Value
for _, ref := range refs {
rng := ref.SourceRange
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
rawSubj := ref.Subject
if rawSubj == addrs.Self {
if selfAddr == nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: `Invalid "self" reference`,
// This detail message mentions some current practice that
// this codepath doesn't really "know about". If the "self"
// object starts being supported in more contexts later then
// we'll need to adjust this message.
Detail: `The "self" object is not available in this context. This object can be used only in resource provisioner, connection, and postcondition blocks.`,
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
Subject: ref.SourceRange.ToHCL().Ptr(),
})
continue
}
if selfAddr == addrs.Self {
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
// Programming error: the self address cannot alias itself.
panic("scope SelfAddr attempting to alias itself")
}
// self can only be used within a resource instance
subj := selfAddr.(addrs.ResourceInstance)
val, valDiags := normalizeRefValue(s.Data.GetResource(subj.ContainingResource(), rng))
diags = diags.Append(valDiags)
// Self is an exception in that it must always resolve to a
// particular instance. We will still insert the full resource into
// the context below.
var hclDiags hcl.Diagnostics
// We should always have a valid self index by this point, but in
// the case of an error, self may end up as a cty.DynamicValue.
switch k := subj.Key.(type) {
case addrs.IntKey:
self, hclDiags = hcl.Index(val, cty.NumberIntVal(int64(k)), ref.SourceRange.ToHCL().Ptr())
diags = diags.Append(hclDiags)
case addrs.StringKey:
self, hclDiags = hcl.Index(val, cty.StringVal(string(k)), ref.SourceRange.ToHCL().Ptr())
diags = diags.Append(hclDiags)
default:
self = val
}
continue
}
// This type switch must cover all of the "Referenceable" implementations
// in package addrs, however we are removing the possibility of
// Instances beforehand.
switch addr := rawSubj.(type) {
case addrs.ResourceInstance:
rawSubj = addr.ContainingResource()
case addrs.ModuleCallInstance:
rawSubj = addr.Call
case addrs.ModuleCallInstanceOutput:
rawSubj = addr.Call.Call
}
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
switch subj := rawSubj.(type) {
case addrs.Resource:
var into map[string]map[string]cty.Value
switch subj.Mode {
case addrs.ManagedResourceMode:
into = managedResources
case addrs.DataResourceMode:
into = dataResources
default:
panic(fmt.Errorf("unsupported ResourceMode %s", subj.Mode))
}
val, valDiags := normalizeRefValue(s.Data.GetResource(subj, rng))
diags = diags.Append(valDiags)
r := subj
if into[r.Type] == nil {
into[r.Type] = make(map[string]cty.Value)
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
}
into[r.Type][r.Name] = val
case addrs.ModuleCall:
val, valDiags := normalizeRefValue(s.Data.GetModule(subj, rng))
diags = diags.Append(valDiags)
wholeModules[subj.Name] = val
case addrs.InputVariable:
val, valDiags := normalizeRefValue(s.Data.GetInputVariable(subj, rng))
diags = diags.Append(valDiags)
inputVariables[subj.Name] = val
case addrs.LocalValue:
val, valDiags := normalizeRefValue(s.Data.GetLocalValue(subj, rng))
diags = diags.Append(valDiags)
localValues[subj.Name] = val
case addrs.PathAttr:
val, valDiags := normalizeRefValue(s.Data.GetPathAttr(subj, rng))
diags = diags.Append(valDiags)
pathAttrs[subj.Name] = val
case addrs.TerraformAttr:
val, valDiags := normalizeRefValue(s.Data.GetTerraformAttr(subj, rng))
diags = diags.Append(valDiags)
terraformAttrs[subj.Name] = val
case addrs.CountAttr:
val, valDiags := normalizeRefValue(s.Data.GetCountAttr(subj, rng))
diags = diags.Append(valDiags)
countAttrs[subj.Name] = val
2019-06-12 17:07:32 +02:00
case addrs.ForEachAttr:
val, valDiags := normalizeRefValue(s.Data.GetForEachAttr(subj, rng))
diags = diags.Append(valDiags)
forEachAttrs[subj.Name] = val
default:
// Should never happen
terraform: ugly huge change to weave in new HCL2-oriented types Due to how deeply the configuration types go into Terraform Core, there isn't a great way to switch out to HCL2 gradually. As a consequence, this huge commit gets us from the old state to a _compilable_ new state, but does not yet attempt to fix any tests and has a number of known missing parts and bugs. We will continue to iterate on this in forthcoming commits, heading back towards passing tests and making Terraform fully-functional again. The three main goals here are: - Use the configuration models from the "configs" package instead of the older models in the "config" package, which is now deprecated and preserved only to help us write our migration tool. - Do expression inspection and evaluation using the functionality of the new "lang" package, instead of the Interpolator type and related functionality in the main "terraform" package. - Represent addresses of various objects using types in the addrs package, rather than hand-constructed strings. This is not critical to support the above, but was a big help during the implementation of these other points since it made it much more explicit what kind of address is expected in each context. Since our new packages are built to accommodate some future planned features that are not yet implemented (e.g. the "for_each" argument on resources, "count"/"for_each" on modules), and since there's still a fair amount of functionality still using old-style APIs, there is a moderate amount of shimming here to connect new assumptions with old, hopefully in a way that makes it easier to find and eliminate these shims later. I apologize in advance to the person who inevitably just found this huge commit while spelunking through the commit history.
2018-04-30 19:33:53 +02:00
panic(fmt.Errorf("Scope.buildEvalContext cannot handle address type %T", rawSubj))
}
}
lang: Allow "resource." prefix as another way to refer to resources The current way to refer to a managed resource is to use its resource type name as a top-level symbol in the reference. This is convenient and makes sense given that managed resources are the primary kind of object in Terraform. However, it does mean that an externally-extensible namespace (the set of all possible resource type names) overlaps with a reserved word namespace (the special prefixes like "path", "var", etc), and thus introducing any new reserved prefix in future risks masking an existing resource type so it can't be used anymore. We only intend to introduce new reserved symbols as part of future language editions that each module can opt into separately, and when doing so we will always research to try to choose a name that doesn't overlap with commonly-used providers, but not all providers are visible to us and so there is always a small chance that the name we choose will already be in use by a third-party provider. In preparation for that event, this introduces an alternative way to refer to managed resources that mimics the reference style used for data resources: resource.type.name . When using this form, the second portion is _always_ a resource type name and never a reserved word. There is currently no need to use this because all of the already-reserved symbol names are effectively blocked from use by existing Terraform versions that lack this escape hatch. Therefore there's no explicit documentation about it yet. The intended use for this is that a module upgrade tool for a future language edition would detect references to resource types that have now become reserved words and add the "resource." prefix to keep that functionality working. Existing modules that aren't opted in to the new language edition would keep working without that prefix, thus keeping to compatibility promises.
2021-05-15 01:42:30 +02:00
// Managed resources are exposed in two different locations. The primary
// is at the top level where the resource type name is the root of the
// traversal, but we also expose them under "resource" as an escaping
// technique if we add a reserved name in a future language edition which
// conflicts with someone's existing provider.
for k, v := range buildResourceObjects(managedResources) {
vals[k] = v
}
lang: Allow "resource." prefix as another way to refer to resources The current way to refer to a managed resource is to use its resource type name as a top-level symbol in the reference. This is convenient and makes sense given that managed resources are the primary kind of object in Terraform. However, it does mean that an externally-extensible namespace (the set of all possible resource type names) overlaps with a reserved word namespace (the special prefixes like "path", "var", etc), and thus introducing any new reserved prefix in future risks masking an existing resource type so it can't be used anymore. We only intend to introduce new reserved symbols as part of future language editions that each module can opt into separately, and when doing so we will always research to try to choose a name that doesn't overlap with commonly-used providers, but not all providers are visible to us and so there is always a small chance that the name we choose will already be in use by a third-party provider. In preparation for that event, this introduces an alternative way to refer to managed resources that mimics the reference style used for data resources: resource.type.name . When using this form, the second portion is _always_ a resource type name and never a reserved word. There is currently no need to use this because all of the already-reserved symbol names are effectively blocked from use by existing Terraform versions that lack this escape hatch. Therefore there's no explicit documentation about it yet. The intended use for this is that a module upgrade tool for a future language edition would detect references to resource types that have now become reserved words and add the "resource." prefix to keep that functionality working. Existing modules that aren't opted in to the new language edition would keep working without that prefix, thus keeping to compatibility promises.
2021-05-15 01:42:30 +02:00
vals["resource"] = cty.ObjectVal(buildResourceObjects(managedResources))
vals["data"] = cty.ObjectVal(buildResourceObjects(dataResources))
vals["module"] = cty.ObjectVal(wholeModules)
vals["var"] = cty.ObjectVal(inputVariables)
vals["local"] = cty.ObjectVal(localValues)
vals["path"] = cty.ObjectVal(pathAttrs)
vals["terraform"] = cty.ObjectVal(terraformAttrs)
vals["count"] = cty.ObjectVal(countAttrs)
2019-06-12 17:07:32 +02:00
vals["each"] = cty.ObjectVal(forEachAttrs)
if self != cty.NilVal {
vals["self"] = self
}
return ctx, diags
}
func buildResourceObjects(resources map[string]map[string]cty.Value) map[string]cty.Value {
vals := make(map[string]cty.Value)
for typeName, nameVals := range resources {
vals[typeName] = cty.ObjectVal(nameVals)
}
return vals
}
func normalizeRefValue(val cty.Value, diags tfdiags.Diagnostics) (cty.Value, tfdiags.Diagnostics) {
if diags.HasErrors() {
// If there are errors then we will force an unknown result so that
// we can still evaluate and catch type errors but we'll avoid
// producing redundant re-statements of the same errors we've already
// dealt with here.
return cty.UnknownVal(val.Type()), diags
}
return val, diags
}