From 82ff3c19e90197d572c502043cda5ae6d13d6223 Mon Sep 17 00:00:00 2001 From: Alex Tomlins Date: Wed, 5 Aug 2020 11:39:02 +0100 Subject: [PATCH] Fix naming.NamePrefixFromName with hex suffix. github.com/hashicorp/terraform-plugin-sdk/helper/resource.PrefixedUniqueId generates names with a suffix containing hex digits, whereas the naming package was assuming these were purely decimal. This caused the name_prefix property not to be set in the statefile for some resources (eg aws_security_group) when the generated name included hex digits a-f. --- aws/internal/naming/naming.go | 2 +- aws/internal/naming/naming_test.go | 31 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/aws/internal/naming/naming.go b/aws/internal/naming/naming.go index d1313be3ffa..24cde915254 100644 --- a/aws/internal/naming/naming.go +++ b/aws/internal/naming/naming.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/terraform" ) -var resourceUniqueIDSuffixRegexpPattern = fmt.Sprintf("\\d{%d}$", resource.UniqueIDSuffixLength) +var resourceUniqueIDSuffixRegexpPattern = fmt.Sprintf("[[:xdigit:]]{%d}$", resource.UniqueIDSuffixLength) var resourceUniqueIDSuffixRegexp = regexp.MustCompile(resourceUniqueIDSuffixRegexpPattern) var resourceUniqueIDRegexpPattern = resourcePrefixedUniqueIDRegexpPattern(resource.UniqueIdPrefix) diff --git a/aws/internal/naming/naming_test.go b/aws/internal/naming/naming_test.go index d08b3b75d00..2d0241e1097 100644 --- a/aws/internal/naming/naming_test.go +++ b/aws/internal/naming/naming_test.go @@ -108,11 +108,21 @@ func TestHasResourceUniqueIdSuffix(t *testing.T) { Input: "test-20060102150405000000000001", Expected: true, }, + { + TestName: "correct suffix with hex, incorrect prefix", + Input: "test-200601021504050000000000a1", + Expected: true, + }, { TestName: "correct suffix, correct prefix", Input: "terraform-20060102150405000000000001", Expected: true, }, + { + TestName: "correct suffix with hex, correct prefix", + Input: "terraform-2006010215040500000000000a", + Expected: true, + }, } for _, testCase := range testCases { @@ -152,6 +162,11 @@ func TestNamePrefixFromName(t *testing.T) { Input: "test-20060102150405000000000001", Expected: strPtr("test-"), }, + { + TestName: "correct prefix with hyphen, correct suffix with hex", + Input: "test-200601021504050000000000f1", + Expected: strPtr("test-"), + }, { TestName: "incorrect prefix, correct suffix", Input: "terraform-20060102150405000000000001", @@ -177,4 +192,20 @@ func TestNamePrefixFromName(t *testing.T) { } }) } + + t.Run("extracting prefix from generated name", func(t *testing.T) { + for i := 0; i < 10; i++ { + prefix := "test-" + input := Generate("", prefix) + got := NamePrefixFromName(input) + + if got == nil { + t.Errorf("run%d: got nil, expected %s for input %s", i, prefix, input) + } + + if got != nil && prefix != *got { + t.Errorf("run%d: got %s, expected %s for input %s", i, *got, prefix, input) + } + } + }) }