From 78e056770c598b7d93ac9b18f94cd2aa00383335 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 2 Jul 2014 21:06:26 -0700 Subject: [PATCH] config: validate that resource references are valid --- config/config.go | 28 +++++++++++++++++-- config/config_test.go | 7 +++++ .../validate-unknown-resource-var/main.tf | 6 ++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 config/test-fixtures/validate-unknown-resource-var/main.tf diff --git a/config/config.go b/config/config.go index 0ac049f33..bab8a6322 100644 --- a/config/config.go +++ b/config/config.go @@ -89,10 +89,13 @@ func (r *Resource) Id() string { // Validate does some basic semantic checking of the configuration. func (c *Config) Validate() error { + var errs []error + + vars := c.allVariables() + // Check for references to user variables that do not actually // exist and record those errors. - var errs []error - for source, v := range c.allVariables() { + for source, v := range vars { uv, ok := v.(*UserVariable) if !ok { continue @@ -106,6 +109,27 @@ func (c *Config) Validate() error { } } + // Check that all references to resources are valid + resources := make(map[string]struct{}) + for _, r := range c.Resources { + resources[r.Id()] = struct{}{} + } + for source, v := range vars { + rv, ok := v.(*ResourceVariable) + if !ok { + continue + } + + id := fmt.Sprintf("%s.%s", rv.Type, rv.Name) + if _, ok := resources[id]; !ok { + errs = append(errs, fmt.Errorf( + "%s: unknown resource '%s' referenced in variable %s", + source, + id, + rv.FullKey())) + } + } + if len(errs) > 0 { return &MultiError{Errors: errs} } diff --git a/config/config_test.go b/config/config_test.go index 3c68e0f9d..4974b7276 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -15,6 +15,13 @@ func TestConfigValidate(t *testing.T) { } } +func TestConfigValidate_unknownResourceVar(t *testing.T) { + c := testConfig(t, "validate-unknown-resource-var") + if err := c.Validate(); err == nil { + t.Fatal("should not be valid") + } +} + func TestConfigValidate_unknownVar(t *testing.T) { c := testConfig(t, "validate-unknownvar") if err := c.Validate(); err == nil { diff --git a/config/test-fixtures/validate-unknown-resource-var/main.tf b/config/test-fixtures/validate-unknown-resource-var/main.tf new file mode 100644 index 000000000..3c89cc013 --- /dev/null +++ b/config/test-fixtures/validate-unknown-resource-var/main.tf @@ -0,0 +1,6 @@ +resource "aws_instance" "web" { +} + +resource "aws_instance" "db" { + ami = "${aws_instance.loadbalancer.foo}" +}