From aa6a758f6b8434b7fd4f369b9799301a2f57c746 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sun, 6 Jul 2014 13:46:56 -0700 Subject: [PATCH] config: if count > 1, variable references must have index /cc @pearkes - Here is that validation --- config/config.go | 24 +++++++++++++++---- config/config_test.go | 7 ++++++ .../validate-bad-multi-resource/main.tf | 7 ++++++ 3 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 config/test-fixtures/validate-bad-multi-resource/main.tf diff --git a/config/config.go b/config/config.go index 39f0cce0b7..7f8d0a121e 100644 --- a/config/config.go +++ b/config/config.go @@ -66,7 +66,9 @@ type ResourceVariable struct { Type string // Resource type, i.e. "aws_instance" Name string // Resource name Field string // Resource field - Multi bool // True if multi-variable: aws_instance.foo.*.id + + Multi bool // True if multi-variable: aws_instance.foo.*.id + Index int // Index for multi-variable: aws_instance.foo.1.id == 1 key string } @@ -124,9 +126,9 @@ func (c *Config) Validate() error { } // Check that all references to resources are valid - resources := make(map[string]struct{}) + resources := make(map[string]*Resource) for _, r := range c.Resources { - resources[r.Id()] = struct{}{} + resources[r.Id()] = r } for source, vs := range vars { for _, v := range vs { @@ -136,12 +138,26 @@ func (c *Config) Validate() error { } id := fmt.Sprintf("%s.%s", rv.Type, rv.Name) - if _, ok := resources[id]; !ok { + r, ok := resources[id] + if !ok { errs = append(errs, fmt.Errorf( "%s: unknown resource '%s' referenced in variable %s", source, id, rv.FullKey())) + continue + } + + // If it is a multi reference and resource has a single + // count, it is an error. + if r.Count > 1 && !rv.Multi { + errs = append(errs, fmt.Errorf( + "%s: variable '%s' must specify index for multi-count "+ + "resource %s", + source, + rv.FullKey(), + id)) + continue } } } diff --git a/config/config_test.go b/config/config_test.go index 613c6a58b6..29f5224444 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -15,6 +15,13 @@ func TestConfigValidate(t *testing.T) { } } +func TestConfigValidate_badMultiResource(t *testing.T) { + c := testConfig(t, "validate-bad-multi-resource") + if err := c.Validate(); err == nil { + t.Fatal("should not be valid") + } +} + func TestConfigValidate_outputBadField(t *testing.T) { c := testConfig(t, "validate-output-bad-field") if err := c.Validate(); err == nil { diff --git a/config/test-fixtures/validate-bad-multi-resource/main.tf b/config/test-fixtures/validate-bad-multi-resource/main.tf new file mode 100644 index 0000000000..c92ada9686 --- /dev/null +++ b/config/test-fixtures/validate-bad-multi-resource/main.tf @@ -0,0 +1,7 @@ +resource "aws_instance" "web" { + count = 5 +} + +output "ip" { + value = "${aws_instance.web.id}" +}