From 05ac30287fb2d749d3d5a386b5e5ccec238e5321 Mon Sep 17 00:00:00 2001 From: Kishan B Date: Tue, 21 May 2024 17:02:59 +0530 Subject: [PATCH] Handle duplicated module address in state json to support very old terraform versions --- pkg/internal/parser/json_parser.go | 8 +++-- pkg/internal/parser/json_parser_test.go | 48 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/pkg/internal/parser/json_parser.go b/pkg/internal/parser/json_parser.go index c231bce..ef08931 100644 --- a/pkg/internal/parser/json_parser.go +++ b/pkg/internal/parser/json_parser.go @@ -60,10 +60,14 @@ func (parser TerraformStateJsonParser) parseResources(resources []*tfjson.StateR } func (parser TerraformStateJsonParser) computeResourceAddressIncludingModule(moduleAddress string, resource *tfjson.StateResource) string { + resourceAddress := parser.computeResourceAddress(resource) if len(moduleAddress) == 0 { - return parser.computeResourceAddress(resource) + return resourceAddress } - return fmt.Sprintf("%s.%s", moduleAddress, parser.computeResourceAddress(resource)) + if strings.HasPrefix(resourceAddress, moduleAddress) { + return resourceAddress + } + return fmt.Sprintf("%s.%s", moduleAddress, resourceAddress) } func (parser TerraformStateJsonParser) computeResourceAddress(resource *tfjson.StateResource) string { diff --git a/pkg/internal/parser/json_parser_test.go b/pkg/internal/parser/json_parser_test.go index 417929b..557811f 100644 --- a/pkg/internal/parser/json_parser_test.go +++ b/pkg/internal/parser/json_parser_test.go @@ -156,6 +156,54 @@ func TestTerraformStateJsonParserAddressComputationForRootResources(t *testing.T } } +func TestTerraformStateJsonParserDoesNotAddModuleNameTwice(t *testing.T) { + tests := []struct { + name string + inputTerraformStateJson string + computedAddress string + }{ + { + name: "1 level repeated module address", + inputTerraformStateJson: ` + { + "format_version": "0.1", + "terraform_version": "0.12.31", + "values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.test_mwaa.aws_iam_policy.test_mwaa_permissions", + "mode": "managed", + "type": "aws_iam_policy", + "name": "test_mwaa_permissions", + "provider_name": "aws", + "values": { + "id": "id_test_mwaa_permissions" + } + } + ], + "address": "module.test_mwaa" + } + ] + } + } + } +`, + computedAddress: "module.test_mwaa.aws_iam_policy.test_mwaa_permissions", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + parser := NewTerraformStateJsonParser(bytes.NewBufferString(tt.inputTerraformStateJson)) + actualResources, err := parser.Parse() + require.NoError(t, err) + require.Equal(t, tt.computedAddress, actualResources[0].Address) + }) + } +} + func TestTerraformStateJsonParserAddressComputationForNestedResources(t *testing.T) { tests := []struct { name string