From 4eb2eb6de83ac75a9265bc67a8ebc2fdb87235ef Mon Sep 17 00:00:00 2001 From: Christian Lechner <22294087+lechnerc77@users.noreply.github.com.> Date: Thu, 19 Nov 2026 16:38:27 +0100 Subject: [PATCH] feat: add clean up of environment instance parameters --- docs/tfcodeimprovements.md | 21 ++++ docs/troubleshooting.md | 2 + ...baccount_environment_instance_processor.go | 73 +++++++++++ ...unt_environment_instance_processor_test.go | 118 ++++++++++++++++++ .../resource_processor/resource_processor.go | 5 +- 5 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor.go create mode 100644 pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor_test.go diff --git a/docs/tfcodeimprovements.md b/docs/tfcodeimprovements.md index c601a1a..036ae12 100644 --- a/docs/tfcodeimprovements.md +++ b/docs/tfcodeimprovements.md @@ -44,6 +44,27 @@ The Terraform configuration on subaccount level gets improved via the following - If a resource `btp_subaccount_trust_configuration` gets exported that is the SAP default trust, the corresponding resource is removed from the resource configuration as well as the import block from the corresponding import file. - If a resource `btp_subaccount_role_collection` as well as `btp_subaccount_role` a check if there are dependencies is executed. If there are any a corresponding `depends_on` block is added to the resource `btp_subaccount_role_collection`. +### Cloud Foundry environment instances + +For `btp_subaccount_environment_instance` resources with `environment_type = "cloudfoundry"`, post-processing removes the top-level `status` entry from the object passed to `jsonencode` in `parameters`, regardless of its value. If this leaves the object empty, the entire `parameters` attribute is removed. Other parameters, including nested `status` entries, are preserved. This refinement applies only to Cloud Foundry environment instances. + +For example, these exported parameters: + +```hcl +parameters = jsonencode({ + instance_name = "cf-instance" + status = "ACTIVE" +}) +``` + +become: + +```hcl +parameters = jsonencode({ + instance_name = "cf-instance" +}) +``` + ### Role collection assignments For `btp_subaccount_role_collection_assignment`, post-processing removes `null` attributes for unused assignment types. User assignments retain `user_name`; group assignments retain `group_name`; attribute assignments retain `attribute_name` and `attribute_value`. Populated values, including the string `"null"`, are preserved. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 579e165..2de5884 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -13,6 +13,8 @@ Version 2 requires Terraform CLI 1.14 or newer. Check that the `terraform` binar The Terraform Provider for SAP BTP tries to optimize the generated code to make it more readable and maintainable. This includes several actions like removing empty values and introducing implicit and explicit dependencies between resources. +For Cloud Foundry environment instances, post-processing also removes the top-level `status` parameter regardless of its value and removes the `parameters` attribute if it becomes empty. See [Cloud Foundry environment instances](tfcodeimprovements.md#cloud-foundry-environment-instances) for an example. + If the generated code looks different than expected you can switch off this feature by setting the environment variable `BTPTF_SKIP_CODECLEANUP` to a non-empty value: === "Windows" diff --git a/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor.go b/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor.go new file mode 100644 index 0000000..c7d6a6c --- /dev/null +++ b/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor.go @@ -0,0 +1,73 @@ +package resourceprocessor + +import ( + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclsyntax" + "github.com/hashicorp/hcl/v2/hclwrite" + "github.com/zclconf/go-cty/cty" +) + +// Cloud Foundry exports include runtime status in the provisioning parameters. +func processEnvironmentInstanceParameters(body *hclwrite.Body) { + environmentType, ok := literalStringAttribute(body, "environment_type") + if !ok || environmentType != "cloudfoundry" { + return + } + parameters := body.GetAttribute("parameters") + if parameters == nil { + return + } + tokens := parameters.Expr().BuildTokens(nil) + expression, diagnostics := hclsyntax.ParseExpression(tokens.Bytes(), "", hcl.InitialPos) + if diagnostics.HasErrors() { + return + } + call, ok := expression.(*hclsyntax.FunctionCallExpr) + if !ok || call.Name != "jsonencode" || len(call.Args) != 1 { + return + } + object, ok := call.Args[0].(*hclsyntax.ObjectConsExpr) + if !ok { + return + } + + attributes := make([]hclwrite.ObjectAttrTokens, 0, len(object.Items)) + removed := false + for _, item := range object.Items { + key, diagnostics := item.KeyExpr.Value(nil) + if !diagnostics.HasErrors() && key.IsKnown() && !key.IsNull() && key.Type() == cty.String && key.AsString() == "status" { + removed = true + continue + } + // Keep expressions intact: other parameters may contain references or + // nested objects with their own status fields. + attributes = append(attributes, hclwrite.ObjectAttrTokens{ + Name: environmentParameterTokens(tokens, item.KeyExpr.Range()), + Value: environmentParameterTokens(tokens, item.ValueExpr.Range()), + }) + } + if !removed { + return + } + if len(attributes) == 0 { + body.RemoveAttribute("parameters") + return + } + body.SetAttributeRaw("parameters", hclwrite.TokensForFunctionCall("jsonencode", hclwrite.TokensForObject(attributes))) +} + +// Expression ranges refer to the bytes emitted by tokens.Bytes(), including +// each token's leading spaces. Select the original tokens to preserve values. +func environmentParameterTokens(tokens hclwrite.Tokens, expressionRange hcl.Range) hclwrite.Tokens { + var selected hclwrite.Tokens + offset := 0 + for _, token := range tokens { + offset += token.SpacesBefore + end := offset + len(token.Bytes) + if offset >= expressionRange.Start.Byte && end <= expressionRange.End.Byte { + selected = append(selected, token) + } + offset = end + } + return selected +} diff --git a/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor_test.go b/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor_test.go new file mode 100644 index 0000000..23911ff --- /dev/null +++ b/pkg/tfcleanup/resource_processor/btp_subaccount_environment_instance_processor_test.go @@ -0,0 +1,118 @@ +package resourceprocessor + +import ( + "fmt" + "testing" + + generictools "github.com/SAP/terraform-exporter-btp/pkg/tfcleanup/generic_tools" + "github.com/SAP/terraform-exporter-btp/pkg/tfutils" + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclwrite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEnvironmentInstancePostProcessing(t *testing.T) { + tests := []struct { + name string + environment string + blockType string + resource string + parameters string + want string + }{ + { + name: "exported Cloud Foundry instance", + parameters: `jsonencode({ + instance_name = "dev-inttest-exporter-8b2967c9-c3f3-68a4-4604-16702098e1d1" + status = "ACTIVE" +})`, + want: `jsonencode({ + instance_name = "dev-inttest-exporter-8b2967c9-c3f3-68a4-4604-16702098e1d1" +})`, + }, + {name: "inactive status", parameters: `jsonencode({ status = "INACTIVE", instance_name = "cf" })`, want: `jsonencode({ + instance_name = "cf" +})`}, + {name: "null status only", parameters: `jsonencode({ status = null })`}, + {name: "referenced status only", parameters: `jsonencode({ status = var.status })`}, + {name: "object status only", parameters: `jsonencode({ status = { value = "ACTIVE" } })`}, + {name: "quoted status key", parameters: `jsonencode({ "status" = "ACTIVE", "instance_name" = "cf" })`, want: `jsonencode({ + "instance_name" = "cf" +})`}, + { + name: "preserve nested objects and expressions", + parameters: `jsonencode({ + status = "ACTIVE" + instance_name = var.instance_name + metadata = { status = "keep", tags = ["Grüße", "ACTIVE"] } + message = "hello ${var.name}" + enabled = true + count = 2 +})`, + want: `jsonencode({ + instance_name = var.instance_name + metadata = { status = "keep", tags = ["Grüße", "ACTIVE"] } + message = "hello ${var.name}" + enabled = true + count = 2 +})`, + }, + {name: "missing status", parameters: `jsonencode({ instance_name = "cf" })`, want: `jsonencode({ instance_name = "cf" })`}, + {name: "empty parameters", parameters: `jsonencode({})`}, + {name: "missing parameters"}, + {name: "other environment", environment: `"kyma"`, parameters: `jsonencode({ status = "ACTIVE" })`, want: `jsonencode({ status = "ACTIVE" })`}, + {name: "missing environment type", environment: "omit", parameters: `jsonencode({ status = "ACTIVE" })`, want: `jsonencode({ status = "ACTIVE" })`}, + {name: "unknown environment type", environment: "var.environment_type", parameters: `jsonencode({ status = "ACTIVE" })`, want: `jsonencode({ status = "ACTIVE" })`}, + {name: "other resource", resource: "btp_subaccount_service_binding", parameters: `jsonencode({ status = "ACTIVE" })`, want: `jsonencode({ status = "ACTIVE" })`}, + {name: "data source", blockType: "data", parameters: `jsonencode({ status = "ACTIVE" })`, want: `jsonencode({ status = "ACTIVE" })`}, + {name: "referenced parameters", parameters: "var.parameters", want: "var.parameters"}, + {name: "computed parameters", parameters: `jsonencode(var.parameters)`, want: `jsonencode(var.parameters)`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + environment := tt.environment + if environment == "" { + environment = `"cloudfoundry"` + } + blockType := tt.blockType + if blockType == "" { + blockType = "resource" + } + resource := tt.resource + if resource == "" { + resource = tfutils.SubaccountEnvironmentInstanceType + } + config := func(parameters, subaccount string) string { + source := fmt.Sprintf(`%s "%s" "instance" { + provider = btp + name = "cf-instance" + landscape_label = "cf-us10" + plan_name = "standard" + service_name = "cloudfoundry" + subaccount_id = %s +`, blockType, resource, subaccount) + if environment != "omit" { + source += " environment_type = " + environment + "\n" + } + if parameters != "" { + source += " parameters = " + parameters + "\n" + } + return source + "}\n" + } + file, diagnostics := hclwrite.ParseConfig([]byte(config(tt.parameters, `"sa"`)), "test.tf", hcl.InitialPos) + require.False(t, diagnostics.HasErrors(), diagnostics.Error()) + variables := generictools.VariableContent{} + dependencies := generictools.NewDependencyAddresses() + dependencies.SubaccountAddress = "btp_subaccount.export_0" + ProcessResources(file, tfutils.SubaccountLevel, &variables, &dependencies, nil, generictools.LevelIds{SubaccountId: "sa"}) + want := hclwrite.Format([]byte(config(tt.want, "btp_subaccount.export_0.id"))) + assert.Equal(t, string(want), string(file.Bytes())) + _, diagnostics = hclwrite.ParseConfig(file.Bytes(), "result.tf", hcl.InitialPos) + require.False(t, diagnostics.HasErrors(), diagnostics.Error()) + before := string(file.Bytes()) + ProcessResources(file, tfutils.SubaccountLevel, &variables, &dependencies, nil, generictools.LevelIds{SubaccountId: "sa"}) + assert.Equal(t, before, string(file.Bytes()), "cleanup must be idempotent") + }) + } +} diff --git a/pkg/tfcleanup/resource_processor/resource_processor.go b/pkg/tfcleanup/resource_processor/resource_processor.go index a8f2bec..741432b 100644 --- a/pkg/tfcleanup/resource_processor/resource_processor.go +++ b/pkg/tfcleanup/resource_processor/resource_processor.go @@ -20,10 +20,13 @@ func processResourceAttributes(body *hclwrite.Body, inBlocks []string, level str generictools.RemoveEmptyAttributes(body) - _, blockIdentifier, resourceAddress := generictools.ExtractBlockInformation(inBlocks) + blockType, blockIdentifier, resourceAddress := generictools.ExtractBlockInformation(inBlocks) switch level { case tfutils.SubaccountLevel: + if blockType == "resource" && blockIdentifier == tfutils.SubaccountEnvironmentInstanceType { + processEnvironmentInstanceParameters(body) + } processSubaccountLevel(body, variables, dependencyAddresses, blockIdentifier, resourceAddress, btpClient, levelIds) case tfutils.DirectoryLevel: processDirectoryLevel(body, variables, dependencyAddresses, blockIdentifier, resourceAddress, btpClient, levelIds.DirectoryId)