From b6bfc4798d21eea5d71482fc99585663691a0620 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 10 Feb 2017 10:41:41 -0800 Subject: [PATCH] config: Resource.Count should type check Fixes #11800 Type check the value of count so we don't panic on the conversion. I wondered "why didn't we do this before?" There is no excuse for NOT doing it at all but the reasoning was beacuse prior to the list/map work in 0.7, the value couldn't be anything other than a string since any primitive can turn into a string. Regardless, we should've always done this. --- config/config.go | 9 ++++++++- config/config_test.go | 19 +++++++++++++++++++ config/test-fixtures/count-list/main.tf | 3 +++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 config/test-fixtures/count-list/main.tf diff --git a/config/config.go b/config/config.go index 14e35d6fa..5210e4937 100644 --- a/config/config.go +++ b/config/config.go @@ -212,7 +212,14 @@ func (r *Module) Id() string { // Count returns the count of this resource. func (r *Resource) Count() (int, error) { - v, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) + raw := r.RawCount.Value() + count, ok := r.RawCount.Value().(string) + if !ok { + return 0, fmt.Errorf( + "expected count to be a string or int, got %T", raw) + } + + v, err := strconv.ParseInt(count, 0, 0) if err != nil { return 0, err } diff --git a/config/config_test.go b/config/config_test.go index f554061ea..1c7b36e04 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/hashicorp/hil/ast" "github.com/hashicorp/terraform/helper/logging" ) @@ -98,6 +99,24 @@ func TestConfigCount_string(t *testing.T) { } } +// Terraform GH-11800 +func TestConfigCount_list(t *testing.T) { + c := testConfig(t, "count-list") + + // The key is to interpolate so it doesn't fail parsing + c.Resources[0].RawCount.Interpolate(map[string]ast.Variable{ + "var.list": ast.Variable{ + Value: []ast.Variable{}, + Type: ast.TypeList, + }, + }) + + _, err := c.Resources[0].Count() + if err == nil { + t.Fatal("should error") + } +} + func TestConfigCount_var(t *testing.T) { c := testConfig(t, "count-var") _, err := c.Resources[0].Count() diff --git a/config/test-fixtures/count-list/main.tf b/config/test-fixtures/count-list/main.tf new file mode 100644 index 000000000..3c6f1ab8f --- /dev/null +++ b/config/test-fixtures/count-list/main.tf @@ -0,0 +1,3 @@ +resource "foo" "bar" { + count = "${var.list}" +}