Skip to content

Commit

Permalink
Merge pull request #26 from kishaningithub/handle-duplicated-module-a…
Browse files Browse the repository at this point in the history
…ddress

Handle duplicated module address in state json to support very old terraform versions
  • Loading branch information
kishaningithub authored May 21, 2024
2 parents f716494 + 05ac302 commit c256da4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pkg/internal/parser/json_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
48 changes: 48 additions & 0 deletions pkg/internal/parser/json_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c256da4

Please sign in to comment.