diff --git a/config/config.go b/config/config.go index 7f8d0a121..fd6cfba3c 100644 --- a/config/config.go +++ b/config/config.go @@ -4,6 +4,7 @@ package config import ( "fmt" + "strconv" "strings" "github.com/hashicorp/terraform/helper/multierror" @@ -222,10 +223,24 @@ func NewResourceVariable(key string) (*ResourceVariable, error) { parts := strings.SplitN(key, ".", 3) field := parts[2] multi := false + var index int - if idx := strings.Index(field, "."); idx != -1 && field[:idx] == "*" { - multi = true - field = field[idx+1:] + if idx := strings.Index(field, "."); idx != -1 { + indexStr := field[:idx] + multi = indexStr == "*" + index = -1 + + if !multi { + indexInt, err := strconv.ParseInt(indexStr, 0, 0) + if err == nil { + multi = true + index = int(indexInt) + } + } + + if multi { + field = field[idx+1:] + } } return &ResourceVariable{ @@ -233,6 +248,7 @@ func NewResourceVariable(key string) (*ResourceVariable, error) { Name: parts[1], Field: field, Multi: multi, + Index: index, key: key, }, nil } diff --git a/config/config_test.go b/config/config_test.go index 29f522444..c64eecde5 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -94,6 +94,34 @@ func TestResourceVariable_Multi(t *testing.T) { } } +func TestResourceVariable_MultiIndex(t *testing.T) { + cases := []struct { + Input string + Index int + Field string + }{ + {"foo.bar.*.baz", -1, "baz"}, + {"foo.bar.0.baz", 0, "baz"}, + {"foo.bar.5.baz", 5, "baz"}, + } + + for _, tc := range cases { + v, err := NewResourceVariable(tc.Input) + if err != nil { + t.Fatalf("err: %s", err) + } + if !v.Multi { + t.Fatalf("should be multi: %s", tc.Input) + } + if v.Index != tc.Index { + t.Fatalf("bad: %d\n\n%s", v.Index, tc.Input) + } + if v.Field != tc.Field { + t.Fatalf("bad: %s\n\n%s", v.Field, tc.Input) + } + } +} + func TestNewUserVariable(t *testing.T) { v, err := NewUserVariable("var.bar") if err != nil {