From 5cf791861f7364bedc2cd2c9147b6120057d39d9 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Wed, 2 May 2018 17:51:01 -0700 Subject: [PATCH] configs: Allow looking up resources by resource addresses. Throughout the main "terraform" package we identify resources using the address types, and so this helper is useful to make concise transitions between the address types and the configuration types. As part of this, we use the address types to produce the keys used in our resource maps. This has no visible change in behavior since the prior implementation produced an equal result, but this change ensures that ResourceByAddr cannot be broken by hypothetical future changes to the key serialization. --- configs/module.go | 16 ++++++++++++++++ configs/resource.go | 9 +-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/configs/module.go b/configs/module.go index 21f021fb8..250f9d345 100644 --- a/configs/module.go +++ b/configs/module.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/hashicorp/hcl2/hcl" + + "github.com/hashicorp/terraform/addrs" ) // Module is a container for a set of configuration constructs that are @@ -99,6 +101,20 @@ func NewModule(primaryFiles, overrideFiles []*File) (*Module, hcl.Diagnostics) { return mod, diags } +// ResourceByAddr returns the configuration for the resource with the given +// address, or nil if there is no such resource. +func (m *Module) ResourceByAddr(addr addrs.Resource) *Resource { + key := addr.String() + switch addr.Mode { + case addrs.ManagedResourceMode: + return m.ManagedResources[key] + case addrs.DataResourceMode: + return m.DataResources[key] + default: + return nil + } +} + func (m *Module) appendFile(file *File) hcl.Diagnostics { var diags hcl.Diagnostics diff --git a/configs/resource.go b/configs/resource.go index 9909fa4cb..87d833315 100644 --- a/configs/resource.go +++ b/configs/resource.go @@ -47,14 +47,7 @@ type ManagedResource struct { } func (r *Resource) moduleUniqueKey() string { - switch r.Mode { - case addrs.ManagedResourceMode: - return fmt.Sprintf("%s.%s", r.Name, r.Type) - case addrs.DataResourceMode: - return fmt.Sprintf("data.%s.%s", r.Name, r.Type) - default: - panic(fmt.Errorf("Resource has invalid resource mode %s", r.Mode)) - } + return r.Addr().String() } // Addr returns a resource address for the receiver that is relative to the