diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1d38b641..cc4184b8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,9 +37,10 @@ jobs: passphrase: ${{ secrets.PASSPHRASE }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v5.1.0 + uses: goreleaser/goreleaser-action@v6 with: - version: latest + distribution: goreleaser + version: '~> v2' args: release --clean # Changed --rm-dist to --clean as per the deprecation notice env: GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }} diff --git a/.goreleaser.yml b/.goreleaser.yml index 0ddfa1d2..690d5340 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,5 +1,7 @@ # Visit https://goreleaser.com for documentation on how to customize this # behavior. +version: 2 + before: hooks: # this is just an example and not a requirement for provider building/publishing @@ -59,5 +61,3 @@ release: # owner: zscaler # name: terraform-provider-zpa draft: true -changelog: - skip: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ee68e5c..91827d22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 3.3.24 (June, 14 2024) + +### Notes + +- Release date: **(June, 14 2024)** +- Supported Terraform version: **v1.x** + +### Internal Changes +- [PR #464](https://github.com/zscaler/terraform-provider-zpa/pull/464) Upgraded to [Zscaler-SDK-GO](https://github.com/zscaler/zscaler-sdk-go/releases/tag/v2.61.0). The upgrade supports easier ZPA API Client instantiation for existing and new resources. +- [PR #464](https://github.com/zscaler/terraform-provider-zpa/pull/464) Upgraded ``releaser.yml`` to [GoReleaser v6](https://github.com/goreleaser/goreleaser-action/releases/tag/v6.0.0) + + ## 3.3.23 (May, 31 2024) ### Notes diff --git a/GNUmakefile b/GNUmakefile index e944e15e..adf645e9 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -54,14 +54,14 @@ test\:integration\:zpa: build13: GOOS=$(shell go env GOOS) build13: GOARCH=$(shell go env GOARCH) ifeq ($(OS),Windows_NT) # is Windows_NT on XP, 2000, 7, Vista, 10... -build13: DESTINATION=$(APPDATA)/terraform.d/plugins/$(ZPA_PROVIDER_NAMESPACE)/3.3.1/$(GOOS)_$(GOARCH) +build13: DESTINATION=$(APPDATA)/terraform.d/plugins/$(ZPA_PROVIDER_NAMESPACE)/3.31.0/$(GOOS)_$(GOARCH) else -build13: DESTINATION=$(HOME)/.terraform.d/plugins/$(ZPA_PROVIDER_NAMESPACE)/3.3.1/$(GOOS)_$(GOARCH) +build13: DESTINATION=$(HOME)/.terraform.d/plugins/$(ZPA_PROVIDER_NAMESPACE)/3.31.0/$(GOOS)_$(GOARCH) endif build13: fmtcheck @echo "==> Installing plugin to $(DESTINATION)" @mkdir -p $(DESTINATION) - go build -o $(DESTINATION)/terraform-provider-zpa_v3.3.1 + go build -o $(DESTINATION)/terraform-provider-zpa_v3.31.0 vet: @echo "==> Checking source code against go vet and staticcheck" @@ -101,7 +101,7 @@ lint: @$(TFPROVIDERLINT) \ -c 1 \ -AT001 \ - -R004 \ + -R004 \ -S001 \ -S002 \ -S003 \ @@ -144,4 +144,6 @@ ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO))) git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO) endif @$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider-test PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME) -.PHONY: build test testacc vet fmt fmtcheck errcheck tools vendor-status test-compile website-lint website website-test \ No newline at end of file + +.PHONY: build test testacc vet fmt fmtcheck errcheck tools vendor-status test-compile website-lint website website-test + diff --git a/docs/guides/release-notes.md b/docs/guides/release-notes.md index bb452384..ad8ce52e 100644 --- a/docs/guides/release-notes.md +++ b/docs/guides/release-notes.md @@ -12,10 +12,21 @@ Track all ZPA Terraform provider's releases. New resources, features, and bug fi --- -``Last updated: v3.3.23`` +``Last updated: v3.3.24`` --- +## 3.3.24 (June, 14 2024) + +### Notes + +- Release date: **(June, 14 2024)** +- Supported Terraform version: **v1.x** + +### Internal Changes +- [PR #464](https://github.com/zscaler/terraform-provider-zpa/pull/464) Upgraded to [Zscaler-SDK-GO](https://github.com/zscaler/zscaler-sdk-go/releases/tag/v2.61.0). The upgrade supports easier ZPA API Client instantiation for existing and new resources. +- [PR #464](https://github.com/zscaler/terraform-provider-zpa/pull/464) Upgraded ``releaser.yml`` to [GoReleaser v6](https://github.com/goreleaser/goreleaser-action/releases/tag/v6.0.0) + ## 3.3.23 (May, 31 2024) ### Notes diff --git a/go.mod b/go.mod index 9e8d5acb..949de2fa 100644 --- a/go.mod +++ b/go.mod @@ -10,10 +10,10 @@ require ( github.com/fabiotavarespr/iso3166 v0.0.2 github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 github.com/hashicorp/go-hclog v1.6.3 - github.com/hashicorp/terraform-plugin-docs v0.19.3 + github.com/hashicorp/terraform-plugin-docs v0.19.4 github.com/hashicorp/terraform-plugin-sdk v1.17.2 github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 - github.com/zscaler/zscaler-sdk-go/v2 v2.5.23 + github.com/zscaler/zscaler-sdk-go/v2 v2.61.1 ) require ( @@ -83,8 +83,8 @@ require ( golang.org/x/net v0.25.0 // indirect golang.org/x/sync v0.7.0 // indirect golang.org/x/sys v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect - golang.org/x/tools v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect + golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect google.golang.org/grpc v1.63.2 // indirect diff --git a/go.sum b/go.sum index a75e71e5..6f32e622 100644 --- a/go.sum +++ b/go.sum @@ -260,8 +260,8 @@ github.com/hashicorp/terraform-exec v0.21.0/go.mod h1:1PPeMYou+KDUSSeRE9szMZ/oHf github.com/hashicorp/terraform-json v0.10.0/go.mod h1:3defM4kkMfttwiE7VakJDwCd4R+umhSQnvJwORXbprE= github.com/hashicorp/terraform-json v0.22.1 h1:xft84GZR0QzjPVWs4lRUwvTcPnegqlyS7orfb5Ltvec= github.com/hashicorp/terraform-json v0.22.1/go.mod h1:JbWSQCLFSXFFhg42T7l9iJwdGXBYV8fmmD6o/ML4p3A= -github.com/hashicorp/terraform-plugin-docs v0.19.3 h1:xoxpeIuBfnoGxXY0dTajdj4GjEv6TihZdj0lHNXbKew= -github.com/hashicorp/terraform-plugin-docs v0.19.3/go.mod h1:4pLASsatTmRynVzsjEhbXZ6s7xBlUw/2Kt0zfrq8HxA= +github.com/hashicorp/terraform-plugin-docs v0.19.4 h1:G3Bgo7J22OMtegIgn8Cd/CaSeyEljqjH3G39w28JK4c= +github.com/hashicorp/terraform-plugin-docs v0.19.4/go.mod h1:4pLASsatTmRynVzsjEhbXZ6s7xBlUw/2Kt0zfrq8HxA= github.com/hashicorp/terraform-plugin-go v0.23.0 h1:AALVuU1gD1kPb48aPQUjug9Ir/125t+AAurhqphJ2Co= github.com/hashicorp/terraform-plugin-go v0.23.0/go.mod h1:1E3Cr9h2vMlahWMbsSEcNrOCxovCZhOOIXjFHbjc/lQ= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= @@ -441,8 +441,8 @@ github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgr github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b h1:FosyBZYxY34Wul7O/MSKey3txpPYyCqVO5ZyceuQJEI= github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= github.com/zclconf/go-cty-yaml v1.0.2/go.mod h1:IP3Ylp0wQpYm50IHK8OZWKMu6sPJIUgKa8XhiVHura0= -github.com/zscaler/zscaler-sdk-go/v2 v2.5.23 h1:34J7i52kVtQzrvpokFzYpNsgjKTQ7H8B0XzLDYXUQog= -github.com/zscaler/zscaler-sdk-go/v2 v2.5.23/go.mod h1:UgwsquQFF3nSn4mJGbbJRweh5Jpiwqkw+4mIxm14Eso= +github.com/zscaler/zscaler-sdk-go/v2 v2.61.1 h1:NB7jbUWKvaMSjWnqjSzJLeApu20QpsRl/BnesO6u86g= +github.com/zscaler/zscaler-sdk-go/v2 v2.61.1/go.mod h1:lbdgIlORFfkAGvju4szC7SLxpLddJJKvZ6brfOECIL4= go.abhg.dev/goldmark/frontmatter v0.2.0 h1:P8kPG0YkL12+aYk2yU3xHv4tcXzeVnN+gU0tJ5JnxRw= go.abhg.dev/goldmark/frontmatter v0.2.0/go.mod h1:XqrEkZuM57djk7zrlRUB02x8I5J0px76YjkOzhB4YlU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -613,8 +613,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -662,8 +662,8 @@ golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20201028111035-eafbe7b904eb/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.21.0 h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw= -golang.org/x/tools v0.21.0/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/zpa/common.go b/zpa/common.go index 5c4a6068..79f98fe3 100644 --- a/zpa/common.go +++ b/zpa/common.go @@ -11,9 +11,19 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudconnectorgroup" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/idpcontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/machinegroup" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/platforms" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/postureprofile" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/samlattribute" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/scimattributeheader" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/trustednetwork" ) var ( @@ -66,23 +76,23 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr switch operand.ObjectType { case "APP": return customValidate(operand, []string{"id"}, "application segment ID", Getter(func(id string) error { - _, _, err := zClient.applicationsegment.WithMicroTenant(microtenantID).Get(id) + _, _, err := applicationsegment.Get(zClient.ApplicationSegment.WithMicroTenant(microtenantID), id) return err })) case "APP_GROUP": return customValidate(operand, []string{"id"}, "Segment Group ID", Getter(func(id string) error { - _, _, err := zClient.segmentgroup.WithMicroTenant(microtenantID).Get(id) + _, _, err := segmentgroup.Get(zClient.SegmentGroup.WithMicroTenant(microtenantID), id) return err })) case "IDP": return customValidate(operand, []string{"id"}, "IDP ID", Getter(func(id string) error { - _, _, err := zClient.idpcontroller.Get(id) + _, _, err := idpcontroller.Get(zClient.IDPController, id) return err })) case "EDGE_CONNECTOR_GROUP": return customValidate(operand, []string{"id"}, "cloud connector group ID", Getter(func(id string) error { - _, _, err := zClient.cloudconnectorgroup.Get(id) + _, _, err := cloudconnectorgroup.Get(zClient.CloudConnectorGroup, id) return err })) case "CLIENT_TYPE": @@ -94,14 +104,14 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr })) case "MACHINE_GRP": return customValidate(operand, []string{"id"}, "machine group ID", Getter(func(id string) error { - _, _, err := zClient.machinegroup.WithMicroTenant(microtenantID).Get(id) + _, _, err := machinegroup.Get(zClient.MachineGroup.WithMicroTenant(microtenantID), id) return err })) case "POSTURE": if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid posture network ID", operand.LHS, nil) } - _, _, err := zClient.postureprofile.GetByPostureUDID(operand.LHS) + _, _, err := postureprofile.GetByPostureUDID(zClient.PostureProfile, operand.LHS) if err != nil { return lhsWarn(operand.ObjectType, "valid posture network ID", operand.LHS, err) } @@ -113,7 +123,7 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid trusted network ID", operand.LHS, nil) } - _, _, err := zClient.trustednetwork.GetByNetID(operand.LHS) + _, _, err := trustednetwork.GetByNetID(zClient.TrustedNetwork, operand.LHS) if err != nil { return lhsWarn(operand.ObjectType, "valid trusted network ID", operand.LHS, err) } @@ -125,7 +135,7 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid platform ID", operand.LHS, nil) } - _, _, err := zClient.platforms.GetAllPlatforms() + _, _, err := platforms.GetAllPlatforms(zClient.Platforms) if err != nil { return lhsWarn(operand.ObjectType, "valid platform ID", operand.LHS, err) } @@ -137,7 +147,7 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid SAML Attribute ID", operand.LHS, nil) } - _, _, err := zClient.samlattribute.Get(operand.LHS) + _, _, err := samlattribute.Get(zClient.SAMLAttribute, operand.LHS) if err != nil { return lhsWarn(operand.ObjectType, "valid SAML Attribute ID", operand.LHS, err) } @@ -152,14 +162,14 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid SCIM Attribute ID", operand.LHS, nil) } - scim, _, err := zClient.scimattributeheader.Get(operand.IdpID, operand.LHS) + scim, _, err := scimattributeheader.Get(zClient.ScimAttributeHeader, operand.IdpID, operand.LHS) if err != nil { return lhsWarn(operand.ObjectType, "valid SCIM Attribute ID", operand.LHS, err) } if operand.RHS == "" { return rhsWarn(operand.ObjectType, "SCIM Attribute Value", operand.RHS, nil) } - values, _ := zClient.scimattributeheader.SearchValues(scim.IdpID, scim.ID, operand.RHS) + values, _ := scimattributeheader.SearchValues(zClient.ScimAttributeHeader, scim.IdpID, scim.ID, operand.RHS) if len(values) == 0 { return rhsWarn(operand.ObjectType, fmt.Sprintf("valid SCIM Attribute Value (%s)", values), operand.RHS, nil) } @@ -168,14 +178,14 @@ func validateOperand(operand policysetcontroller.Operands, zClient *Client, micr if operand.LHS == "" { return lhsWarn(operand.ObjectType, "valid IDP Controller ID", operand.LHS, nil) } - _, _, err := zClient.idpcontroller.Get(operand.LHS) + _, _, err := idpcontroller.Get(zClient.IDPController, operand.LHS) if err != nil { return lhsWarn(operand.ObjectType, "valid IDP Controller ID", operand.LHS, err) } if operand.RHS == "" { return rhsWarn(operand.ObjectType, "SCIM Group ID", operand.RHS, nil) } - _, _, err = zClient.scimgroup.Get(operand.RHS) + _, _, err = zClient.ScimGroup.Get(operand.RHS) if err != nil { return rhsWarn(operand.ObjectType, "SCIM Group ID", operand.RHS, err) } @@ -588,9 +598,39 @@ func resourceAppSegmentPortRange(desc string) *schema.Schema { } } +/* + func importPolicyStateContextFunc(types []string) schema.StateContextFunc { + return func(_ context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + + id := d.Id() + _, parseIDErr := strconv.ParseInt(id, 10, 64) + if parseIDErr == nil { + // assume if the passed value is an int + _ = d.Set("id", id) + } else { + resp, _, err := service.GetByNameAndTypes(types, id) + if err == nil { + d.SetId(resp.ID) + _ = d.Set("id", resp.ID) + } else { + return []*schema.ResourceData{d}, err + } + + } + return []*schema.ResourceData{d}, nil + } + } +*/ func importPolicyStateContextFunc(types []string) schema.StateContextFunc { return func(_ context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -598,22 +638,51 @@ func importPolicyStateContextFunc(types []string) schema.StateContextFunc { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByNameAndTypes(types, id) + resp, _, err := policysetcontroller.GetByNameAndTypes(service, types, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) } else { return []*schema.ResourceData{d}, err } - } return []*schema.ResourceData{d}, nil } } +/* + func importPolicyStateContextFuncV2(types []string) schema.StateContextFunc { + return func(_ context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + service := m.(*Client).policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + + id := d.Id() + _, parseIDErr := strconv.ParseInt(id, 10, 64) + if parseIDErr == nil { + // assume if the passed value is an int + _ = d.Set("id", id) + } else { + resp, _, err := service.GetByNameAndTypes(types, id) + if err == nil { + d.SetId(resp.ID) + _ = d.Set("id", resp.ID) + } else { + return []*schema.ResourceData{d}, err + } + + } + return []*schema.ResourceData{d}, nil + } + } +*/ func importPolicyStateContextFuncV2(types []string) schema.StateContextFunc { return func(_ context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -621,14 +690,13 @@ func importPolicyStateContextFuncV2(types []string) schema.StateContextFunc { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByNameAndTypes(types, id) + resp, _, err := policysetcontrollerv2.GetByNameAndTypes(service, types, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) } else { return []*schema.ResourceData{d}, err } - } return []*schema.ResourceData{d}, nil } @@ -711,9 +779,11 @@ var AllowedPolicyTypes = map[string]struct{}{ "CREDENTIAL_POLICY": {}, "CAPABILITIES_POLICY": {}, "CLIENTLESS_SESSION_PROTECTION_POLICY": {}, + "REDIRECTION_POLICY": {}, } -func GetGlobalPolicySetByPolicyType(policysetcontroller policysetcontroller.Service, policyType string) (*policysetcontroller.PolicySet, error) { +/* +func GetGlobalPolicySetByPolicyType(policysetcontroller services.Service, policyType string) (*policysetcontroller.PolicySet, error) { // Check if the provided policy type is allowed if _, ok := AllowedPolicyTypes[policyType]; !ok { return nil, fmt.Errorf("invalid policy type: %s", policyType) @@ -732,6 +802,29 @@ func GetGlobalPolicySetByPolicyType(policysetcontroller policysetcontroller.Serv policySets[policyType] = *globalPolicySet return globalPolicySet, nil } +*/ + +func GetGlobalPolicySetByPolicyType(client *Client, policyType string) (*policysetcontroller.PolicySet, error) { + // Check if the provided policy type is allowed + if _, ok := AllowedPolicyTypes[policyType]; !ok { + return nil, fmt.Errorf("invalid policy type: %s", policyType) + } + + policySetsMutex.Lock() + defer policySetsMutex.Unlock() + + if p, ok := policySets[policyType]; ok { + return &p, nil + } + + service := client.PolicySetController + globalPolicySet, _, err := policysetcontroller.GetByPolicyType(service, policyType) + if err != nil { + return nil, err + } + policySets[policyType] = *globalPolicySet + return globalPolicySet, nil +} //###################################################################################################################### //######################################## ZPA ACCESS POLICY V2 COMMON CONDITIONS FUNCTIONS ######################################## @@ -1080,6 +1173,7 @@ func ValidatePolicyRuleConditions(d *schema.ResourceData) error { return nil } +/* func fetchPolicySetIDByType(client *Client, policyType string, microTenantID string) (string, error) { service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) globalPolicySet, _, err := service.GetByPolicyType(policyType) @@ -1088,3 +1182,73 @@ func fetchPolicySetIDByType(client *Client, policyType string, microTenantID str } return globalPolicySet.ID, nil } +*/ + +func fetchPolicySetIDByType(client *Client, policyType string, microTenantID string) (string, error) { + service := client.PolicySetControllerV2 + + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + globalPolicySet, _, err := policysetcontroller.GetByPolicyType(service, policyType) + if err != nil { + return "", fmt.Errorf("failed to fetch policy set ID for type '%s': %v", policyType, err) + } + return globalPolicySet.ID, nil +} + +// ConvertV1ResponseToV2Request converts a PolicyRuleResource (API v1 response) to a PolicyRule (API v2 request) with aggregated values. +func ConvertV1ResponseToV2Request(v1Response policysetcontrollerv2.PolicyRuleResource) policysetcontrollerv2.PolicyRule { + v2Request := policysetcontrollerv2.PolicyRule{ + ID: v1Response.ID, + Name: v1Response.Name, + Description: v1Response.Description, + Action: v1Response.Action, + PolicySetID: v1Response.PolicySetID, + Operator: v1Response.Operator, + CustomMsg: v1Response.CustomMsg, + ZpnIsolationProfileID: v1Response.ZpnIsolationProfileID, + Conditions: make([]policysetcontrollerv2.PolicyRuleResourceConditions, 0), + } + + for _, condition := range v1Response.Conditions { + newCondition := policysetcontrollerv2.PolicyRuleResourceConditions{ + Operator: condition.Operator, + Operands: make([]policysetcontrollerv2.PolicyRuleResourceOperands, 0), + } + + // Use a map to aggregate RHS values by ObjectType + operandMap := make(map[string][]string) + entryValuesMap := make(map[string][]policysetcontrollerv2.OperandsResourceLHSRHSValue) + + for _, operand := range condition.Operands { + switch operand.ObjectType { + case "APP", "APP_GROUP", "CONSOLE", "MACHINE_GRP", "LOCATION", "BRANCH_CONNECTOR_GROUP", "EDGE_CONNECTOR_GROUP", "CLIENT_TYPE": + operandMap[operand.ObjectType] = append(operandMap[operand.ObjectType], operand.RHS) + case "PLATFORM", "POSTURE", "TRUSTED_NETWORK", "SAML", "SCIM", "SCIM_GROUP", "COUNTRY_CODE": + entryValuesMap[operand.ObjectType] = append(entryValuesMap[operand.ObjectType], policysetcontrollerv2.OperandsResourceLHSRHSValue{ + LHS: operand.LHS, + RHS: operand.RHS, + }) + } + } + + // Create operand blocks from the aggregated data + for objectType, values := range operandMap { + newCondition.Operands = append(newCondition.Operands, policysetcontrollerv2.PolicyRuleResourceOperands{ + ObjectType: objectType, + Values: values, + }) + } + + for objectType, entryValues := range entryValuesMap { + newCondition.Operands = append(newCondition.Operands, policysetcontrollerv2.PolicyRuleResourceOperands{ + ObjectType: objectType, + EntryValuesLHSRHS: entryValues, + }) + } + v2Request.Conditions = append(v2Request.Conditions, newCondition) + } + return v2Request +} diff --git a/zpa/config.go b/zpa/config.go index 293af719..99928391 100644 --- a/zpa/config.go +++ b/zpa/config.go @@ -4,50 +4,8 @@ import ( "log" gozscaler "github.com/zscaler/zscaler-sdk-go/v2/zpa" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorcontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorgroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentbytype" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentinspection" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentpra" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appservercontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/bacertificate" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/browseraccess" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/clienttypes" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbibannercontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbicertificatecontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbiprofilecontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbiregions" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbizpaprofile" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/isolationprofile" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudconnectorgroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/customerversionprofile" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/emergencyaccess" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/enrollmentcert" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/idpcontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/inspectioncontrol/inspection_custom_controls" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/inspectioncontrol/inspection_predefined_controls" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/inspectioncontrol/inspection_profile" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/lssconfigcontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/machinegroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/microtenants" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/platforms" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/postureprofile" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praapproval" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praconsole" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/pracredential" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praportal" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/provisioningkey" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/samlattribute" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/scimattributeheader" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/scimgroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/servergroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/serviceedgecontroller" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/serviceedgegroup" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/trustednetwork" ) func init() { @@ -56,67 +14,60 @@ func init() { } type Client struct { - appconnectorgroup appconnectorgroup.Service - appconnectorcontroller appconnectorcontroller.Service - applicationsegment applicationsegment.Service - applicationsegmentpra applicationsegmentpra.Service - applicationsegmentinspection applicationsegmentinspection.Service - applicationsegmentbytype applicationsegmentbytype.Service - appservercontroller appservercontroller.Service - bacertificate bacertificate.Service - browseraccess browseraccess.Service - cbiregions cbiregions.Service - cbiprofilecontroller cbiprofilecontroller.Service - cbizpaprofile cbizpaprofile.Service - cbicertificatecontroller cbicertificatecontroller.Service - cbibannercontroller cbibannercontroller.Service - cloudconnectorgroup cloudconnectorgroup.Service - customerversionprofile customerversionprofile.Service - clienttypes clienttypes.Service - emergencyaccess emergencyaccess.Service - enrollmentcert enrollmentcert.Service - idpcontroller idpcontroller.Service - inspection_custom_controls inspection_custom_controls.Service - inspection_predefined_controls inspection_predefined_controls.Service - inspection_profile inspection_profile.Service - isolationprofile isolationprofile.Service - lssconfigcontroller lssconfigcontroller.Service - machinegroup machinegroup.Service - microtenants microtenants.Service - platforms platforms.Service - policysetcontroller policysetcontroller.Service - policysetcontrollerv2 policysetcontrollerv2.Service - postureprofile postureprofile.Service - praapproval praapproval.Service - praconsole praconsole.Service - pracredential pracredential.Service - praportal praportal.Service - provisioningkey provisioningkey.Service - samlattribute samlattribute.Service - scimgroup scimgroup.Service - scimattributeheader scimattributeheader.Service - segmentgroup segmentgroup.Service - servergroup servergroup.Service - serviceedgegroup serviceedgegroup.Service - serviceedgecontroller serviceedgecontroller.Service - trustednetwork trustednetwork.Service + AppConnectorGroup *services.Service + AppConnectorController *services.Service + AppConnectorSchedule *services.Service + ApplicationSegment *services.Service + ApplicationSegmentPRA *services.Service + ApplicationSegmentInspection *services.Service + ApplicationSegmentByType *services.Service + AppServerController *services.Service + BACertificate *services.Service + BrowserAccess *services.Service + CBIRegions *services.Service + CBIProfileController *services.Service + CBIZpaProfile *services.Service + CBICertificateController *services.Service + CBIBannerController *services.Service + CloudConnectorGroup *services.Service + CustomerVersionProfile *services.Service + ClientTypes *services.Service + EmergencyAccess *services.Service + EnrollmentCert *services.Service + IDPController *services.Service + InspectionCustomControls *services.Service + InspectionPredefinedControls *services.Service + InspectionProfile *services.Service + IsolationProfile *services.Service + LSSConfigController *services.Service + MachineGroup *services.Service + MicroTenants *services.Service + Platforms *services.Service + PolicySetController *services.Service + PolicySetControllerV2 *services.Service + PostureProfile *services.Service + PRAApproval *services.Service + PRAConsole *services.Service + PRACredential *services.Service + PRAPortal *services.Service + ProvisioningKey *services.Service + SAMLAttribute *services.Service + ScimGroup *scimgroup.Service + ScimAttributeHeader *services.Service + SegmentGroup *services.Service + ServerGroup *services.Service + ServiceEdgeGroup *services.Service + ServiceEdgeSchedule *services.Service + ServiceEdgeController *services.Service + TrustedNetwork *services.Service } type Config struct { - // ZPA Client ID for API Client - ClientID string - - // ZPA Client Secret for API Client + ClientID string ClientSecret string - - // ZPA Customer ID for API Client - CustomerID string - - // ZPA Base URL for API Client - BaseURL string - - // UserAgent for API Client - UserAgent string + CustomerID string + BaseURL string + UserAgent string } func (c *Config) Client() (*Client, error) { @@ -125,51 +76,54 @@ func (c *Config) Client() (*Client, error) { return nil, err } zpaClient := gozscaler.NewClient(config) + client := &Client{ - appconnectorgroup: *appconnectorgroup.New(zpaClient), - appconnectorcontroller: *appconnectorcontroller.New(zpaClient), - applicationsegment: *applicationsegment.New(zpaClient), - applicationsegmentpra: *applicationsegmentpra.New(zpaClient), - applicationsegmentinspection: *applicationsegmentinspection.New(zpaClient), - applicationsegmentbytype: *applicationsegmentbytype.New(zpaClient), - appservercontroller: *appservercontroller.New(zpaClient), - bacertificate: *bacertificate.New(zpaClient), - browseraccess: *browseraccess.New(zpaClient), - cbiregions: *cbiregions.New(zpaClient), - cbiprofilecontroller: *cbiprofilecontroller.New(zpaClient), - cbicertificatecontroller: *cbicertificatecontroller.New(zpaClient), - cbibannercontroller: *cbibannercontroller.New(zpaClient), - cbizpaprofile: *cbizpaprofile.New(zpaClient), - clienttypes: *clienttypes.New(zpaClient), - cloudconnectorgroup: *cloudconnectorgroup.New(zpaClient), - customerversionprofile: *customerversionprofile.New(zpaClient), - emergencyaccess: *emergencyaccess.New(zpaClient), - enrollmentcert: *enrollmentcert.New(zpaClient), - idpcontroller: *idpcontroller.New(zpaClient), - inspection_custom_controls: *inspection_custom_controls.New(zpaClient), - inspection_predefined_controls: *inspection_predefined_controls.New(zpaClient), - inspection_profile: *inspection_profile.New(zpaClient), - isolationprofile: *isolationprofile.New(zpaClient), - lssconfigcontroller: *lssconfigcontroller.New(zpaClient), - machinegroup: *machinegroup.New(zpaClient), - microtenants: *microtenants.New(zpaClient), - platforms: *platforms.New(zpaClient), - policysetcontroller: *policysetcontroller.New(zpaClient), - policysetcontrollerv2: *policysetcontrollerv2.New(zpaClient), - postureprofile: *postureprofile.New(zpaClient), - praapproval: *praapproval.New(zpaClient), - praconsole: *praconsole.New(zpaClient), - pracredential: *pracredential.New(zpaClient), - praportal: *praportal.New(zpaClient), - provisioningkey: *provisioningkey.New(zpaClient), - samlattribute: *samlattribute.New(zpaClient), - scimgroup: *scimgroup.New(zpaClient), - scimattributeheader: *scimattributeheader.New(zpaClient), - segmentgroup: *segmentgroup.New(zpaClient), - servergroup: *servergroup.New(zpaClient), - serviceedgegroup: *serviceedgegroup.New(zpaClient), - serviceedgecontroller: *serviceedgecontroller.New(zpaClient), - trustednetwork: *trustednetwork.New(zpaClient), + AppConnectorGroup: services.New(zpaClient), + AppConnectorController: services.New(zpaClient), + AppConnectorSchedule: services.New(zpaClient), + ApplicationSegment: services.New(zpaClient), + ApplicationSegmentPRA: services.New(zpaClient), + ApplicationSegmentInspection: services.New(zpaClient), + ApplicationSegmentByType: services.New(zpaClient), + AppServerController: services.New(zpaClient), + BACertificate: services.New(zpaClient), + BrowserAccess: services.New(zpaClient), + CBIRegions: services.New(zpaClient), + CBIProfileController: services.New(zpaClient), + CBIZpaProfile: services.New(zpaClient), + CBICertificateController: services.New(zpaClient), + CBIBannerController: services.New(zpaClient), + CloudConnectorGroup: services.New(zpaClient), + CustomerVersionProfile: services.New(zpaClient), + ClientTypes: services.New(zpaClient), + EmergencyAccess: services.New(zpaClient), + EnrollmentCert: services.New(zpaClient), + IDPController: services.New(zpaClient), + InspectionCustomControls: services.New(zpaClient), + InspectionPredefinedControls: services.New(zpaClient), + InspectionProfile: services.New(zpaClient), + IsolationProfile: services.New(zpaClient), + LSSConfigController: services.New(zpaClient), + MachineGroup: services.New(zpaClient), + MicroTenants: services.New(zpaClient), + Platforms: services.New(zpaClient), + PolicySetController: services.New(zpaClient), // Correct initialization + PolicySetControllerV2: services.New(zpaClient), // Correct initialization + PostureProfile: services.New(zpaClient), + PRAApproval: services.New(zpaClient), + PRAConsole: services.New(zpaClient), + PRACredential: services.New(zpaClient), + PRAPortal: services.New(zpaClient), + ProvisioningKey: services.New(zpaClient), + SAMLAttribute: services.New(zpaClient), + ScimGroup: scimgroup.New(zpaClient), + ScimAttributeHeader: services.New(zpaClient), + SegmentGroup: services.New(zpaClient), + ServerGroup: services.New(zpaClient), + ServiceEdgeGroup: services.New(zpaClient), + ServiceEdgeSchedule: services.New(zpaClient), + ServiceEdgeController: services.New(zpaClient), + TrustedNetwork: services.New(zpaClient), } log.Println("[INFO] initialized ZPA client") diff --git a/zpa/data_source_zpa_access_policy_client_types.go b/zpa/data_source_zpa_access_policy_client_types.go index 2ee58609..ea87a9eb 100644 --- a/zpa/data_source_zpa_access_policy_client_types.go +++ b/zpa/data_source_zpa_access_policy_client_types.go @@ -4,6 +4,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/clienttypes" ) func dataSourceAccessPolicyClientTypes() *schema.Resource { @@ -54,9 +55,11 @@ func dataSourceAccessPolicyClientTypes() *schema.Resource { func dataSourceAccessPolicyClientTypesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ClientTypes + log.Printf("[INFO] Getting data for all client types set\n") - resp, _, err := zClient.clienttypes.GetAllClientTypes() + resp, _, err := clienttypes.GetAllClientTypes(service) if err != nil { return err } diff --git a/zpa/data_source_zpa_access_policy_platform.go b/zpa/data_source_zpa_access_policy_platform.go index 3cc62573..799c825b 100644 --- a/zpa/data_source_zpa_access_policy_platform.go +++ b/zpa/data_source_zpa_access_policy_platform.go @@ -4,6 +4,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/platforms" ) func dataSourceAccessPolicyPlatforms() *schema.Resource { @@ -38,9 +39,11 @@ func dataSourceAccessPolicyPlatforms() *schema.Resource { func dataSourceAccessPolicyPlatformsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.Platforms + log.Printf("[INFO] Getting data for all platforms set\n") - resp, _, err := zClient.platforms.GetAllPlatforms() + resp, _, err := platforms.GetAllPlatforms(service) if err != nil { return err } diff --git a/zpa/data_source_zpa_app_connector_assistant_schedule.go b/zpa/data_source_zpa_app_connector_assistant_schedule.go index 23d96dc9..307251c2 100644 --- a/zpa/data_source_zpa_app_connector_assistant_schedule.go +++ b/zpa/data_source_zpa_app_connector_assistant_schedule.go @@ -5,7 +5,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorcontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorschedule" ) func dataSourceAppConnectorAssistantSchedule() *schema.Resource { @@ -42,7 +42,9 @@ func dataSourceAppConnectorAssistantSchedule() *schema.Resource { func dataSourceAppConnectorAssistantScheduleRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) - var resp *appconnectorcontroller.AssistantSchedule + service := zClient.AppConnectorSchedule + + var resp *appconnectorschedule.AssistantSchedule var err error id, idOk := d.GetOk("id") @@ -50,19 +52,19 @@ func dataSourceAppConnectorAssistantScheduleRead(d *schema.ResourceData, m inter if idOk && id != "" { log.Printf("[INFO] Getting data for app connector assistant schedule %s\n", id) - resp, _, err = zClient.appconnectorcontroller.GetSchedule() + resp, _, err = appconnectorschedule.GetSchedule(service) if err != nil { return err } } else if customerIDOk && customerID != "" { log.Printf("[INFO] Getting data for app connector name %s\n", customerID) - resp, _, err = zClient.appconnectorcontroller.GetSchedule() + resp, _, err = appconnectorschedule.GetSchedule(service) if err != nil { return err } } else { log.Printf("[INFO] No specific ID or customer ID provided, fetching default schedule") - resp, _, err = zClient.appconnectorcontroller.GetSchedule() + resp, _, err = appconnectorschedule.GetSchedule(service) if err != nil { return err } diff --git a/zpa/data_source_zpa_app_connector_assistant_schedule_test.go b/zpa/data_source_zpa_app_connector_assistant_schedule_test.go index 135f9327..d30f705f 100644 --- a/zpa/data_source_zpa_app_connector_assistant_schedule_test.go +++ b/zpa/data_source_zpa_app_connector_assistant_schedule_test.go @@ -1,6 +1,5 @@ package zpa -/* import ( "testing" @@ -41,4 +40,4 @@ data "zpa_app_connector_assistant_schedule" "by_id" { data "zpa_app_connector_assistant_schedule" "customer_id" { customer_id = data.zpa_app_connector_assistant_schedule.this.customer_id } -`*/ +` diff --git a/zpa/data_source_zpa_app_connector_controller.go b/zpa/data_source_zpa_app_connector_controller.go index 70caabde..a787f97e 100644 --- a/zpa/data_source_zpa_app_connector_controller.go +++ b/zpa/data_source_zpa_app_connector_controller.go @@ -170,12 +170,19 @@ func dataSourceAppConnectorController() *schema.Resource { } func dataSourceAppConnectorControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appconnectorcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppConnectorController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var resp *appconnectorcontroller.AppConnector id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for app connector %s\n", id) - res, _, err := service.Get(id) + res, _, err := appconnectorcontroller.Get(service, id) if err != nil { return err } @@ -184,7 +191,7 @@ func dataSourceAppConnectorControllerRead(d *schema.ResourceData, m interface{}) name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for app connector name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := appconnectorcontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_app_connector_group.go b/zpa/data_source_zpa_app_connector_group.go index 7ab727c4..427959a7 100644 --- a/zpa/data_source_zpa_app_connector_group.go +++ b/zpa/data_source_zpa_app_connector_group.go @@ -325,13 +325,14 @@ func dataSourceAppConnectorGroup() *schema.Resource { } func dataSourceConnectorGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppConnectorGroup var resp *appconnectorgroup.AppConnectorGroup id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for app connector group %s\n", id) - res, _, err := service.Get(id) + res, _, err := appconnectorgroup.Get(service, id) if err != nil { return err } @@ -340,7 +341,7 @@ func dataSourceConnectorGroupRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for app connector group name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := appconnectorgroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_app_server_controller.go b/zpa/data_source_zpa_app_server_controller.go index f2229cca..9443939e 100644 --- a/zpa/data_source_zpa_app_server_controller.go +++ b/zpa/data_source_zpa_app_server_controller.go @@ -66,13 +66,19 @@ func dataSourceApplicationServer() *schema.Resource { } func dataSourceApplicationServerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppServerController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *appservercontroller.ApplicationServer id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for application server %s\n", id) - res, _, err := service.Get(id) + res, _, err := appservercontroller.Get(service, id) if err != nil { return err } @@ -81,7 +87,7 @@ func dataSourceApplicationServerRead(d *schema.ResourceData, m interface{}) erro name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for application server name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := appservercontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_application_segment.go b/zpa/data_source_zpa_application_segment.go index 00fcf2f5..1abf6c82 100644 --- a/zpa/data_source_zpa_application_segment.go +++ b/zpa/data_source_zpa_application_segment.go @@ -175,12 +175,19 @@ func dataSourceApplicationSegment() *schema.Resource { } func dataSourceApplicationSegmentRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegment + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var resp *applicationsegment.ApplicationSegmentResource id, ok := d.Get("id").(string) if ok && id != "" { - log.Printf("[INFO] Getting data for server group %s\n", id) - res, _, err := service.Get(id) + log.Printf("[INFO] Getting data for application segment %s\n", id) + res, _, err := applicationsegment.Get(service, id) if err != nil { return err } @@ -188,8 +195,8 @@ func dataSourceApplicationSegmentRead(d *schema.ResourceData, m interface{}) err } name, ok := d.Get("name").(string) if id == "" && ok && name != "" { - log.Printf("[INFO] Getting data for server group name %s\n", name) - res, _, err := service.GetByName(name) + log.Printf("[INFO] Getting data for application segment name %s\n", name) + res, _, err := applicationsegment.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_application_segment_browser_access.go b/zpa/data_source_zpa_application_segment_browser_access.go index 3d296bd7..814a1a28 100644 --- a/zpa/data_source_zpa_application_segment_browser_access.go +++ b/zpa/data_source_zpa_application_segment_browser_access.go @@ -188,11 +188,18 @@ func dataSourceApplicationSegmentBrowserAccess() *schema.Resource { func dataSourceApplicationSegmentBrowserAccessRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BrowserAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var resp *browseraccess.BrowserAccess id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for browser access application %s\n", id) - res, _, err := zClient.browseraccess.Get(id) + res, _, err := browseraccess.Get(service, id) if err != nil { return err } @@ -201,7 +208,7 @@ func dataSourceApplicationSegmentBrowserAccessRead(d *schema.ResourceData, m int name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for browser access application name %s\n", name) - res, _, err := zClient.browseraccess.GetByName(name) + res, _, err := browseraccess.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_application_segment_by_type.go b/zpa/data_source_zpa_application_segment_by_type.go index a413ac89..637584ac 100644 --- a/zpa/data_source_zpa_application_segment_by_type.go +++ b/zpa/data_source_zpa_application_segment_by_type.go @@ -5,6 +5,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentbytype" ) func dataSourceApplicationSegmentByType() *schema.Resource { @@ -76,8 +77,13 @@ func dataSourceApplicationSegmentByType() *schema.Resource { } func dataSourceApplicationSegmentByTypeRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.applicationsegmentbytype.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegmentByType + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } applicationType := d.Get("application_type").(string) if applicationType != "BROWSER_ACCESS" && applicationType != "SECURE_REMOTE_ACCESS" && applicationType != "INSPECT" { @@ -91,7 +97,7 @@ func dataSourceApplicationSegmentByTypeRead(d *schema.ResourceData, m interface{ } // Call the SDK function - resp, _, err := service.GetByApplicationType(name, applicationType, true) + resp, _, err := applicationsegmentbytype.GetByApplicationType(service, name, applicationType, true) if err != nil { return err } diff --git a/zpa/data_source_zpa_application_segment_inspection.go b/zpa/data_source_zpa_application_segment_inspection.go index 3d4013db..48b98dce 100644 --- a/zpa/data_source_zpa_application_segment_inspection.go +++ b/zpa/data_source_zpa_application_segment_inspection.go @@ -187,13 +187,19 @@ func dataSourceApplicationSegmentInspection() *schema.Resource { } func dataSourceApplicationSegmentInspectionRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegmentinspection.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *applicationsegmentinspection.AppSegmentInspection id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for inspection application segment %s\n", id) - res, _, err := service.Get(id) + res, _, err := applicationsegmentinspection.Get(service, id) if err != nil { return err } @@ -202,7 +208,7 @@ func dataSourceApplicationSegmentInspectionRead(d *schema.ResourceData, m interf name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for inspection application segment name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := applicationsegmentinspection.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_application_segment_pra.go b/zpa/data_source_zpa_application_segment_pra.go index 8d0a9e6c..9fa58183 100644 --- a/zpa/data_source_zpa_application_segment_pra.go +++ b/zpa/data_source_zpa_application_segment_pra.go @@ -191,12 +191,14 @@ func dataSourceApplicationSegmentPRA() *schema.Resource { } func dataSourceApplicationSegmentPRARead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegmentpra.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegmentPRA + var resp *applicationsegmentpra.AppSegmentPRA id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for sra application %s\n", id) - res, _, err := service.Get(id) + res, _, err := applicationsegmentpra.Get(service, id) if err != nil { return err } @@ -205,7 +207,7 @@ func dataSourceApplicationSegmentPRARead(d *schema.ResourceData, m interface{}) name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for sra application name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := applicationsegmentpra.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_ba_certificate.go b/zpa/data_source_zpa_ba_certificate.go index 9c072315..8adc3397 100644 --- a/zpa/data_source_zpa_ba_certificate.go +++ b/zpa/data_source_zpa_ba_certificate.go @@ -90,13 +90,18 @@ func dataSourceBaCertificate() *schema.Resource { } func dataSourceBaCertificateRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).bacertificate.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.BACertificate + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *bacertificate.BaCertificate id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for browser certificate %s\n", id) - res, _, err := service.Get(id) + res, _, err := bacertificate.Get(service, id) if err != nil { return err } @@ -106,7 +111,7 @@ func dataSourceBaCertificateRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for browser certificate name %s\n", name) - res, _, err := service.GetIssuedByName(name) + res, _, err := bacertificate.GetIssuedByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_browser_isolation_banner.go b/zpa/data_source_zpa_cloud_browser_isolation_banner.go index 30ee353d..bcaa62eb 100644 --- a/zpa/data_source_zpa_cloud_browser_isolation_banner.go +++ b/zpa/data_source_zpa_cloud_browser_isolation_banner.go @@ -54,12 +54,13 @@ func dataSourceCBIBanners() *schema.Resource { func dataSourceCBIBannersRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIBannerController var resp *cbibannercontroller.CBIBannerController id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for cbi banner %s\n", id) - res, _, err := zClient.cbibannercontroller.Get(id) + res, _, err := cbibannercontroller.Get(service, id) if err != nil { return err } @@ -68,7 +69,7 @@ func dataSourceCBIBannersRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data cbi banner name %s\n", name) - res, _, err := zClient.cbibannercontroller.GetByName(name) + res, _, err := cbibannercontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_browser_isolation_certificate.go b/zpa/data_source_zpa_cloud_browser_isolation_certificate.go index 2286a8a1..86a08269 100644 --- a/zpa/data_source_zpa_cloud_browser_isolation_certificate.go +++ b/zpa/data_source_zpa_cloud_browser_isolation_certificate.go @@ -35,12 +35,13 @@ func dataSourceCBICertificates() *schema.Resource { func dataSourceCBICertificatesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBICertificateController var resp *cbicertificatecontroller.CBICertificate id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for cbi certificate %s\n", id) - res, _, err := zClient.cbicertificatecontroller.Get(id) + res, _, err := cbicertificatecontroller.Get(service, id) if err != nil { return err } @@ -49,7 +50,7 @@ func dataSourceCBICertificatesRead(d *schema.ResourceData, m interface{}) error name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data cbi certificate name %s\n", name) - res, _, err := zClient.cbicertificatecontroller.GetByName(name) + res, _, err := cbicertificatecontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_browser_isolation_external_profile.go b/zpa/data_source_zpa_cloud_browser_isolation_external_profile.go index fcc1224a..813fc3f7 100644 --- a/zpa/data_source_zpa_cloud_browser_isolation_external_profile.go +++ b/zpa/data_source_zpa_cloud_browser_isolation_external_profile.go @@ -103,12 +103,13 @@ func dataSourceCBIExternalProfile() *schema.Resource { func dataSourceCBIExternalProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIProfileController var resp *cbiprofilecontroller.IsolationProfile id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for cbi external profile %s\n", id) - res, _, err := zClient.cbiprofilecontroller.Get(id) + res, _, err := cbiprofilecontroller.Get(service, id) if err != nil { return err } @@ -117,7 +118,7 @@ func dataSourceCBIExternalProfileRead(d *schema.ResourceData, m interface{}) err name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for cbi external profile name %s\n", name) - res, _, err := zClient.cbiprofilecontroller.GetByName(name) + res, _, err := cbiprofilecontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_browser_isolation_region.go b/zpa/data_source_zpa_cloud_browser_isolation_region.go index 3ed6f520..03c1f560 100644 --- a/zpa/data_source_zpa_cloud_browser_isolation_region.go +++ b/zpa/data_source_zpa_cloud_browser_isolation_region.go @@ -28,12 +28,13 @@ func dataSourceCBIRegions() *schema.Resource { func dataSourceCBIRegionsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIRegions var resp *cbiregions.CBIRegions name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for cbi regions name %s\n", name) - res, _, err := zClient.cbiregions.GetByName(name) + res, _, err := cbiregions.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_browser_isolation_zpaprofiles.go b/zpa/data_source_zpa_cloud_browser_isolation_zpaprofiles.go index 6fdf83a4..6fedaa47 100644 --- a/zpa/data_source_zpa_cloud_browser_isolation_zpaprofiles.go +++ b/zpa/data_source_zpa_cloud_browser_isolation_zpaprofiles.go @@ -58,13 +58,14 @@ func dataSourceCBIZPAProfiles() *schema.Resource { func dataSourceCBIZPAProfilesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIZpaProfile var resp *cbizpaprofile.ZPAProfiles name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for cbi zpa profile name %s\n", name) - res, _, err := zClient.cbizpaprofile.GetByName(name) + res, _, err := cbizpaprofile.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_cloud_connector_group.go b/zpa/data_source_zpa_cloud_connector_group.go index 1c671a4b..a120f315 100644 --- a/zpa/data_source_zpa_cloud_connector_group.go +++ b/zpa/data_source_zpa_cloud_connector_group.go @@ -112,12 +112,13 @@ func dataSourceCloudConnectorGroup() *schema.Resource { func dataSourceCloudConnectorGroupRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CloudConnectorGroup var resp *cloudconnectorgroup.CloudConnectorGroup id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for cloud connector group %s\n", id) - res, _, err := zClient.cloudconnectorgroup.Get(id) + res, _, err := cloudconnectorgroup.Get(service, id) if err != nil { return err } @@ -126,7 +127,7 @@ func dataSourceCloudConnectorGroupRead(d *schema.ResourceData, m interface{}) er name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for cloud connector group name %s\n", name) - res, _, err := zClient.cloudconnectorgroup.GetByName(name) + res, _, err := cloudconnectorgroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_customer_version_profile.go b/zpa/data_source_zpa_customer_version_profile.go index 5c1c845a..de44e41b 100644 --- a/zpa/data_source_zpa_customer_version_profile.go +++ b/zpa/data_source_zpa_customer_version_profile.go @@ -139,11 +139,13 @@ func dataSourceCustomerVersionProfile() *schema.Resource { func dataSourceCustomerVersionProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CustomerVersionProfile + var resp *customerversionprofile.CustomerVersionProfile name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for customer version profile name %s\n", name) - res, _, err := zClient.customerversionprofile.GetByName(name) + res, _, err := customerversionprofile.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_enrollement_cert.go b/zpa/data_source_zpa_enrollement_cert.go index 37ed9a6e..a05a3c4f 100644 --- a/zpa/data_source_zpa_enrollement_cert.go +++ b/zpa/data_source_zpa_enrollement_cert.go @@ -110,13 +110,18 @@ func dataSourceEnrollmentCert() *schema.Resource { } func dataSourceEnrollmentCertRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).enrollmentcert.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.EnrollmentCert + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *enrollmentcert.EnrollmentCert id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for signing certificate %s\n", id) - res, _, err := service.Get(id) + res, _, err := enrollmentcert.Get(service, id) if err != nil { return err } @@ -125,7 +130,7 @@ func dataSourceEnrollmentCertRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for signing certificate name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := enrollmentcert.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_idp_controller.go b/zpa/data_source_zpa_idp_controller.go index 378d45ec..a233ad02 100644 --- a/zpa/data_source_zpa_idp_controller.go +++ b/zpa/data_source_zpa_idp_controller.go @@ -187,12 +187,13 @@ func dataSourceIdpController() *schema.Resource { func dataSourceIdpControllerRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.IDPController var resp *idpcontroller.IdpController id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for idp controller %s\n", id) - res, _, err := zClient.idpcontroller.Get(id) + res, _, err := idpcontroller.Get(service, id) if err != nil { return err } @@ -202,7 +203,7 @@ func dataSourceIdpControllerRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for idp controller name %s\n", name) - res, _, err := zClient.idpcontroller.GetByName(name) + res, _, err := idpcontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_inspection_all_predefined_controls.go b/zpa/data_source_zpa_inspection_all_predefined_controls.go index 519b6cfa..04f7a6f2 100644 --- a/zpa/data_source_zpa_inspection_all_predefined_controls.go +++ b/zpa/data_source_zpa_inspection_all_predefined_controls.go @@ -123,6 +123,8 @@ func dataSourceInspectionAllPredefinedControls() *schema.Resource { func dataSourceInspectionAllPredefinedControlsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionPredefinedControls + version, versionSet := d.Get("version").(string) if !versionSet || version == "" { return fmt.Errorf("when the name is set, version must be set as well") @@ -131,9 +133,9 @@ func dataSourceInspectionAllPredefinedControlsRead(d *schema.ResourceData, m int var err error groupName, groupNameSet := d.Get("group_name").(string) if groupNameSet && groupName != "" { - list, err = zClient.inspection_predefined_controls.GetAllByGroup(version, groupName) + list, err = inspection_predefined_controls.GetAllByGroup(service, version, groupName) } else { - list, err = zClient.inspection_predefined_controls.GetAll(version) + list, err = inspection_predefined_controls.GetAll(service, version) } if err != nil { return err diff --git a/zpa/data_source_zpa_inspection_custom_controls.go b/zpa/data_source_zpa_inspection_custom_controls.go index efc84bfa..166ab4b1 100644 --- a/zpa/data_source_zpa_inspection_custom_controls.go +++ b/zpa/data_source_zpa_inspection_custom_controls.go @@ -132,12 +132,13 @@ func dataSourceInspectionCustomControls() *schema.Resource { func dataSourceInspectionCustomControlsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionCustomControls var resp *inspection_custom_controls.InspectionCustomControl id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for custom inspection control %s\n", id) - res, _, err := zClient.inspection_custom_controls.Get(id) + res, _, err := inspection_custom_controls.Get(service, id) if err != nil { return err } @@ -146,7 +147,7 @@ func dataSourceInspectionCustomControlsRead(d *schema.ResourceData, m interface{ name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for custom inspection control name %s\n", name) - res, _, err := zClient.inspection_custom_controls.GetByName(name) + res, _, err := inspection_custom_controls.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_inspection_predefined_controls.go b/zpa/data_source_zpa_inspection_predefined_controls.go index 19bcbc28..d7ea239a 100644 --- a/zpa/data_source_zpa_inspection_predefined_controls.go +++ b/zpa/data_source_zpa_inspection_predefined_controls.go @@ -110,12 +110,13 @@ func dataSourceInspectionPredefinedControls() *schema.Resource { func dataSourceInspectionPredefinedControlsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionPredefinedControls var resp *inspection_predefined_controls.PredefinedControls id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for predefined controls %s\n", id) - res, _, err := zClient.inspection_predefined_controls.Get(id) + res, _, err := inspection_predefined_controls.Get(service, id) if err != nil { return err } @@ -128,7 +129,7 @@ func dataSourceInspectionPredefinedControlsRead(d *schema.ResourceData, m interf return fmt.Errorf("when the name is set, version must be set as well") } log.Printf("[INFO] Getting data for predefined controls name %s\n", name) - res, _, err := zClient.inspection_predefined_controls.GetByName(name, version) + res, _, err := inspection_predefined_controls.GetByName(service, name, version) if err != nil { return err } diff --git a/zpa/data_source_zpa_inspection_predefined_controls_test.go b/zpa/data_source_zpa_inspection_predefined_controls_test.go index b45b9fa7..83bcd722 100644 --- a/zpa/data_source_zpa_inspection_predefined_controls_test.go +++ b/zpa/data_source_zpa_inspection_predefined_controls_test.go @@ -48,11 +48,6 @@ data "zpa_inspection_predefined_controls" "control03" { version = "OWASP_CRS/3.3.0" } -data "zpa_inspection_predefined_controls" "control04" { - name = "Attempted multipart/form-data bypass" - version = "OWASP_CRS/3.3.0" -} - data "zpa_inspection_predefined_controls" "control05" { name = "GET or HEAD Request with Body Content" version = "OWASP_CRS/3.3.0" diff --git a/zpa/data_source_zpa_inspection_profile.go b/zpa/data_source_zpa_inspection_profile.go index a741f85a..a42c001f 100644 --- a/zpa/data_source_zpa_inspection_profile.go +++ b/zpa/data_source_zpa_inspection_profile.go @@ -361,12 +361,13 @@ func dataSourceInspectionProfile() *schema.Resource { func dataSourceInspectionProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionProfile var resp *inspection_profile.InspectionProfile id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for inspection profile %s\n", id) - res, _, err := zClient.inspection_profile.Get(id) + res, _, err := inspection_profile.Get(service, id) if err != nil { return err } @@ -375,7 +376,7 @@ func dataSourceInspectionProfileRead(d *schema.ResourceData, m interface{}) erro name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for inspection profile name %s\n", name) - res, _, err := zClient.inspection_profile.GetByName(name) + res, _, err := inspection_profile.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_isolation_profiles.go b/zpa/data_source_zpa_isolation_profiles.go index 1d84a2bc..cab3d5f0 100644 --- a/zpa/data_source_zpa_isolation_profiles.go +++ b/zpa/data_source_zpa_isolation_profiles.go @@ -58,12 +58,13 @@ func dataSourceIsolationProfile() *schema.Resource { func dataSourceIsolationProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.IsolationProfile var resp *isolationprofile.IsolationProfile name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for isolation profile name %s\n", name) - res, _, err := zClient.isolationprofile.GetByName(name) + res, _, err := isolationprofile.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_lss_config_client_types.go b/zpa/data_source_zpa_lss_config_client_types.go index 00216a58..52b30a67 100644 --- a/zpa/data_source_zpa_lss_config_client_types.go +++ b/zpa/data_source_zpa_lss_config_client_types.go @@ -4,6 +4,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/lssconfigcontroller" ) func dataSourceLSSClientTypes() *schema.Resource { @@ -42,9 +43,11 @@ func dataSourceLSSClientTypes() *schema.Resource { func dataSourceLSSClientTypesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController + log.Printf("[INFO] Getting data for global policy set\n") - resp, _, err := zClient.lssconfigcontroller.GetClientTypes() + resp, _, err := lssconfigcontroller.GetClientTypes(service) if err != nil { return err } diff --git a/zpa/data_source_zpa_lss_config_controller.go b/zpa/data_source_zpa_lss_config_controller.go index fb429cf2..322d3c63 100644 --- a/zpa/data_source_zpa_lss_config_controller.go +++ b/zpa/data_source_zpa_lss_config_controller.go @@ -272,12 +272,13 @@ func dataSourceLSSConfigController() *schema.Resource { func dataSourceLSSConfigControllerRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController var resp *lssconfigcontroller.LSSResource id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for lss config controller %s\n", id) - res, _, err := zClient.lssconfigcontroller.Get(id) + res, _, err := lssconfigcontroller.Get(service, id) if err != nil { return err } @@ -286,7 +287,7 @@ func dataSourceLSSConfigControllerRead(d *schema.ResourceData, m interface{}) er name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for lss config controller %s\n", name) - res, _, err := zClient.lssconfigcontroller.GetByName(name) + res, _, err := lssconfigcontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_lss_config_log_types_formats.go b/zpa/data_source_zpa_lss_config_log_types_formats.go index 075f1579..e2fb9d8b 100644 --- a/zpa/data_source_zpa_lss_config_log_types_formats.go +++ b/zpa/data_source_zpa_lss_config_log_types_formats.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/lssconfigcontroller" ) func dataSourceLSSLogTypeFormats() *schema.Resource { @@ -56,12 +57,14 @@ func getLogType(d *schema.ResourceData) (string, bool) { func dataSourceLSSLogTypeFormatsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController + log.Printf("[INFO] Getting data for LSS Log Types Format set\n") logType, ok := getLogType(d) if !ok { return fmt.Errorf("[ERROR] log type is required") } - resp, _, err := zClient.lssconfigcontroller.GetFormats(logType) + resp, _, err := lssconfigcontroller.GetFormats(service, logType) if err != nil { return err } diff --git a/zpa/data_source_zpa_lss_config_status_codes.go b/zpa/data_source_zpa_lss_config_status_codes.go index cfbd85fc..ad4f7940 100644 --- a/zpa/data_source_zpa_lss_config_status_codes.go +++ b/zpa/data_source_zpa_lss_config_status_codes.go @@ -5,6 +5,7 @@ import ( "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/lssconfigcontroller" ) func dataSourceLSSStatusCodes() *schema.Resource { @@ -61,9 +62,11 @@ func toMapString(v map[string]interface{}) map[string]string { func dataSourceLSSStatusCodesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController + log.Printf("[INFO] Getting data for LSS Status Codes set\n") - resp, _, err := zClient.lssconfigcontroller.GetStatusCodes() + resp, _, err := lssconfigcontroller.GetStatusCodes(service) if err != nil { return err } diff --git a/zpa/data_source_zpa_machine_group.go b/zpa/data_source_zpa_machine_group.go index 078872ac..1b16e8ab 100644 --- a/zpa/data_source_zpa_machine_group.go +++ b/zpa/data_source_zpa_machine_group.go @@ -120,13 +120,19 @@ func dataSourceMachineGroup() *schema.Resource { } func dataSourceMachineGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).machinegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.MachineGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *machinegroup.MachineGroup id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for machine group %s\n", id) - res, _, err := service.Get(id) + res, _, err := machinegroup.Get(service, id) if err != nil { return err } @@ -135,7 +141,7 @@ func dataSourceMachineGroupRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for machine group name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := machinegroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_microtenant_controller.go b/zpa/data_source_zpa_microtenant_controller.go index 3e60c2c3..c2ad9ffe 100644 --- a/zpa/data_source_zpa_microtenant_controller.go +++ b/zpa/data_source_zpa_microtenant_controller.go @@ -211,12 +211,13 @@ func dataSourceMicrotenantController() *schema.Resource { func dataSourceMicrotenantControllerRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.MicroTenants var resp *microtenants.MicroTenant id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for microtenant %s\n", id) - res, _, err := zClient.microtenants.Get(id) + res, _, err := microtenants.Get(service, id) if err != nil { return err } @@ -226,7 +227,7 @@ func dataSourceMicrotenantControllerRead(d *schema.ResourceData, m interface{}) name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for microtenant name %s\n", name) - res, _, err := zClient.microtenants.GetByName(name) + res, _, err := microtenants.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_policy_type.go b/zpa/data_source_zpa_policy_type.go index 94effe86..ee0db3d1 100644 --- a/zpa/data_source_zpa_policy_type.go +++ b/zpa/data_source_zpa_policy_type.go @@ -238,15 +238,17 @@ func dataSourcePolicyType() *schema.Resource { } func dataSourcePolicyTypeRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetController + log.Printf("[INFO] Getting data for policy type\n") var resp *policysetcontroller.PolicySet var err error policyType, policyTypeIsSet := d.GetOk("policy_type") if policyTypeIsSet { - resp, _, err = service.GetByPolicyType(policyType.(string)) + resp, _, err = policysetcontroller.GetByPolicyType(service, policyType.(string)) } else { - resp, _, err = service.GetByPolicyType("GLOBAL_POLICY") + resp, _, err = policysetcontroller.GetByPolicyType(service, "GLOBAL_POLICY") } if err != nil { return err diff --git a/zpa/data_source_zpa_posture_profile.go b/zpa/data_source_zpa_posture_profile.go index c14718e5..32c12ec5 100644 --- a/zpa/data_source_zpa_posture_profile.go +++ b/zpa/data_source_zpa_posture_profile.go @@ -58,12 +58,13 @@ func dataSourcePostureProfile() *schema.Resource { func dataSourcePostureProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.PostureProfile var resp *postureprofile.PostureProfile id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for posture profile %s\n", id) - res, _, err := zClient.postureprofile.Get(id) + res, _, err := postureprofile.Get(service, id) if err != nil { return err } @@ -72,7 +73,7 @@ func dataSourcePostureProfileRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for posture profile name %s\n", name) - res, _, err := zClient.postureprofile.GetByName(name) + res, _, err := postureprofile.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_pra_approval.go b/zpa/data_source_zpa_pra_approval.go index 7e47e1ba..2d1efa80 100644 --- a/zpa/data_source_zpa_pra_approval.go +++ b/zpa/data_source_zpa_pra_approval.go @@ -120,13 +120,18 @@ func dataSourcePRAPrivilegedApprovalController() *schema.Resource { } func dataSourcePRAPrivilegedApprovalControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *praapproval.PrivilegedApproval id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for pra approval controller %s\n", id) - res, _, err := service.Get(id) + res, _, err := praapproval.Get(service, id) if err != nil { return err } @@ -135,7 +140,7 @@ func dataSourcePRAPrivilegedApprovalControllerRead(d *schema.ResourceData, m int emailID, ok := d.Get("email_ids").(string) if id == "" && ok && emailID != "" { log.Printf("[INFO] Getting data for pra approval email ID %s\n", emailID) - res, _, err := service.GetByEmailID(emailID) + res, _, err := praapproval.GetByEmailID(service, emailID) if err != nil { return err } diff --git a/zpa/data_source_zpa_pra_console.go b/zpa/data_source_zpa_pra_console.go index 7f688f4b..1ee304c1 100644 --- a/zpa/data_source_zpa_pra_console.go +++ b/zpa/data_source_zpa_pra_console.go @@ -103,13 +103,18 @@ func dataSourcePRAConsoleController() *schema.Resource { } func dataSourcePRAConsoleControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAConsole + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *praconsole.PRAConsole id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for pra console controller %s\n", id) - res, _, err := service.Get(id) + res, _, err := praconsole.Get(service, id) if err != nil { return err } @@ -118,7 +123,7 @@ func dataSourcePRAConsoleControllerRead(d *schema.ResourceData, m interface{}) e name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for sra console controller name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := praconsole.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_pra_credential_controller.go b/zpa/data_source_zpa_pra_credential_controller.go index bcbeaa53..5e997979 100644 --- a/zpa/data_source_zpa_pra_credential_controller.go +++ b/zpa/data_source_zpa_pra_credential_controller.go @@ -77,13 +77,18 @@ func dataSourcePRACredentialController() *schema.Resource { } func dataSourcePRACredentialControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRACredential + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *pracredential.Credential id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for credential controller %s\n", id) - res, _, err := service.Get(id) + res, _, err := pracredential.Get(service, id) if err != nil { return err } @@ -92,7 +97,7 @@ func dataSourcePRACredentialControllerRead(d *schema.ResourceData, m interface{} name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for credential controller name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := pracredential.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_pra_portal_controller.go b/zpa/data_source_zpa_pra_portal_controller.go index 80864f9c..4fb45da3 100644 --- a/zpa/data_source_zpa_pra_portal_controller.go +++ b/zpa/data_source_zpa_pra_portal_controller.go @@ -92,13 +92,18 @@ func dataSourcePRAPortalController() *schema.Resource { } func dataSourcePRAPortalControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAPortal + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *praportal.PRAPortal id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for pra portal controller %s\n", id) - res, _, err := service.Get(id) + res, _, err := praportal.Get(service, id) if err != nil { return err } @@ -107,7 +112,7 @@ func dataSourcePRAPortalControllerRead(d *schema.ResourceData, m interface{}) er name, ok := d.Get("name").(string) if id == "" && ok && name != "" { log.Printf("[INFO] Getting data for pra portal controller name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := praportal.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_provisioning_key.go b/zpa/data_source_zpa_provisioning_key.go index 3f7488de..1cfe0fc2 100644 --- a/zpa/data_source_zpa_provisioning_key.go +++ b/zpa/data_source_zpa_provisioning_key.go @@ -114,7 +114,14 @@ func dataSourceProvisioningKey() *schema.Resource { } func dataSourceProvisioningKeyRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + associationType, ok := getAssociationType(d) if !ok { return fmt.Errorf("associationType is required") @@ -123,7 +130,7 @@ func dataSourceProvisioningKeyRead(d *schema.ResourceData, m interface{}) error id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data provisioning key %s\n", id) - res, _, err := service.Get(associationType, id) + res, _, err := provisioningkey.Get(service, associationType, id) if err != nil { return err } @@ -132,7 +139,7 @@ func dataSourceProvisioningKeyRead(d *schema.ResourceData, m interface{}) error name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for provisioning key name %s\n", name) - res, _, err := service.GetByName(associationType, name) + res, _, err := provisioningkey.GetByName(service, associationType, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_saml_attribute.go b/zpa/data_source_zpa_saml_attribute.go index b960350b..918498ab 100644 --- a/zpa/data_source_zpa_saml_attribute.go +++ b/zpa/data_source_zpa_saml_attribute.go @@ -57,6 +57,7 @@ func dataSourceSamlAttribute() *schema.Resource { func dataSourceSamlAttributeRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.SAMLAttribute var resp *samlattribute.SamlAttribute idpId, okidpId := d.Get("idp_id").(string) @@ -68,14 +69,14 @@ func dataSourceSamlAttributeRead(d *schema.ResourceData, m interface{}) error { var idpResp *idpcontroller.IdpController // getting Idp controller by id or name if idpId != "" { - resp, _, err := zClient.idpcontroller.Get(idpId) + resp, _, err := idpcontroller.Get(service, idpId) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by id: %s\n", idpId) return err } idpResp = resp } else { - resp, _, err := zClient.idpcontroller.GetByName(idpName) + resp, _, err := idpcontroller.GetByName(service, idpName) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by name: %s\n", idpName) return err @@ -85,7 +86,7 @@ func dataSourceSamlAttributeRead(d *schema.ResourceData, m interface{}) error { // getting scim attribute header by id or name id, ok := d.Get("id").(string) if ok && id != "" { - res, _, err := zClient.samlattribute.Get(idpResp.ID) + res, _, err := samlattribute.Get(service, idpResp.ID) if err != nil { return err } @@ -93,7 +94,7 @@ func dataSourceSamlAttributeRead(d *schema.ResourceData, m interface{}) error { } name, ok := d.Get("name").(string) if id == "" && ok && name != "" { - res, _, err := zClient.samlattribute.GetByName(name) + res, _, err := samlattribute.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_scim_attribute_header.go b/zpa/data_source_zpa_scim_attribute_header.go index da4eb216..29b696d8 100644 --- a/zpa/data_source_zpa_scim_attribute_header.go +++ b/zpa/data_source_zpa_scim_attribute_header.go @@ -93,6 +93,7 @@ func dataSourceScimAttributeHeader() *schema.Resource { func dataSourceScimAttributeHeaderRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ScimAttributeHeader var resp *scimattributeheader.ScimAttributeHeader idpId, okidpId := d.Get("idp_id").(string) @@ -104,14 +105,14 @@ func dataSourceScimAttributeHeaderRead(d *schema.ResourceData, m interface{}) er var idpResp *idpcontroller.IdpController // getting Idp controller by id or name if idpId != "" { - resp, _, err := zClient.idpcontroller.Get(idpId) + resp, _, err := idpcontroller.Get(service, idpId) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by id: %s\n", idpId) return err } idpResp = resp } else { - resp, _, err := zClient.idpcontroller.GetByName(idpName) + resp, _, err := idpcontroller.GetByName(service, idpName) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by name: %s\n", idpName) return err @@ -121,7 +122,7 @@ func dataSourceScimAttributeHeaderRead(d *schema.ResourceData, m interface{}) er // getting scim attribute header by id or name id, ok := d.Get("id").(string) if ok && id != "" { - res, _, err := zClient.scimattributeheader.Get(idpResp.ID, id) + res, _, err := scimattributeheader.Get(service, idpResp.ID, id) if err != nil { return err } @@ -129,14 +130,14 @@ func dataSourceScimAttributeHeaderRead(d *schema.ResourceData, m interface{}) er } name, ok := d.Get("name").(string) if id == "" && ok && name != "" { - res, _, err := zClient.scimattributeheader.GetByName(name, idpResp.ID) + res, _, err := scimattributeheader.GetByName(service, name, idpResp.ID) if err != nil { return err } resp = res } if resp != nil { - values, _ := zClient.scimattributeheader.GetValues(resp.IdpID, resp.ID) + values, _ := scimattributeheader.GetValues(service, resp.IdpID, resp.ID) d.SetId(resp.ID) _ = d.Set("canonical_values", resp.CanonicalValues) _ = d.Set("case_sensitive", resp.CaseSensitive) diff --git a/zpa/data_source_zpa_scim_group.go b/zpa/data_source_zpa_scim_group.go index 6faf5e11..edadf60e 100644 --- a/zpa/data_source_zpa_scim_group.go +++ b/zpa/data_source_zpa_scim_group.go @@ -48,6 +48,8 @@ func dataSourceScimGroup() *schema.Resource { func dataSourceScimGroupRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.IDPController + var resp *scimgroup.ScimGroup idpId, okidpId := d.Get("idp_id").(string) idpName, okIdpName := d.Get("idp_name").(string) @@ -58,14 +60,14 @@ func dataSourceScimGroupRead(d *schema.ResourceData, m interface{}) error { var idpResp *idpcontroller.IdpController // getting Idp controller by id or name if idpId != "" { - resp, _, err := zClient.idpcontroller.Get(idpId) + resp, _, err := idpcontroller.Get(service, idpId) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by id: %s\n", idpId) return err } idpResp = resp } else { - resp, _, err := zClient.idpcontroller.GetByName(idpName) + resp, _, err := idpcontroller.GetByName(service, idpName) if err != nil || resp == nil { log.Printf("[INFO] couldn't find idp by name: %s\n", idpName) return err @@ -75,7 +77,7 @@ func dataSourceScimGroupRead(d *schema.ResourceData, m interface{}) error { // getting scim attribute header by id or name id, ok := d.Get("id").(string) if ok && id != "" { - res, _, err := zClient.scimgroup.Get(idpResp.ID) + res, _, err := zClient.ScimGroup.Get(idpResp.ID) if err != nil { return err } @@ -83,7 +85,7 @@ func dataSourceScimGroupRead(d *schema.ResourceData, m interface{}) error { } name, ok := d.Get("name").(string) if id == "" && ok && name != "" { - res, _, err := zClient.scimgroup.GetByName(name, idpResp.ID) + res, _, err := zClient.ScimGroup.GetByName(name, idpResp.ID) if err != nil { return err } diff --git a/zpa/data_source_zpa_segment_group.go b/zpa/data_source_zpa_segment_group.go index 31c3faaa..7c823b7c 100644 --- a/zpa/data_source_zpa_segment_group.go +++ b/zpa/data_source_zpa_segment_group.go @@ -203,13 +203,19 @@ func dataSourceSegmentGroup() *schema.Resource { } func dataSourceSegmentGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.SegmentGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *segmentgroup.SegmentGroup id, ok := d.Get("id").(string) if ok && id != "" { - log.Printf("[INFO] Getting data for server group %s\n", id) - res, _, err := service.Get(id) + log.Printf("[INFO] Getting data for segment group %s\n", id) + res, _, err := segmentgroup.Get(service, id) if err != nil { return err } @@ -217,8 +223,8 @@ func dataSourceSegmentGroupRead(d *schema.ResourceData, m interface{}) error { } name, ok := d.Get("name").(string) if ok && name != "" { - log.Printf("[INFO] Getting data for server group name %s\n", name) - res, _, err := service.GetByName(name) + log.Printf("[INFO] Getting data for segment group name %s\n", name) + res, _, err := segmentgroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_server_group.go b/zpa/data_source_zpa_server_group.go index f7cdcee7..030d8158 100644 --- a/zpa/data_source_zpa_server_group.go +++ b/zpa/data_source_zpa_server_group.go @@ -302,13 +302,18 @@ func dataSourceServerGroup() *schema.Resource { } func dataSourceServerGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServerGroup + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *servergroup.ServerGroup id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for server group %s\n", id) - res, _, err := service.Get(id) + res, _, err := servergroup.Get(service, id) if err != nil { return err } @@ -317,7 +322,7 @@ func dataSourceServerGroupRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for server group name %s\n", name) - res, _, err := service.GetByName(name) + res, _, err := servergroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_service_edge.go b/zpa/data_source_zpa_service_edge.go index 94aa7f94..980ec1ad 100644 --- a/zpa/data_source_zpa_service_edge.go +++ b/zpa/data_source_zpa_service_edge.go @@ -220,12 +220,17 @@ func dataSourceServiceEdgeController() *schema.Resource { func dataSourceServiceEdgeControllerRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ServiceEdgeController + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *serviceedgecontroller.ServiceEdgeController id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for service edge controller %s\n", id) - res, _, err := zClient.serviceedgecontroller.Get(id) + res, _, err := serviceedgecontroller.Get(service, id) if err != nil { return err } @@ -234,7 +239,7 @@ func dataSourceServiceEdgeControllerRead(d *schema.ResourceData, m interface{}) name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for service edge controller name %s\n", name) - res, _, err := zClient.serviceedgecontroller.GetByName(name) + res, _, err := serviceedgecontroller.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_service_edge_assistant_schedule.go b/zpa/data_source_zpa_service_edge_assistant_schedule.go new file mode 100644 index 00000000..0a1974ff --- /dev/null +++ b/zpa/data_source_zpa_service_edge_assistant_schedule.go @@ -0,0 +1,85 @@ +package zpa + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/serviceedgeschedule" +) + +func dataSourceServiceEdgeAssistantSchedule() *schema.Resource { + return &schema.Resource{ + Read: dataSourceServiceEdgeRead, + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + "customer_id": { + Type: schema.TypeString, + Optional: true, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "delete_disabled": { + Type: schema.TypeBool, + Computed: true, + }, + "frequency": { + Type: schema.TypeString, + Computed: true, + }, + "frequency_interval": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceServiceEdgeRead(d *schema.ResourceData, m interface{}) error { + zClient := m.(*Client) + service := zClient.ServiceEdgeSchedule + + var resp *serviceedgeschedule.AssistantSchedule + var err error + + id, idOk := d.GetOk("id") + customerID, customerIDOk := d.GetOk("customer_id") + + if idOk && id != "" { + log.Printf("[INFO] Getting data for app connector assistant schedule %s\n", id) + resp, _, err = serviceedgeschedule.GetSchedule(service) + if err != nil { + return err + } + } else if customerIDOk && customerID != "" { + log.Printf("[INFO] Getting data for app connector name %s\n", customerID) + resp, _, err = serviceedgeschedule.GetSchedule(service) + if err != nil { + return err + } + } else { + log.Printf("[INFO] No specific ID or customer ID provided, fetching default schedule") + resp, _, err = serviceedgeschedule.GetSchedule(service) + if err != nil { + return err + } + } + + if resp != nil { + d.SetId(resp.ID) + _ = d.Set("customer_id", resp.CustomerID) + _ = d.Set("enabled", resp.Enabled) + _ = d.Set("delete_disabled", resp.DeleteDisabled) + _ = d.Set("frequency", resp.Frequency) + _ = d.Set("frequency_interval", resp.FrequencyInterval) + } else { + return fmt.Errorf("couldn't find any app connector assistant schedule") + } + + return nil +} diff --git a/zpa/data_source_zpa_service_edge_group.go b/zpa/data_source_zpa_service_edge_group.go index 3d7e877f..933fc54c 100644 --- a/zpa/data_source_zpa_service_edge_group.go +++ b/zpa/data_source_zpa_service_edge_group.go @@ -383,12 +383,13 @@ func dataSourceServiceEdgeGroup() *schema.Resource { func dataSourceServiceEdgeGroupRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ServiceEdgeGroup var resp *serviceedgegroup.ServiceEdgeGroup id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for service edge group %s\n", id) - res, _, err := zClient.serviceedgegroup.Get(id) + res, _, err := serviceedgegroup.Get(service, id) if err != nil { return err } @@ -397,7 +398,7 @@ func dataSourceServiceEdgeGroupRead(d *schema.ResourceData, m interface{}) error name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for service edge group name %s\n", name) - res, _, err := zClient.serviceedgegroup.GetByName(name) + res, _, err := serviceedgegroup.GetByName(service, name) if err != nil { return err } diff --git a/zpa/data_source_zpa_trusted_network.go b/zpa/data_source_zpa_trusted_network.go index 2f8c4957..26de080e 100644 --- a/zpa/data_source_zpa_trusted_network.go +++ b/zpa/data_source_zpa_trusted_network.go @@ -50,12 +50,17 @@ func dataSourceTrustedNetwork() *schema.Resource { func dataSourceTrustedNetworkRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.TrustedNetwork + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } var resp *trustednetwork.TrustedNetwork id, ok := d.Get("id").(string) if ok && id != "" { log.Printf("[INFO] Getting data for trusted network %s\n", id) - res, _, err := zClient.trustednetwork.Get(id) + res, _, err := trustednetwork.Get(service, id) if err != nil { return err } @@ -65,7 +70,7 @@ func dataSourceTrustedNetworkRead(d *schema.ResourceData, m interface{}) error { name, ok := d.Get("name").(string) if ok && name != "" { log.Printf("[INFO] Getting data for trusted network name %s\n", name) - res, _, err := zClient.trustednetwork.GetByName(name) + res, _, err := trustednetwork.GetByName(service, name) if err != nil { return err } diff --git a/zpa/provider.go b/zpa/provider.go index 5563531f..6c19ef38 100644 --- a/zpa/provider.go +++ b/zpa/provider.go @@ -91,6 +91,7 @@ func ZPAProvider() *schema.Provider { "zpa_policy_capabilities_rule": resourcePolicyCapabilitiesAccessRule(), "zpa_provisioning_key": resourceProvisioningKey(), "zpa_service_edge_group": resourceServiceEdgeGroup(), + "zpa_service_edge_assistant_schedule": resourceServiceEdgeAssistantSchedule(), "zpa_lss_config_controller": resourceLSSConfigController(), "zpa_inspection_custom_controls": resourceInspectionCustomControls(), "zpa_inspection_profile": resourceInspectionProfile(), @@ -131,6 +132,7 @@ func ZPAProvider() *schema.Provider { "zpa_posture_profile": dataSourcePostureProfile(), "zpa_service_edge_group": dataSourceServiceEdgeGroup(), "zpa_service_edge_controller": dataSourceServiceEdgeController(), + "zpa_service_edge_assistant_schedule": dataSourceServiceEdgeAssistantSchedule(), "zpa_saml_attribute": dataSourceSamlAttribute(), "zpa_scim_groups": dataSourceScimGroup(), "zpa_scim_attribute_header": dataSourceScimAttributeHeader(), diff --git a/zpa/provider_sweeper_test.go b/zpa/provider_sweeper_test.go index 08df088e..282eb944 100644 --- a/zpa/provider_sweeper_test.go +++ b/zpa/provider_sweeper_test.go @@ -11,6 +11,28 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorgroup" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentinspection" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentpra" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appservercontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/bacertificate" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/browseraccess" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbibannercontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbicertificatecontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/cloudbrowserisolation/cbiprofilecontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/inspectioncontrol/inspection_custom_controls" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/inspectioncontrol/inspection_profile" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/lssconfigcontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praapproval" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praconsole" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/pracredential" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praportal" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/provisioningkey" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/servergroup" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/serviceedgegroup" ) var ( @@ -108,7 +130,7 @@ func setupSweeper(resourceType string, del func(*testClient) error) { // TODO: Tests is failing on QA2 tenant. Needs further investigation. func sweepTestAppConnectorGroup(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.appconnectorgroup.GetAll() + group, _, err := appconnectorgroup.GetAll(client.sdkClient.AppConnectorGroup) if err != nil { return err } @@ -117,7 +139,7 @@ func sweepTestAppConnectorGroup(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.appconnectorgroup.Delete(b.ID); err != nil { + if _, err := appconnectorgroup.Delete(client.sdkClient.AppConnectorGroup, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -135,7 +157,7 @@ func sweepTestAppConnectorGroup(client *testClient) error { func sweepTestApplicationServer(client *testClient) error { var errorList []error - server, _, err := client.sdkClient.appservercontroller.GetAll() + server, _, err := appservercontroller.GetAll(client.sdkClient.AppServerController) if err != nil { return err } @@ -144,7 +166,7 @@ func sweepTestApplicationServer(client *testClient) error { for _, b := range server { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.appservercontroller.Delete(b.ID); err != nil { + if _, err := appservercontroller.Delete(client.sdkClient.AppServerController, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -162,7 +184,7 @@ func sweepTestApplicationServer(client *testClient) error { func sweepTestApplicationSegment(client *testClient) error { var errorList []error - appSegment, _, err := client.sdkClient.applicationsegment.GetAll() + appSegment, _, err := applicationsegment.GetAll(client.sdkClient.ApplicationSegment) if err != nil { return err } @@ -171,7 +193,7 @@ func sweepTestApplicationSegment(client *testClient) error { for _, b := range appSegment { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.applicationsegment.Delete(b.ID); err != nil { + if _, err := applicationsegment.Delete(client.sdkClient.ApplicationSegment, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -189,7 +211,7 @@ func sweepTestApplicationSegment(client *testClient) error { func sweepTestApplicationSegmentBA(client *testClient) error { var errorList []error - appSegmentBA, _, err := client.sdkClient.browseraccess.GetAll() + appSegmentBA, _, err := browseraccess.GetAll(client.sdkClient.BrowserAccess) if err != nil { return err } @@ -198,7 +220,7 @@ func sweepTestApplicationSegmentBA(client *testClient) error { for _, b := range appSegmentBA { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.browseraccess.Delete(b.ID); err != nil { + if _, err := browseraccess.Delete(client.sdkClient.BrowserAccess, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -216,7 +238,7 @@ func sweepTestApplicationSegmentBA(client *testClient) error { func sweepTestApplicationInspection(client *testClient) error { var errorList []error - appInspection, _, err := client.sdkClient.applicationsegmentinspection.GetAll() + appInspection, _, err := applicationsegmentinspection.GetAll(client.sdkClient.ApplicationSegmentInspection) if err != nil { return err } @@ -225,7 +247,7 @@ func sweepTestApplicationInspection(client *testClient) error { for _, b := range appInspection { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.applicationsegmentinspection.Delete(b.ID); err != nil { + if _, err := applicationsegmentinspection.Delete(client.sdkClient.ApplicationSegmentInspection, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -243,7 +265,7 @@ func sweepTestApplicationInspection(client *testClient) error { func sweepTestApplicationPRA(client *testClient) error { var errorList []error - pra, _, err := client.sdkClient.applicationsegmentpra.GetAll() + pra, _, err := applicationsegmentpra.GetAll(client.sdkClient.ApplicationSegmentPRA) if err != nil { return err } @@ -252,7 +274,7 @@ func sweepTestApplicationPRA(client *testClient) error { for _, b := range pra { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.applicationsegmentpra.Delete(b.ID); err != nil { + if _, err := applicationsegmentpra.Delete(client.sdkClient.ApplicationSegmentPRA, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -270,7 +292,7 @@ func sweepTestApplicationPRA(client *testClient) error { func sweepTestInspectionCustomControl(client *testClient) error { var errorList []error - customControl, _, err := client.sdkClient.inspection_custom_controls.GetAll() + customControl, _, err := inspection_custom_controls.GetAll(client.sdkClient.InspectionCustomControls) if err != nil { return err } @@ -279,7 +301,7 @@ func sweepTestInspectionCustomControl(client *testClient) error { for _, b := range customControl { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.inspection_custom_controls.Delete(b.ID); err != nil { + if _, err := inspection_custom_controls.Delete(client.sdkClient.InspectionCustomControls, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -297,7 +319,7 @@ func sweepTestInspectionCustomControl(client *testClient) error { func sweepTestInspectionProfile(client *testClient) error { var errorList []error - profile, _, err := client.sdkClient.inspection_profile.GetAll() + profile, _, err := inspection_profile.GetAll(client.sdkClient.InspectionProfile) if err != nil { return err } @@ -306,7 +328,7 @@ func sweepTestInspectionProfile(client *testClient) error { for _, b := range profile { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.inspection_profile.Delete(b.ID); err != nil { + if _, err := inspection_profile.Delete(client.sdkClient.InspectionProfile, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -325,7 +347,7 @@ func sweepTestInspectionProfile(client *testClient) error { func sweepTestLSSConfigController(client *testClient) error { var errorList []error - lssConfig, _, err := client.sdkClient.lssconfigcontroller.GetAll() + lssConfig, _, err := lssconfigcontroller.GetAll(client.sdkClient.LSSConfigController) if err != nil { if strings.Contains(err.Error(), "resource.not.found") { // Log that the resource was not found and continue @@ -343,7 +365,7 @@ func sweepTestLSSConfigController(client *testClient) error { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.LSSConfig.Name, testResourcePrefix) || strings.HasPrefix(b.LSSConfig.Name, updateResourcePrefix) { // Attempt to delete the resource - _, err := client.sdkClient.lssconfigcontroller.Delete(b.ID) + _, err := lssconfigcontroller.Delete(client.sdkClient.LSSConfigController, b.ID) if err != nil { // Check if the error is because the resource doesn't exist if strings.Contains(err.Error(), "resource.not.found") { @@ -400,7 +422,7 @@ func sweepTestAccessPolicyRuleByType(client *testClient) error { for _, policyType := range policyTypes { // Fetch the PolicySet details for the current policy type to get the PolicySetID - policySet, _, err := client.sdkClient.policysetcontroller.GetByPolicyType(policyType) + policySet, _, err := policysetcontroller.GetByPolicyType(client.sdkClient.PolicySetController, policyType) if err != nil { // If we fail to get a PolicySetID for a specific policy type, append the error and continue to the next type errorList = append(errorList, fmt.Errorf("Failed to get PolicySetID for policy type %s: %v", policyType, err)) @@ -409,7 +431,7 @@ func sweepTestAccessPolicyRuleByType(client *testClient) error { policySetID := policySet.ID // Fetch all rules for the current policy type - rules, _, err := client.sdkClient.policysetcontroller.GetAllByType(policyType) + rules, _, err := policysetcontroller.GetAllByType(client.sdkClient.PolicySetController, policyType) if err != nil { // If we fail to fetch rules for a specific policy type, append the error and continue to the next type errorList = append(errorList, fmt.Errorf("Failed to get rules for policy type %s: %v", policyType, err)) @@ -427,7 +449,7 @@ func sweepTestAccessPolicyRuleByType(client *testClient) error { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(rule.Name, testResourcePrefix) || strings.HasPrefix(rule.Name, updateResourcePrefix) { // Use the fetched PolicySetID for deletion - if _, err := client.sdkClient.policysetcontroller.Delete(policySetID, rule.ID); err != nil { + if _, err := policysetcontroller.Delete(client.sdkClient.PolicySetController, policySetID, rule.ID); err != nil { errorList = append(errorList, err) continue } @@ -445,7 +467,7 @@ func sweepTestAccessPolicyRuleByType(client *testClient) error { func sweepTestProvisioningKey(client *testClient) error { var errorList []error - provisioningKey, err := client.sdkClient.provisioningkey.GetAll() + provisioningKey, err := provisioningkey.GetAll(client.sdkClient.ProvisioningKey) if err != nil { return err } @@ -455,7 +477,7 @@ func sweepTestProvisioningKey(client *testClient) error { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { // Assuming 'AssociationType' is a field in the provisioningKey object - if _, err := client.sdkClient.provisioningkey.Delete(b.AssociationType, b.ID); err != nil { + if _, err := provisioningkey.Delete(client.sdkClient.ProvisioningKey, b.AssociationType, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -473,7 +495,7 @@ func sweepTestProvisioningKey(client *testClient) error { func sweepTestSegmentGroup(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.segmentgroup.GetAll() + group, _, err := segmentgroup.GetAll(client.sdkClient.SegmentGroup) if err != nil { return err } @@ -482,7 +504,7 @@ func sweepTestSegmentGroup(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.segmentgroup.Delete(b.ID); err != nil { + if _, err := segmentgroup.Delete(client.sdkClient.SegmentGroup, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -500,7 +522,7 @@ func sweepTestSegmentGroup(client *testClient) error { func sweepTestServerGroup(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.servergroup.GetAll() + group, _, err := servergroup.GetAll(client.sdkClient.ServerGroup) if err != nil { return err } @@ -509,7 +531,7 @@ func sweepTestServerGroup(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.servergroup.Delete(b.ID); err != nil { + if _, err := servergroup.Delete(client.sdkClient.ServerGroup, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -527,7 +549,7 @@ func sweepTestServerGroup(client *testClient) error { func sweepTestServiceEdgeGroup(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.serviceedgegroup.GetAll() + group, _, err := serviceedgegroup.GetAll(client.sdkClient.ServiceEdgeGroup) if err != nil { return err } @@ -536,7 +558,7 @@ func sweepTestServiceEdgeGroup(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.serviceedgegroup.Delete(b.ID); err != nil { + if _, err := serviceedgegroup.Delete(client.sdkClient.ServiceEdgeGroup, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -554,7 +576,7 @@ func sweepTestServiceEdgeGroup(client *testClient) error { func sweepTestCBIBanner(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.cbibannercontroller.GetAll() + group, _, err := cbibannercontroller.GetAll(client.sdkClient.CBIBannerController) if err != nil { return err } @@ -563,7 +585,7 @@ func sweepTestCBIBanner(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.cbibannercontroller.Delete(b.ID); err != nil { + if _, err := cbibannercontroller.Delete(client.sdkClient.CBIBannerController, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -581,7 +603,7 @@ func sweepTestCBIBanner(client *testClient) error { func sweepTestCBIExternalProfile(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.cbiprofilecontroller.GetAll() + group, _, err := cbiprofilecontroller.GetAll(client.sdkClient.CBIProfileController) if err != nil { return err } @@ -590,7 +612,7 @@ func sweepTestCBIExternalProfile(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.cbiprofilecontroller.Delete(b.ID); err != nil { + if _, err := cbiprofilecontroller.Delete(client.sdkClient.CBIProfileController, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -608,7 +630,7 @@ func sweepTestCBIExternalProfile(client *testClient) error { func sweepTestCBICertificate(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.cbicertificatecontroller.GetAll() + group, _, err := cbicertificatecontroller.GetAll(client.sdkClient.CBICertificateController) if err != nil { return err } @@ -617,7 +639,7 @@ func sweepTestCBICertificate(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.cbicertificatecontroller.Delete(b.ID); err != nil { + if _, err := cbicertificatecontroller.Delete(client.sdkClient.CBICertificateController, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -635,7 +657,7 @@ func sweepTestCBICertificate(client *testClient) error { func sweepTestBaCertificate(client *testClient) error { var errorList []error - group, _, err := client.sdkClient.bacertificate.GetAll() + group, _, err := bacertificate.GetAll(client.sdkClient.BACertificate) if err != nil { return err } @@ -644,7 +666,7 @@ func sweepTestBaCertificate(client *testClient) error { for _, b := range group { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.bacertificate.Delete(b.ID); err != nil { + if _, err := bacertificate.Delete(client.sdkClient.BACertificate, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -662,7 +684,7 @@ func sweepTestBaCertificate(client *testClient) error { func sweepTestPRACredentialController(client *testClient) error { var errorList []error - credential, _, err := client.sdkClient.pracredential.GetAll() + credential, _, err := pracredential.GetAll(client.sdkClient.PRACredential) if err != nil { return err } @@ -671,7 +693,7 @@ func sweepTestPRACredentialController(client *testClient) error { for _, b := range credential { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.pracredential.Delete(b.ID); err != nil { + if _, err := pracredential.Delete(client.sdkClient.PRACredential, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -689,7 +711,7 @@ func sweepTestPRACredentialController(client *testClient) error { func sweepTestPRAConsoleController(client *testClient) error { var errorList []error - console, _, err := client.sdkClient.praconsole.GetAll() + console, _, err := praconsole.GetAll(client.sdkClient.PRAConsole) if err != nil { return err } @@ -698,7 +720,7 @@ func sweepTestPRAConsoleController(client *testClient) error { for _, b := range console { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.praconsole.Delete(b.ID); err != nil { + if _, err := praconsole.Delete(client.sdkClient.PRAConsole, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -716,7 +738,7 @@ func sweepTestPRAConsoleController(client *testClient) error { func sweepTestPRAPortalController(client *testClient) error { var errorList []error - portal, _, err := client.sdkClient.praportal.GetAll() + portal, _, err := praportal.GetAll(client.sdkClient.PRAPortal) if err != nil { return err } @@ -725,7 +747,7 @@ func sweepTestPRAPortalController(client *testClient) error { for _, b := range portal { // Check if the resource name has the required prefix before deleting it if strings.HasPrefix(b.Name, testResourcePrefix) || strings.HasPrefix(b.Name, updateResourcePrefix) { - if _, err := client.sdkClient.praportal.Delete(b.ID); err != nil { + if _, err := praportal.Delete(client.sdkClient.PRAPortal, b.ID); err != nil { errorList = append(errorList, err) continue } @@ -744,7 +766,7 @@ func sweepTestPRAPortalController(client *testClient) error { func sweepTestPRAPrivilegedApprovalController(client *testClient) error { var errorList []error // First, get all pra approval resources - approvals, _, err := client.sdkClient.praapproval.GetAll() + approvals, _, err := praapproval.GetAll(client.sdkClient.PRAApproval) if err != nil { return err } @@ -756,7 +778,7 @@ func sweepTestPRAPrivilegedApprovalController(client *testClient) error { for _, emailID := range approval.EmailIDs { if strings.Contains(emailID, "pra_user_") { // If the emailID contains "pra_user_", delete the resource - if _, err := client.sdkClient.praapproval.Delete(approval.ID); err != nil { + if _, err := praapproval.Delete(client.sdkClient.PRAApproval, approval.ID); err != nil { errorList = append(errorList, err) continue } diff --git a/zpa/resource_zpa_app_connector_assistant_schedule.go b/zpa/resource_zpa_app_connector_assistant_schedule.go index 12e7076b..cb2b6f6e 100644 --- a/zpa/resource_zpa_app_connector_assistant_schedule.go +++ b/zpa/resource_zpa_app_connector_assistant_schedule.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorcontroller" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorschedule" ) func resourceAppConnectorAssistantSchedule() *schema.Resource { @@ -64,6 +64,7 @@ func resourceAppConnectorAssistantSchedule() *schema.Resource { func resourceAppConnectorAssistantScheduleCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.AppConnectorSchedule req, err := expandAssistantSchedule(d) if err != nil { @@ -71,7 +72,7 @@ func resourceAppConnectorAssistantScheduleCreate(d *schema.ResourceData, m inter } // Use = instead of := because err is already declared - _, _, err = zClient.appconnectorcontroller.CreateSchedule(req) + _, _, err = appconnectorschedule.CreateSchedule(service, req) if err != nil { // Assuming err.Error() returns a string representation of the error errStr := err.Error() @@ -81,7 +82,7 @@ func resourceAppConnectorAssistantScheduleCreate(d *schema.ResourceData, m inter log.Printf("[INFO] Resource already exists. Updating instead.") // Get the current state of the resource - resp, _, err := zClient.appconnectorcontroller.GetSchedule() + resp, _, err := appconnectorschedule.GetSchedule(service) if err != nil { return fmt.Errorf("failed to retrieve existing resource for update: %v", err) } @@ -102,8 +103,9 @@ func resourceAppConnectorAssistantScheduleCreate(d *schema.ResourceData, m inter func resourceAppConnectorAssistantScheduleRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.AppConnectorSchedule - resp, _, err := zClient.appconnectorcontroller.GetSchedule() + resp, _, err := appconnectorschedule.GetSchedule(service) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing app connector assistant schedule %s from state because it no longer exists in ZPA", d.Id()) @@ -125,6 +127,7 @@ func resourceAppConnectorAssistantScheduleRead(d *schema.ResourceData, m interfa func resourceAppConnectorAssistantScheduleUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.AppConnectorSchedule id := d.Id() log.Printf("[INFO] Updating app connector group ID: %v\n", id) @@ -133,14 +136,14 @@ func resourceAppConnectorAssistantScheduleUpdate(d *schema.ResourceData, m inter return err } - if _, _, err := zClient.appconnectorcontroller.GetSchedule(); err != nil { + if _, _, err := appconnectorschedule.GetSchedule(service); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.appconnectorcontroller.UpdateSchedule(id, &req); err != nil { + if _, err := appconnectorschedule.UpdateSchedule(service, id, &req); err != nil { return err } @@ -151,17 +154,17 @@ func resourceAppConnectorAssistantScheduleDelete(d *schema.ResourceData, m inter return nil } -func expandAssistantSchedule(d *schema.ResourceData) (appconnectorcontroller.AssistantSchedule, error) { +func expandAssistantSchedule(d *schema.ResourceData) (appconnectorschedule.AssistantSchedule, error) { var customerID string if id, exists := d.GetOk("customer_id"); exists { customerID = id.(string) } else if id := os.Getenv("ZPA_CUSTOMER_ID"); id != "" { customerID = id } else { - return appconnectorcontroller.AssistantSchedule{}, fmt.Errorf("customer_id must be provided either in the HCL or as an environment variable ZPA_CUSTOMER_ID") + return appconnectorschedule.AssistantSchedule{}, fmt.Errorf("customer_id must be provided either in the HCL or as an environment variable ZPA_CUSTOMER_ID") } - scheduler := appconnectorcontroller.AssistantSchedule{ + scheduler := appconnectorschedule.AssistantSchedule{ ID: d.Get("id").(string), CustomerID: customerID, // Now guaranteed to be non-empty Enabled: d.Get("enabled").(bool), diff --git a/zpa/resource_zpa_app_connector_group.go b/zpa/resource_zpa_app_connector_group.go index d8633df9..fc54da4c 100644 --- a/zpa/resource_zpa_app_connector_group.go +++ b/zpa/resource_zpa_app_connector_group.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorgroup" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) @@ -20,7 +21,13 @@ func resourceAppConnectorGroup() *schema.Resource { Delete: resourceAppConnectorGroupDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.AppConnectorGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -28,14 +35,13 @@ func resourceAppConnectorGroup() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := appconnectorgroup.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) } else { return []*schema.ResourceData{d}, err } - } return []*schema.ResourceData{d}, nil }, @@ -187,7 +193,13 @@ func resourceAppConnectorGroup() *schema.Resource { } func resourceAppConnectorGroupCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppConnectorGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } if err := validateAndSetProfileNameID(d); err != nil { return err @@ -199,7 +211,7 @@ func resourceAppConnectorGroupCreate(d *schema.ResourceData, m interface{}) erro return err } - resp, _, err := service.Create(req) + resp, _, err := appconnectorgroup.Create(service, req) if err != nil { return err } @@ -210,20 +222,25 @@ func resourceAppConnectorGroupCreate(d *schema.ResourceData, m interface{}) erro } func resourceAppConnectorGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppConnectorGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := service.Get(d.Id()) + resp, _, err := appconnectorgroup.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing app connector group %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") return nil } - return err } - log.Printf("[INFO] Getting application server:\n%+v\n", resp) + log.Printf("[INFO] Getting app connector group:\n%+v\n", resp) _ = d.Set("name", resp.Name) _ = d.Set("city_country", resp.CityCountry) _ = d.Set("country_code", resp.CountryCode) @@ -250,7 +267,13 @@ func resourceAppConnectorGroupRead(d *schema.ResourceData, m interface{}) error } func resourceAppConnectorGroupUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppConnectorGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } if err := validateAndSetProfileNameID(d); err != nil { return err @@ -263,28 +286,28 @@ func resourceAppConnectorGroupUpdate(d *schema.ResourceData, m interface{}) erro return err } - if _, _, err := service.Get(id); err != nil { + if _, _, err := appconnectorgroup.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := appconnectorgroup.Update(service, id, &req); err != nil { return err } return resourceAppConnectorGroupRead(d, m) } -func detachAppConnectorGroupFromAllAccessPolicyRules(d *schema.ResourceData, policySetControllerService *policysetcontroller.Service) { +func detachAppConnectorGroupFromAllAccessPolicyRules(d *schema.ResourceData, policySetControllerService *services.Service) { policyRulesDetchLock.Lock() defer policyRulesDetchLock.Unlock() - accessPolicySet, _, err := policySetControllerService.GetByPolicyType("ACCESS_POLICY") + accessPolicySet, _, err := policysetcontroller.GetByPolicyType(policySetControllerService, "ACCESS_POLICY") if err != nil { return } - rules, _, err := policySetControllerService.GetAllByType("ACCESS_POLICY") + rules, _, err := policysetcontroller.GetAllByType(policySetControllerService, "ACCESS_POLICY") if err != nil { return } @@ -302,7 +325,8 @@ func detachAppConnectorGroupFromAllAccessPolicyRules(d *schema.ResourceData, pol } rule.AppConnectorGroups = ids if changed { - if _, err := policySetControllerService.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(accessPolicySet.ID, rule.ID, &rule); err != nil { + microTenantID := GetString(d.Get("microtenant_id")) + if _, err := policysetcontroller.UpdateRule(policySetControllerService.WithMicroTenant(microTenantID), accessPolicySet.ID, rule.ID, &rule); err != nil { continue } } @@ -311,14 +335,24 @@ func detachAppConnectorGroupFromAllAccessPolicyRules(d *schema.ResourceData, pol func resourceAppConnectorGroupDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) - policySetControllerService := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) - service := zClient.appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) - log.Printf("[INFO] Deleting app connector groupID: %v\n", d.Id()) + policySetControllerService := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + policySetControllerService = policySetControllerService.WithMicroTenant(microTenantID) + } + + service := zClient.AppConnectorGroup + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + log.Printf("[INFO] Deleting app connector group ID: %v\n", d.Id()) // detach app connector group from all access policy rules detachAppConnectorGroupFromAllAccessPolicyRules(d, policySetControllerService) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := appconnectorgroup.Delete(service, d.Id()); err != nil { return err } d.SetId("") @@ -326,6 +360,19 @@ func resourceAppConnectorGroupDelete(d *schema.ResourceData, m interface{}) erro return nil } +func validateTCPQuickAck(tcp appconnectorgroup.AppConnectorGroup) error { + if tcp.TCPQuickAckApp != tcp.TCPQuickAckAssistant { + return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") + } + if tcp.TCPQuickAckApp != tcp.TCPQuickAckReadAssistant { + return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") + } + if tcp.TCPQuickAckAssistant != tcp.TCPQuickAckReadAssistant { + return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") + } + return nil +} + func expandAppConnectorGroup(d *schema.ResourceData) appconnectorgroup.AppConnectorGroup { appConnectorGroup := appconnectorgroup.AppConnectorGroup{ ID: d.Get("id").(string), @@ -354,16 +401,3 @@ func expandAppConnectorGroup(d *schema.ResourceData) appconnectorgroup.AppConnec } return appConnectorGroup } - -func validateTCPQuickAck(tcp appconnectorgroup.AppConnectorGroup) error { - if tcp.TCPQuickAckApp != tcp.TCPQuickAckAssistant { - return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") - } - if tcp.TCPQuickAckApp != tcp.TCPQuickAckReadAssistant { - return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") - } - if tcp.TCPQuickAckAssistant != tcp.TCPQuickAckReadAssistant { - return fmt.Errorf("the values of tcpQuickAck related flags need to be consistent") - } - return nil -} diff --git a/zpa/resource_zpa_app_connector_group_test.go b/zpa/resource_zpa_app_connector_group_test.go index da437a92..89d972ed 100644 --- a/zpa/resource_zpa_app_connector_group_test.go +++ b/zpa/resource_zpa_app_connector_group_test.go @@ -72,7 +72,13 @@ func testAccCheckAppConnectorGroupDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.appconnectorgroup.Get(rs.Primary.ID) + microTenantID := rs.Primary.Attributes["microtenant_id"] + service := apiClient.AppConnectorGroup + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + rule, _, err := appconnectorgroup.Get(service, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -97,9 +103,15 @@ func testAccCheckAppConnectorGroupExists(resource string, rule *appconnectorgrou } apiClient := testAccProvider.Meta().(*Client) - receivedRule, _, err := apiClient.appconnectorgroup.Get(rs.Primary.ID) + microTenantID := rs.Primary.Attributes["microtenant_id"] + service := apiClient.AppConnectorGroup + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + receivedRule, _, err := appconnectorgroup.Get(service, rs.Primary.ID) if err != nil { - return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) + return fmt.Errorf("failed fetching resource %s. Received error: %s", resource, err) } *rule = *receivedRule diff --git a/zpa/resource_zpa_app_server_controller.go b/zpa/resource_zpa_app_server_controller.go index 11789435..3d0fee30 100644 --- a/zpa/resource_zpa_app_server_controller.go +++ b/zpa/resource_zpa_app_server_controller.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appservercontroller" ) @@ -18,7 +19,13 @@ func resourceApplicationServer() *schema.Resource { Delete: resourceApplicationServerDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - zClient := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.AppServerController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -26,7 +33,7 @@ func resourceApplicationServer() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.GetByName(id) + resp, _, err := appservercontroller.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -94,12 +101,18 @@ func resourceApplicationServer() *schema.Resource { } func resourceApplicationServerCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppServerController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandCreateAppServerRequest(d) log.Printf("[INFO] Creating zpa application server with request\n%+v\n", req) - resp, _, err := service.Create(req) + resp, _, err := appservercontroller.Create(service, req) if err != nil { return err } @@ -110,9 +123,15 @@ func resourceApplicationServerCreate(d *schema.ResourceData, m interface{}) erro } func resourceApplicationServerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppServerController - resp, _, err := service.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := appservercontroller.Get(service, d.Id()) if err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { log.Printf("[WARN] Removing application server %s from state because it no longer exists in ZPA", d.Id()) @@ -135,21 +154,26 @@ func resourceApplicationServerRead(d *schema.ResourceData, m interface{}) error } func resourceApplicationServerUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppServerController + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Println("An updated occurred") if d.HasChange("app_server_group_ids") || d.HasChange("name") || d.HasChange("description") || d.HasChange("address") || d.HasChange("enabled") { log.Println("The AppServerGroupID, name, description or address has been changed") - if _, _, err := service.Get(d.Id()); err != nil { + if _, _, err := appservercontroller.Get(service, d.Id()); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(d.Id(), appservercontroller.ApplicationServer{ + if _, err := appservercontroller.Update(service, d.Id(), appservercontroller.ApplicationServer{ AppServerGroupIds: SetToStringSlice(d.Get("app_server_group_ids").(*schema.Set)), Name: d.Get("name").(string), Description: d.Get("description").(string), @@ -165,8 +189,13 @@ func resourceApplicationServerUpdate(d *schema.ResourceData, m interface{}) erro } func resourceApplicationServerDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).appservercontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.AppServerController + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting application server ID: %v\n", d.Id()) err := removeServerFromGroup(service, d.Id()) @@ -174,7 +203,7 @@ func resourceApplicationServerDelete(d *schema.ResourceData, m interface{}) erro return err } - if _, err = service.Delete(d.Id()); err != nil { + if _, err = appservercontroller.Delete(service, d.Id()); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil @@ -185,10 +214,10 @@ func resourceApplicationServerDelete(d *schema.ResourceData, m interface{}) erro return nil } -func removeServerFromGroup(service *appservercontroller.Service, serverID string) error { +func removeServerFromGroup(service *services.Service, serverID string) error { // Remove the reference to this server from server groups. - resp, _, err := service.Get(serverID) + resp, _, err := appservercontroller.Get(service, serverID) if err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { return nil @@ -201,7 +230,7 @@ func removeServerFromGroup(service *appservercontroller.Service, serverID string resp.AppServerGroupIds = make([]string, 0) log.Printf("[INFO] Updating server group ID: %s", serverID) - _, err = service.Update(serverID, *resp) + _, err = appservercontroller.Update(service, serverID, *resp) if err != nil { log.Printf("[ERROR] Failed to update application server ID: %s", serverID) return err diff --git a/zpa/resource_zpa_app_server_controller_test.go b/zpa/resource_zpa_app_server_controller_test.go index 169b3031..de7f84d6 100644 --- a/zpa/resource_zpa_app_server_controller_test.go +++ b/zpa/resource_zpa_app_server_controller_test.go @@ -66,7 +66,7 @@ func testAccCheckApplicationServerDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.appservercontroller.Get(rs.Primary.ID) + rule, _, err := appservercontroller.Get(apiClient.AppServerController, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -91,7 +91,7 @@ func testAccCheckApplicationServerExists(resource string, server *appservercontr } apiClient := testAccProvider.Meta().(*Client) - receivedServer, _, err := apiClient.appservercontroller.Get(rs.Primary.ID) + receivedServer, _, err := appservercontroller.Get(apiClient.AppServerController, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_application_segment.go b/zpa/resource_zpa_application_segment.go index e97b9aea..acb55368 100644 --- a/zpa/resource_zpa_application_segment.go +++ b/zpa/resource_zpa_application_segment.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" @@ -24,7 +25,13 @@ func resourceApplicationSegment() *schema.Resource { Delete: resourceApplicationSegmentDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.ApplicationSegment + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -32,7 +39,7 @@ func resourceApplicationSegment() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := applicationsegment.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -224,9 +231,15 @@ func resourceApplicationSegment() *schema.Resource { } func resourceApplicationSegmentCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegment + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - req := expandApplicationSegmentRequest(d, service, "") + req := expandApplicationSegmentRequest(d, zClient, "") if err := validateAppPorts(req.SelectConnectorCloseToApp, req.UDPAppPortRange, req.UDPPortRanges); err != nil { return err @@ -237,7 +250,8 @@ func resourceApplicationSegmentCreate(d *schema.ResourceData, m interface{}) err log.Println("[ERROR] Please provide a valid segment group for the application segment") return fmt.Errorf("please provide a valid segment group for the application segment") } - resp, _, err := service.Create(req) + + resp, _, err := applicationsegment.Create(service, req) if err != nil { return err } @@ -249,9 +263,15 @@ func resourceApplicationSegmentCreate(d *schema.ResourceData, m interface{}) err } func resourceApplicationSegmentRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ApplicationSegment - resp, _, err := service.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := applicationsegment.Get(service, d.Id()) if err != nil { if err.(*client.ErrorResponse).IsObjectNotFound() { log.Printf("[WARN] Removing application segment %s from state because it no longer exists in ZPA", d.Id()) @@ -314,10 +334,12 @@ func flattenAppServerGroupsSimple(serverGroups []applicationsegment.AppServerGro } func resourceApplicationSegmentUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + microTenantID := GetString(d.Get("microtenant_id")) + id := d.Id() log.Printf("[INFO] Updating application segment ID: %v\n", id) - req := expandApplicationSegmentRequest(d, service, id) + req := expandApplicationSegmentRequest(d, zClient, id) if err := validateAppPorts(req.SelectConnectorCloseToApp, req.UDPAppPortRange, req.UDPPortRanges); err != nil { return err @@ -328,31 +350,36 @@ func resourceApplicationSegmentUpdate(d *schema.ResourceData, m interface{}) err return fmt.Errorf("please provide a valid segment group for the application segment") } - if _, _, err := service.Get(id); err != nil { + service := zClient.ApplicationSegment + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, _, err := applicationsegment.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, req); err != nil { + if _, err := applicationsegment.Update(service, id, req); err != nil { return err } return resourceApplicationSegmentRead(d, m) } -func detachAppsFromAllPolicyRules(id string, policySetControllerService *policysetcontroller.Service) { +func detachAppsFromAllPolicyRules(id string, policySetControllerService *services.Service) { policyRulesDetchLock.Lock() defer policyRulesDetchLock.Unlock() var rules []policysetcontroller.PolicyRule types := []string{"ACCESS_POLICY", "TIMEOUT_POLICY", "SIEM_POLICY", "CLIENT_FORWARDING_POLICY", "INSPECTION_POLICY"} for _, t := range types { - policySet, _, err := policySetControllerService.GetByPolicyType(t) + policySet, _, err := policysetcontroller.GetByPolicyType(policySetControllerService, t) if err != nil { continue } - r, _, err := policySetControllerService.GetAllByType(t) + r, _, err := policysetcontroller.GetAllByType(policySetControllerService, t) if err != nil { continue } @@ -380,7 +407,7 @@ func detachAppsFromAllPolicyRules(id string, policySetControllerService *policys rule.Conditions = []policysetcontroller.Conditions{} } if changed { - if _, err := policySetControllerService.UpdateRule(rule.PolicySetID, rule.ID, &rule); err != nil { + if _, err := policysetcontroller.UpdateRule(policySetControllerService, rule.PolicySetID, rule.ID, &rule); err != nil { continue } } @@ -389,19 +416,25 @@ func detachAppsFromAllPolicyRules(id string, policySetControllerService *policys func resourceApplicationSegmentDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) - service := zClient.applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) - policySetControllerService := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + service := zClient.ApplicationSegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) + policySetControllerService := zClient.PolicySetController.WithMicroTenant(GetString(d.Get("microtenant_id"))) id := d.Id() log.Printf("[INFO] Deleting application segment with id %v\n", id) detachAppsFromAllPolicyRules(id, policySetControllerService) - if _, err := service.Delete(id); err != nil { + if _, err := applicationsegment.Delete(service, id); err != nil { return err } return nil } -func expandApplicationSegmentRequest(d *schema.ResourceData, service *applicationsegment.Service, id string) applicationsegment.ApplicationSegmentResource { +func expandApplicationSegmentRequest(d *schema.ResourceData, client *Client, id string) applicationsegment.ApplicationSegmentResource { + microTenantID := GetString(d.Get("microtenant_id")) + service := client.ApplicationSegment + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + details := applicationsegment.ApplicationSegmentResource{ ID: d.Id(), Name: d.Get("name").(string), @@ -432,7 +465,7 @@ func expandApplicationSegmentRequest(d *schema.ResourceData, service *applicatio remoteTCPAppPortRanges := []string{} remoteUDPAppPortRanges := []string{} if service != nil && id != "" { - resource, _, err := service.Get(id) + resource, _, err := applicationsegment.Get(service, id) if err == nil { remoteTCPAppPortRanges = resource.TCPPortRanges remoteUDPAppPortRanges = resource.UDPPortRanges diff --git a/zpa/resource_zpa_application_segment_browser_access.go b/zpa/resource_zpa_application_segment_browser_access.go index 00ab96c0..c1345a1d 100644 --- a/zpa/resource_zpa_application_segment_browser_access.go +++ b/zpa/resource_zpa_application_segment_browser_access.go @@ -8,9 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/browseraccess" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" ) func resourceApplicationSegmentBrowserAccess() *schema.Resource { @@ -21,7 +21,13 @@ func resourceApplicationSegmentBrowserAccess() *schema.Resource { Delete: resourceApplicationSegmentBrowserAccessDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - zClient := m.(*Client) + client := m.(*Client) + service := client.AppServerController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -29,7 +35,7 @@ func resourceApplicationSegmentBrowserAccess() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.browseraccess.GetByName(id) + resp, _, err := browseraccess.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -296,6 +302,12 @@ func resourceApplicationSegmentBrowserAccess() *schema.Resource { func resourceApplicationSegmentBrowserAccessCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BrowserAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandBrowserAccess(d, zClient, "") @@ -310,7 +322,7 @@ func resourceApplicationSegmentBrowserAccessCreate(d *schema.ResourceData, m int return fmt.Errorf("please provide a valid segment group for the application segment") } - browseraccess, _, err := zClient.browseraccess.Create(req) + browseraccess, _, err := browseraccess.Create(service, req) if err != nil { return err } @@ -323,8 +335,14 @@ func resourceApplicationSegmentBrowserAccessCreate(d *schema.ResourceData, m int func resourceApplicationSegmentBrowserAccessRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BrowserAccess - resp, _, err := zClient.browseraccess.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := browseraccess.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing browser access %s from state because it no longer exists in ZPA", d.Id()) @@ -381,6 +399,12 @@ func resourceApplicationSegmentBrowserAccessRead(d *schema.ResourceData, m inter func resourceApplicationSegmentBrowserAccessUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BrowserAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating browser access ID: %v\n", id) @@ -395,14 +419,14 @@ func resourceApplicationSegmentBrowserAccessUpdate(d *schema.ResourceData, m int return fmt.Errorf("please provide a valid segment group for the browser access application segment") } - if _, _, err := zClient.browseraccess.Get(id); err != nil { + if _, _, err := browseraccess.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.browseraccess.Update(id, &req); err != nil { + if _, err := browseraccess.Update(service, id, &req); err != nil { return err } @@ -411,28 +435,38 @@ func resourceApplicationSegmentBrowserAccessUpdate(d *schema.ResourceData, m int func resourceApplicationSegmentBrowserAccessDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BrowserAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + id := d.Id() segmentGroupID, ok := d.GetOk("segment_group_id") if ok && segmentGroupID != nil { gID, ok := segmentGroupID.(string) if ok && gID != "" { // detach it from segment group first - if err := detachBrowserAccessFromGroup(zClient, id, gID); err != nil { + if err := detachSegmentGroup(zClient, id, gID); err != nil { return err } } } log.Printf("[INFO] Deleting browser access application with id %v\n", id) - if _, err := zClient.browseraccess.Delete(id); err != nil { + if _, err := browseraccess.Delete(service, id); err != nil { return err } return nil } +/* func detachBrowserAccessFromGroup(client *Client, segmentID, segmentGroupID string) error { - log.Printf("[INFO] Detaching browser access %s from segment group: %s\n", segmentID, segmentGroupID) - segGroup, _, err := client.segmentgroup.Get(segmentGroupID) + log.Printf("[INFO] Detaching browser access %s from segment group: %s\n", segmentID, segmentGroupID) + service := client.SegmentGroup + + segGroup, _, err := segmentgroup.Get(service, segmentGroupID) if err != nil { log.Printf("[error] Error while getting segment group id: %s", segmentGroupID) return err @@ -444,9 +478,10 @@ func detachBrowserAccessFromGroup(client *Client, segmentID, segmentGroupID stri } } segGroup.Applications = adaptedApplications - _, err = client.segmentgroup.Update(segmentGroupID, segGroup) + _, err = segmentgroup.Update(service, segmentGroupID, segGroup) return err } +*/ func expandBrowserAccess(d *schema.ResourceData, zClient *Client, id string) browseraccess.BrowserAccess { details := browseraccess.BrowserAccess{ @@ -478,7 +513,13 @@ func expandBrowserAccess(d *schema.ResourceData, zClient *Client, id string) bro remoteTCPAppPortRanges := []string{} remoteUDPAppPortRanges := []string{} if zClient != nil && id != "" { - resource, _, err := zClient.applicationsegment.Get(id) + microTenantID := GetString(d.Get("microtenant_id")) + service := zClient.ApplicationSegment + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resource, _, err := applicationsegment.Get(service, id) if err == nil { remoteTCPAppPortRanges = resource.TCPPortRanges remoteUDPAppPortRanges = resource.UDPPortRanges diff --git a/zpa/resource_zpa_application_segment_browser_access_test.go b/zpa/resource_zpa_application_segment_browser_access_test.go index cdfa8fd4..5c43583b 100644 --- a/zpa/resource_zpa_application_segment_browser_access_test.go +++ b/zpa/resource_zpa_application_segment_browser_access_test.go @@ -72,14 +72,14 @@ func TestAccResourceApplicationSegmentBrowserAccessBasic(t *testing.T) { } func testAccCheckApplicationSegmentBrowserAccessDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*Client) + apiClient := testAccProvider.Meta().(*Client) for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPAApplicationSegmentBrowserAccess { continue } - _, _, err := client.browseraccess.GetByName(rs.Primary.Attributes["name"]) + _, _, err := browseraccess.GetByName(apiClient.BrowserAccess, rs.Primary.Attributes["name"]) if err == nil { return fmt.Errorf("Broser Access still exists") } @@ -100,7 +100,7 @@ func testAccCheckApplicationSegmentBrowserAccessExists(resource string, segment } apiClient := testAccProvider.Meta().(*Client) - receivedSegment, _, err := apiClient.browseraccess.Get(rs.Primary.ID) + receivedSegment, _, err := browseraccess.Get(apiClient.BrowserAccess, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_application_segment_inspection.go b/zpa/resource_zpa_application_segment_inspection.go index 6f70a5b9..acd0f376 100644 --- a/zpa/resource_zpa_application_segment_inspection.go +++ b/zpa/resource_zpa_application_segment_inspection.go @@ -10,7 +10,6 @@ import ( client "github.com/zscaler/zscaler-sdk-go/v2/zpa" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentinspection" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" ) func resourceApplicationSegmentInspection() *schema.Resource { @@ -21,7 +20,13 @@ func resourceApplicationSegmentInspection() *schema.Resource { Delete: resourceApplicationSegmentInspectionDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - zClient := m.(*Client) + client := m.(*Client) + service := client.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -29,7 +34,7 @@ func resourceApplicationSegmentInspection() *schema.Resource { // assume if the passed value is an int d.Set("id", id) } else { - resp, _, err := zClient.applicationsegmentinspection.GetByName(id) + resp, _, err := applicationsegmentinspection.GetByName(service, id) if err == nil { d.SetId(resp.ID) d.Set("id", resp.ID) @@ -289,6 +294,12 @@ func resourceApplicationSegmentInspection() *schema.Resource { func resourceApplicationSegmentInspectionCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandInspectionApplicationSegment(d, zClient, "") @@ -304,7 +315,7 @@ func resourceApplicationSegmentInspectionCreate(d *schema.ResourceData, m interf return fmt.Errorf("please provide a valid segment group for the application segment") } - resp, _, err := zClient.applicationsegmentinspection.Create(req) + resp, _, err := applicationsegmentinspection.Create(service, req) if err != nil { return err } @@ -317,8 +328,14 @@ func resourceApplicationSegmentInspectionCreate(d *schema.ResourceData, m interf func resourceApplicationSegmentInspectionRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := zClient.applicationsegmentinspection.Get(d.Id()) + resp, _, err := applicationsegmentinspection.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing inspection application segment %s from state because it no longer exists in ZPA", d.Id()) @@ -378,6 +395,12 @@ func flattenInspectionAppServerGroupsSimple(serverGroup []applicationsegmentinsp func resourceApplicationSegmentInspectionUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating inspection application segment ID: %v\n", id) @@ -394,14 +417,14 @@ func resourceApplicationSegmentInspectionUpdate(d *schema.ResourceData, m interf if err := validateProtocolAndCertID(d); err != nil { return err } - if _, _, err := zClient.applicationsegmentinspection.Get(id); err != nil { + if _, _, err := applicationsegmentinspection.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.applicationsegmentinspection.Update(id, &req); err != nil { + if _, err := applicationsegmentinspection.Update(service, id, &req); err != nil { return err } @@ -410,42 +433,53 @@ func resourceApplicationSegmentInspectionUpdate(d *schema.ResourceData, m interf func resourceApplicationSegmentInspectionDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentInspection + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + id := d.Id() segmentGroupID, ok := d.GetOk("segment_group_id") if ok && segmentGroupID != nil { gID, ok := segmentGroupID.(string) if ok && gID != "" { // detach it from segment group first - if err := detachInspectionPortalsFromGroup(zClient, id, gID); err != nil { + if err := detachSegmentGroup(zClient, id, gID); err != nil { return err } } } log.Printf("[INFO] Deleting inspection application segment with id %v\n", id) - if _, err := zClient.applicationsegmentinspection.Delete(id); err != nil { + if _, err := applicationsegmentinspection.Delete(service, id); err != nil { return err } return nil } -func detachInspectionPortalsFromGroup(client *Client, segmentID, segmentGroupID string) error { - log.Printf("[INFO] Detaching inspection application segment %s from segment group: %s\n", segmentID, segmentGroupID) - segGroup, _, err := client.segmentgroup.Get(segmentGroupID) - if err != nil { - log.Printf("[error] Error while getting segment group id: %s", segmentGroupID) - return err - } - adaptedApplications := []segmentgroup.Application{} - for _, app := range segGroup.Applications { - if app.ID != segmentID { - adaptedApplications = append(adaptedApplications, app) +/* + func detachInspectionPortalsFromGroup(client *Client, segmentID, segmentGroupID string) error { + log.Printf("[INFO] Detaching inspection application segment %s from segment group: %s\n", segmentID, segmentGroupID) + service := client.SegmentGroup + + segGroup, _, err := segmentgroup.Get(service, segmentGroupID) + if err != nil { + log.Printf("[error] Error while getting segment group id: %s", segmentGroupID) + return err + } + adaptedApplications := []segmentgroup.Application{} + for _, app := range segGroup.Applications { + if app.ID != segmentID { + adaptedApplications = append(adaptedApplications, app) + } } + segGroup.Applications = adaptedApplications + _, err = segmentgroup.Update(service, segmentGroupID, segGroup) + return err } - segGroup.Applications = adaptedApplications - _, err = client.segmentgroup.Update(segmentGroupID, segGroup) - return err -} +*/ func expandInspectionApplicationSegment(d *schema.ResourceData, zClient *Client, id string) applicationsegmentinspection.AppSegmentInspection { details := applicationsegmentinspection.AppSegmentInspection{ @@ -487,7 +521,13 @@ func expandInspectionApplicationSegment(d *schema.ResourceData, zClient *Client, remoteTCPAppPortRanges := []string{} remoteUDPAppPortRanges := []string{} if zClient != nil && id != "" { - resource, _, err := zClient.applicationsegment.Get(id) + microTenantID := GetString(d.Get("microtenant_id")) + service := zClient.ApplicationSegmentInspection + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resource, _, err := applicationsegmentinspection.Get(service, id) if err == nil { remoteTCPAppPortRanges = resource.TCPPortRanges remoteUDPAppPortRanges = resource.UDPPortRanges diff --git a/zpa/resource_zpa_application_segment_inspection_test.go b/zpa/resource_zpa_application_segment_inspection_test.go index ca9681a3..ca3f7223 100644 --- a/zpa/resource_zpa_application_segment_inspection_test.go +++ b/zpa/resource_zpa_application_segment_inspection_test.go @@ -68,14 +68,14 @@ func TestAccResourceApplicationSegmentInspectionBasic(t *testing.T) { } func testAccCheckApplicationSegmentInspectionDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*Client) + apiClient := testAccProvider.Meta().(*Client) for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPAApplicationSegmentInspection { continue } - _, _, err := client.applicationsegmentinspection.GetByName(rs.Primary.Attributes["name"]) + _, _, err := applicationsegmentinspection.GetByName(apiClient.ApplicationSegmentInspection, rs.Primary.Attributes["name"]) if err == nil { return fmt.Errorf("Inspection Application Segment Inspection still exists") } @@ -96,7 +96,7 @@ func testAccCheckApplicationSegmentInspectionExists(resource string, segment *ap } apiClient := testAccProvider.Meta().(*Client) - receivedSegment, _, err := apiClient.applicationsegmentinspection.Get(rs.Primary.ID) + receivedSegment, _, err := applicationsegmentinspection.Get(apiClient.ApplicationSegmentInspection, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_application_segment_pra.go b/zpa/resource_zpa_application_segment_pra.go index b1e213c5..0bb27cec 100644 --- a/zpa/resource_zpa_application_segment_pra.go +++ b/zpa/resource_zpa_application_segment_pra.go @@ -13,7 +13,6 @@ import ( client "github.com/zscaler/zscaler-sdk-go/v2/zpa" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegmentpra" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" - "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" ) func resourceApplicationSegmentPRA() *schema.Resource { @@ -24,7 +23,8 @@ func resourceApplicationSegmentPRA() *schema.Resource { Delete: resourceApplicationSegmentPRADelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - zClient := m.(*Client) + client := m.(*Client) + service := client.ApplicationSegmentPRA id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -32,7 +32,7 @@ func resourceApplicationSegmentPRA() *schema.Resource { // assume if the passed value is an int d.Set("id", id) } else { - resp, _, err := zClient.applicationsegmentpra.GetByName(id) + resp, _, err := applicationsegmentpra.GetByName(service, id) if err == nil { d.SetId(resp.ID) d.Set("id", resp.ID) @@ -302,6 +302,7 @@ func resourceApplicationSegmentPRA() *schema.Resource { func resourceApplicationSegmentPRACreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentPRA req := expandSRAApplicationSegment(d, zClient, "") if err := checkForPRAPortsOverlap(zClient, req); err != nil { @@ -313,7 +314,7 @@ func resourceApplicationSegmentPRACreate(d *schema.ResourceData, m interface{}) } log.Printf("[INFO] Creating application segment request\n%+v\n", req) - resp, _, err := zClient.applicationsegmentpra.Create(req) + resp, _, err := applicationsegmentpra.Create(service, req) if err != nil { log.Printf("[ERROR] Failed to create application segment: %s", err) return err @@ -326,7 +327,7 @@ func resourceApplicationSegmentPRACreate(d *schema.ResourceData, m interface{}) time.Sleep(5 * time.Second) // Explicitly call GET using the ID to fetch the latest resource state - _, _, err = zClient.applicationsegmentpra.Get(resp.ID) + _, _, err = applicationsegmentpra.Get(service, resp.ID) if err != nil { log.Printf("[ERROR] Failed to fetch application segment after creation: %s", err) return err @@ -338,8 +339,9 @@ func resourceApplicationSegmentPRACreate(d *schema.ResourceData, m interface{}) func resourceApplicationSegmentPRARead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentPRA - resp, _, err := zClient.applicationsegmentpra.Get(d.Id()) + resp, _, err := applicationsegmentpra.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing sra application segment %s from state because it no longer exists in ZPA", d.Id()) @@ -403,6 +405,7 @@ func flattenPRAAppServerGroupsSimple(serverGroup []applicationsegmentpra.AppServ func resourceApplicationSegmentPRAUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentPRA id := d.Id() log.Printf("[INFO] Updating pra application segment ID: %v\n", id) @@ -416,7 +419,7 @@ func resourceApplicationSegmentPRAUpdate(d *schema.ResourceData, m interface{}) return err } - if _, _, err := zClient.applicationsegmentpra.Get(id); err != nil { + if _, _, err := applicationsegmentpra.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil @@ -424,7 +427,7 @@ func resourceApplicationSegmentPRAUpdate(d *schema.ResourceData, m interface{}) } // Perform the update - _, err := zClient.applicationsegmentpra.Update(id, &req) + _, err := applicationsegmentpra.Update(service, id, &req) if err != nil { return err } @@ -433,7 +436,7 @@ func resourceApplicationSegmentPRAUpdate(d *schema.ResourceData, m interface{}) time.Sleep(5 * time.Second) // Fetch the latest resource state after the update - _, _, err = zClient.applicationsegmentpra.Get(id) + _, _, err = applicationsegmentpra.Get(service, id) if err != nil { log.Printf("[ERROR] Failed to fetch application segment after update: %s", err) return err @@ -445,25 +448,28 @@ func resourceApplicationSegmentPRAUpdate(d *schema.ResourceData, m interface{}) func resourceApplicationSegmentPRADelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.ApplicationSegmentPRA + id := d.Id() segmentGroupID, ok := d.GetOk("segment_group_id") if ok && segmentGroupID != nil { gID, ok := segmentGroupID.(string) if ok && gID != "" { // detach it from segment group first - if err := detachSraPortalsFromGroup(zClient, id, gID); err != nil { + if err := detachSegmentGroup(zClient, id, gID); err != nil { return err } } } log.Printf("[INFO] Deleting sra application segment with id %v\n", id) - if _, err := zClient.applicationsegmentpra.Delete(id); err != nil { + if _, err := applicationsegmentpra.Delete(service, id); err != nil { return err } return nil } +/* func detachSraPortalsFromGroup(client *Client, segmentID, segmentGroupID string) error { log.Printf("[INFO] Detaching pra application segment %s from segment group: %s\n", segmentID, segmentGroupID) segGroup, _, err := client.segmentgroup.Get(segmentGroupID) @@ -481,6 +487,7 @@ func detachSraPortalsFromGroup(client *Client, segmentID, segmentGroupID string) _, err = client.segmentgroup.Update(segmentGroupID, segGroup) return err } +*/ func expandSRAApplicationSegment(d *schema.ResourceData, zClient *Client, id string) applicationsegmentpra.AppSegmentPRA { details := applicationsegmentpra.AppSegmentPRA{ @@ -520,7 +527,13 @@ func expandSRAApplicationSegment(d *schema.ResourceData, zClient *Client, id str remoteTCPAppPortRanges := []string{} remoteUDPAppPortRanges := []string{} if zClient != nil && id != "" { - resource, _, err := zClient.applicationsegment.Get(id) + microTenantID := GetString(d.Get("microtenant_id")) + service := zClient.ApplicationSegmentInspection + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resource, _, err := applicationsegmentpra.Get(service, id) if err == nil { remoteTCPAppPortRanges = resource.TCPPortRanges remoteUDPAppPortRanges = resource.UDPPortRanges @@ -662,16 +675,24 @@ func flattenAppsConfig(d *schema.ResourceData, appConfigs []applicationsegmentpr func checkForPRAPortsOverlap(client *Client, app applicationsegmentpra.AppSegmentPRA) error { time.Sleep(time.Second * time.Duration(rand.Intn(5))) - apps, _, err := client.browseraccess.GetAll() + + microTenantID := app.MicroTenantID + service := client.ApplicationSegmentPRA + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + apps, _, err := applicationsegmentpra.GetAll(service) if err != nil { return err } for _, app2 := range apps { if found, common := sliceHasCommon(app.DomainNames, app2.DomainNames); found && app2.ID != app.ID && app2.Name != app.Name { - // check for udp ports + // check for TCP ports if overlap, o1, o2 := PRAPortOverlap(app.TCPPortRanges, app2.TCPPortRanges); overlap { return fmt.Errorf("found TCP overlapping ports: %v of application %s with %v of application %s (%s) with common domain name %s", o1, app.Name, o2, app2.Name, app2.ID, common) } + // check for UDP ports if overlap, o1, o2 := PRAPortOverlap(app.UDPPortRanges, app2.UDPPortRanges); overlap { return fmt.Errorf("found UDP overlapping ports: %v of application %s with %v of application %s (%s) with common domain name %s", o1, app.Name, o2, app2.Name, app2.ID, common) } diff --git a/zpa/resource_zpa_application_segment_pra_test.go b/zpa/resource_zpa_application_segment_pra_test.go index 2fd6635c..73ac7042 100644 --- a/zpa/resource_zpa_application_segment_pra_test.go +++ b/zpa/resource_zpa_application_segment_pra_test.go @@ -68,14 +68,14 @@ func TestAccResourceApplicationSegmentPRABasic(t *testing.T) { } func testAccCheckApplicationSegmentPRADestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*Client) + apiClient := testAccProvider.Meta().(*Client) for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPAApplicationSegmentPRA { continue } - _, _, err := client.applicationsegmentpra.GetByName(rs.Primary.Attributes["name"]) + _, _, err := applicationsegmentpra.GetByName(apiClient.ApplicationSegmentPRA, rs.Primary.Attributes["name"]) if err == nil { return fmt.Errorf("Application Segment PRA still exists") } @@ -96,7 +96,7 @@ func testAccCheckApplicationSegmentPRAExists(resource string, segment *applicati } apiClient := testAccProvider.Meta().(*Client) - receivedSegment, _, err := apiClient.applicationsegmentpra.Get(rs.Primary.ID) + receivedSegment, _, err := applicationsegmentpra.Get(apiClient.ApplicationSegmentPRA, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_application_segment_test.go b/zpa/resource_zpa_application_segment_test.go index 368f81e0..d28ad4c6 100644 --- a/zpa/resource_zpa_application_segment_test.go +++ b/zpa/resource_zpa_application_segment_test.go @@ -72,14 +72,14 @@ func TestAccResourceApplicationSegmentBasic(t *testing.T) { } func testAccCheckApplicationSegmentDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*Client) + apiClient := testAccProvider.Meta().(*Client) for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPAApplicationSegment { continue } - _, _, err := client.applicationsegment.GetByName(rs.Primary.Attributes["name"]) + _, _, err := applicationsegment.GetByName(apiClient.ApplicationSegment, rs.Primary.Attributes["name"]) if err == nil { return fmt.Errorf("Application Segment still exists") } @@ -98,8 +98,8 @@ func testAccCheckApplicationSegmentExists(resource string, segment *applications if rs.Primary.ID == "" { return fmt.Errorf("no Application Segment ID is set") } - client := testAccProvider.Meta().(*Client) - receivedApp, _, err := client.applicationsegment.Get(rs.Primary.ID) + apiClient := testAccProvider.Meta().(*Client) + receivedApp, _, err := applicationsegment.Get(apiClient.ApplicationSegment, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Received error: %s", resource, err) } diff --git a/zpa/resource_zpa_ba_certificate.go b/zpa/resource_zpa_ba_certificate.go index 2e42eacb..86c2ef2e 100644 --- a/zpa/resource_zpa_ba_certificate.go +++ b/zpa/resource_zpa_ba_certificate.go @@ -54,12 +54,18 @@ func resourceBaCertificate() *schema.Resource { } func resourceBaCertificateCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).bacertificate.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.BACertificate + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandBaCertificate(d) log.Printf("[INFO] Creating certificate with request\n%+v\n", req) - baCertificate, _, err := service.Create(req) + baCertificate, _, err := bacertificate.Create(service, req) if err != nil { return err } @@ -71,8 +77,14 @@ func resourceBaCertificateCreate(d *schema.ResourceData, m interface{}) error { func resourceBaCertificateRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.BACertificate + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := zClient.bacertificate.Get(d.Id()) + resp, _, err := bacertificate.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing ba certificate %s from state because it no longer exists in ZPA", d.Id()) @@ -93,11 +105,17 @@ func resourceBaCertificateRead(d *schema.ResourceData, m interface{}) error { } func resourceBaCertificateDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).bacertificate.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.BACertificate + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting certificate ID: %v\n", d.Id()) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := bacertificate.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_ba_certificate_test.go b/zpa/resource_zpa_ba_certificate_test.go index f429e900..6ccc707b 100644 --- a/zpa/resource_zpa_ba_certificate_test.go +++ b/zpa/resource_zpa_ba_certificate_test.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/bacertificate" ) func TestAccResourceBaCertificate_basic(t *testing.T) { @@ -95,7 +96,7 @@ func testAccCheckBaCertificateExists(n string) resource.TestCheckFunc { // Assume you have an API client set up and it has a method to get a certificate by ID apiClient := testAccProvider.Meta().(*Client) - _, _, err := apiClient.bacertificate.Get(rs.Primary.ID) + _, _, err := bacertificate.Get(apiClient.BACertificate, rs.Primary.ID) if err != nil { return fmt.Errorf("error fetching certificate with resource ID [%s] from API: %s", rs.Primary.ID, err) } @@ -112,7 +113,7 @@ func testAccBaCertificateDestroy(s *terraform.State) error { continue } - baCertificate, _, err := apiClient.bacertificate.Get(rs.Primary.ID) + baCertificate, _, err := bacertificate.Get(apiClient.BACertificate, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) diff --git a/zpa/resource_zpa_cloud_browser_isolation_banner.go b/zpa/resource_zpa_cloud_browser_isolation_banner.go index cab63e12..3310278b 100644 --- a/zpa/resource_zpa_cloud_browser_isolation_banner.go +++ b/zpa/resource_zpa_cloud_browser_isolation_banner.go @@ -18,6 +18,7 @@ func resourceCBIBanners() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.CBIBannerController id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -25,7 +26,7 @@ func resourceCBIBanners() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.cbibannercontroller.GetByName(id) + resp, _, err := cbibannercontroller.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -82,11 +83,12 @@ func resourceCBIBanners() *schema.Resource { func resourceCBIBannersCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIBannerController req := expandCBIBanner(d) log.Printf("[INFO] Creating cbi banner with request\n%+v\n", req) - cbiBanner, _, err := zClient.cbibannercontroller.Create(&req) + cbiBanner, _, err := cbibannercontroller.Create(service, &req) if err != nil { return err } @@ -98,8 +100,9 @@ func resourceCBIBannersCreate(d *schema.ResourceData, m interface{}) error { func resourceCBIBannersRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIBannerController - resp, _, err := zClient.cbibannercontroller.Get(d.Id()) + resp, _, err := cbibannercontroller.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing cbi certificate %s from state because it no longer exists in ZPA", d.Id()) @@ -125,19 +128,20 @@ func resourceCBIBannersRead(d *schema.ResourceData, m interface{}) error { func resourceCBIBannersUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIBannerController id := d.Id() log.Printf("[INFO] Updating cbi certificate ID: %v\n", id) req := expandCBIBanner(d) - if _, _, err := zClient.cbibannercontroller.Get(id); err != nil { + if _, _, err := cbibannercontroller.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.cbibannercontroller.Update(id, &req); err != nil { + if _, err := cbibannercontroller.Update(service, id, &req); err != nil { return err } @@ -146,10 +150,11 @@ func resourceCBIBannersUpdate(d *schema.ResourceData, m interface{}) error { func resourceCBIBannersDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIBannerController log.Printf("[INFO] Deleting cbi banner ID: %v\n", d.Id()) - if _, err := zClient.cbibannercontroller.Delete(d.Id()); err != nil { + if _, err := cbibannercontroller.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_cloud_browser_isolation_banner_test.go b/zpa/resource_zpa_cloud_browser_isolation_banner_test.go index 4a79de1b..63b552b7 100644 --- a/zpa/resource_zpa_cloud_browser_isolation_banner_test.go +++ b/zpa/resource_zpa_cloud_browser_isolation_banner_test.go @@ -68,7 +68,7 @@ func testAccCheckCBIBannerDestroy(s *terraform.State) error { continue } - banner, _, err := apiClient.cbibannercontroller.Get(rs.Primary.ID) + banner, _, err := cbibannercontroller.Get(apiClient.CBIBannerController, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -93,7 +93,7 @@ func testAccCheckCBIBannerExists(resource string, banner *cbibannercontroller.CB } apiClient := testAccProvider.Meta().(*Client) - receivedBanner, _, err := apiClient.cbibannercontroller.Get(rs.Primary.ID) + receivedBanner, _, err := cbibannercontroller.Get(apiClient.CBIBannerController, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_cloud_browser_isolation_certificate.go b/zpa/resource_zpa_cloud_browser_isolation_certificate.go index f5b55aa0..bd0984d5 100644 --- a/zpa/resource_zpa_cloud_browser_isolation_certificate.go +++ b/zpa/resource_zpa_cloud_browser_isolation_certificate.go @@ -18,6 +18,12 @@ func resourceCBICertificates() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.CBICertificateController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -25,7 +31,7 @@ func resourceCBICertificates() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.cbicertificatecontroller.GetByName(id) + resp, _, err := cbicertificatecontroller.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -55,11 +61,17 @@ func resourceCBICertificates() *schema.Resource { func resourceCBICertificatesCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBICertificateController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandCBICertificate(d) log.Printf("[INFO] Creating cbi certificate with request\n%+v\n", req) - cbiCertificate, _, err := zClient.cbicertificatecontroller.Create(&req) + cbiCertificate, _, err := cbicertificatecontroller.Create(service, &req) if err != nil { return err } @@ -71,8 +83,14 @@ func resourceCBICertificatesCreate(d *schema.ResourceData, m interface{}) error func resourceCBICertificatesRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBICertificateController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := zClient.cbicertificatecontroller.Get(d.Id()) + resp, _, err := cbicertificatecontroller.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing cbi certificate %s from state because it no longer exists in ZPA", d.Id()) @@ -93,19 +111,25 @@ func resourceCBICertificatesRead(d *schema.ResourceData, m interface{}) error { func resourceCBICertificatesUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBICertificateController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating cbi certificate ID: %v\n", id) req := expandCBICertificate(d) - if _, _, err := zClient.cbicertificatecontroller.Get(id); err != nil { + if _, _, err := cbicertificatecontroller.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.cbicertificatecontroller.Update(id, &req); err != nil { + if _, err := cbicertificatecontroller.Update(service, id, &req); err != nil { return err } @@ -114,10 +138,16 @@ func resourceCBICertificatesUpdate(d *schema.ResourceData, m interface{}) error func resourceCBICertificatesDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBICertificateController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting cbi certificate ID: %v\n", d.Id()) - if _, err := zClient.cbicertificatecontroller.Delete(d.Id()); err != nil { + if _, err := cbicertificatecontroller.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_cloud_browser_isolation_certificate_test.go b/zpa/resource_zpa_cloud_browser_isolation_certificate_test.go index 2ad67bb1..731fe2c7 100644 --- a/zpa/resource_zpa_cloud_browser_isolation_certificate_test.go +++ b/zpa/resource_zpa_cloud_browser_isolation_certificate_test.go @@ -111,7 +111,7 @@ func testAccCheckCBICertificateExists(resource string, certificate *cbicertifica } apiClient := testAccProvider.Meta().(*Client) - receivedCertificate, _, err := apiClient.cbicertificatecontroller.Get(rs.Primary.ID) + receivedCertificate, _, err := cbicertificatecontroller.Get(apiClient.CBICertificateController, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } @@ -129,7 +129,7 @@ func testAccCheckCBICertificateDestroy(s *terraform.State) error { continue } - cbiCertificate, _, err := apiClient.cbicertificatecontroller.Get(rs.Primary.ID) + cbiCertificate, _, err := cbicertificatecontroller.Get(apiClient.CBICertificateController, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) diff --git a/zpa/resource_zpa_cloud_browser_isolation_external_profile.go b/zpa/resource_zpa_cloud_browser_isolation_external_profile.go index 024aaf77..4bc065d2 100644 --- a/zpa/resource_zpa_cloud_browser_isolation_external_profile.go +++ b/zpa/resource_zpa_cloud_browser_isolation_external_profile.go @@ -20,6 +20,7 @@ func resourceCBIExternalProfile() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.CBIProfileController id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -27,7 +28,7 @@ func resourceCBIExternalProfile() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.cbiprofilecontroller.GetByName(id) + resp, _, err := cbiprofilecontroller.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -141,13 +142,14 @@ func resourceCBIExternalProfileCreate(d *schema.ResourceData, m interface{}) err } zClient := m.(*Client) + service := zClient.CBIProfileController req := expandCBIExternalProfile(d) req.Regions = nil req.Certificates = nil req.Banner = nil log.Printf("[INFO] Creating cbi external profile with request\n%+v\n", req) - cbiProfile, _, err := zClient.cbiprofilecontroller.Create(&req) + cbiProfile, _, err := cbiprofilecontroller.Create(service, &req) if err != nil { return err } @@ -159,8 +161,9 @@ func resourceCBIExternalProfileCreate(d *schema.ResourceData, m interface{}) err func resourceCBIExternalProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIProfileController - resp, _, err := zClient.cbiprofilecontroller.Get(d.Id()) + resp, _, err := cbiprofilecontroller.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing cbi profile %s from state because it no longer exists in ZPA", d.Id()) @@ -211,19 +214,20 @@ func resourceCBIExternalProfileUpdate(d *schema.ResourceData, m interface{}) err } zClient := m.(*Client) + service := zClient.CBIProfileController id := d.Id() log.Printf("[INFO] Updating cbi profile ID: %v\n", id) req := expandCBIExternalProfile(d) - if _, _, err := zClient.cbiprofilecontroller.Get(id); err != nil { + if _, _, err := cbiprofilecontroller.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.cbiprofilecontroller.Update(id, &req); err != nil { + if _, err := cbiprofilecontroller.Update(service, id, &req); err != nil { return err } @@ -232,10 +236,11 @@ func resourceCBIExternalProfileUpdate(d *schema.ResourceData, m interface{}) err func resourceCBIExternalProfileDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.CBIProfileController log.Printf("[INFO] Deleting cbi profile ID: %v\n", d.Id()) - if _, err := zClient.cbiprofilecontroller.Delete(d.Id()); err != nil { + if _, err := cbiprofilecontroller.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_emergency_access.go b/zpa/resource_zpa_emergency_access.go index 462cf20b..6c9d5ae1 100644 --- a/zpa/resource_zpa_emergency_access.go +++ b/zpa/resource_zpa_emergency_access.go @@ -46,11 +46,17 @@ func resourceEmergencyAccess() *schema.Resource { func resourceEmergencyAccessCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.EmergencyAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandEmergencyAccess(d) log.Printf("[INFO] Creating emergency access user with request\n%+v\n", req) - emgAccess, _, err := zClient.emergencyaccess.Create(&req) + emgAccess, _, err := emergencyaccess.Create(service, &req) if err != nil { return err } @@ -62,8 +68,14 @@ func resourceEmergencyAccessCreate(d *schema.ResourceData, m interface{}) error func resourceEmergencyAccessRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.EmergencyAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := zClient.emergencyaccess.Get(d.Id()) + resp, _, err := emergencyaccess.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing emergency access user %s from state because it no longer exists in ZPA", d.Id()) @@ -84,19 +96,25 @@ func resourceEmergencyAccessRead(d *schema.ResourceData, m interface{}) error { func resourceEmergencyAccessUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.EmergencyAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating emergency access user ID: %v\n", id) req := expandEmergencyAccess(d) - if _, _, err := zClient.emergencyaccess.Get(id); err != nil { + if _, _, err := emergencyaccess.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.emergencyaccess.Update(id, &req); err != nil { + if _, err := emergencyaccess.Update(service, id, &req); err != nil { return err } @@ -105,10 +123,16 @@ func resourceEmergencyAccessUpdate(d *schema.ResourceData, m interface{}) error func resourceEmergencyAccessDeactivated(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.EmergencyAccess + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deactivated Emergency Access User ID: %v\n", d.Id()) - if _, err := zClient.emergencyaccess.Deactivate(d.Id()); err != nil { + if _, err := emergencyaccess.Deactivate(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_inspection_custom_controls.go b/zpa/resource_zpa_inspection_custom_controls.go index 16cc75ee..17f8b2d1 100644 --- a/zpa/resource_zpa_inspection_custom_controls.go +++ b/zpa/resource_zpa_inspection_custom_controls.go @@ -21,6 +21,7 @@ func resourceInspectionCustomControls() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.InspectionCustomControls id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -28,7 +29,7 @@ func resourceInspectionCustomControls() *schema.Resource { // assume if the passed value is an int d.Set("custom_id", id) } else { - resp, _, err := zClient.inspection_custom_controls.GetByName(id) + resp, _, err := inspection_custom_controls.GetByName(service, id) if err == nil { d.SetId(resp.ID) d.Set("custom_id", resp.ID) @@ -251,30 +252,40 @@ func resourceInspectionCustomControls() *schema.Resource { } } -func updateInspectionProfile(zClient *Client, customControlId string, req *inspection_custom_controls.InspectionCustomControl) { - obj, _, err := zClient.inspection_custom_controls.Get(customControlId) - if err == nil { - for _, i := range req.AssociatedInspectionProfileNames { - profile, _, err := zClient.inspection_profile.Get(i.ID) - if err != nil { - continue - } - zClient.inspection_profile.Patch(profile.ID, &inspection_profile.InspectionProfile{ - CustomControls: []inspection_profile.InspectionCustomControl{ - { - ID: obj.ID, - Action: req.Action, - ActionValue: req.ActionValue, - }, +func updateInspectionProfile(zClient *Client, customControlID string, req *inspection_custom_controls.InspectionCustomControl) { + obj, _, err := inspection_custom_controls.Get(zClient.InspectionCustomControls, customControlID) + if err != nil { + log.Printf("[ERROR] Error fetching inspection custom control: %s", err) + return + } + + for _, profileName := range req.AssociatedInspectionProfileNames { + profile, _, err := inspection_profile.Get(zClient.InspectionProfile, profileName.ID) + if err != nil { + log.Printf("[ERROR] Error fetching inspection profile: %s", err) + continue + } + + updateProfile := &inspection_profile.InspectionProfile{ + CustomControls: []inspection_profile.InspectionCustomControl{ + { + ID: obj.ID, + Action: req.Action, + ActionValue: req.ActionValue, }, - PredefinedControls: profile.PredefinedControls, - }) + }, + PredefinedControls: profile.PredefinedControls, + } + + if _, err := inspection_profile.Patch(zClient.InspectionProfile, profile.ID, updateProfile); err != nil { + log.Printf("[ERROR] Error patching inspection profile: %s", err) } } } func resourceInspectionCustomControlsCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionCustomControls req := expandInspectionCustomControls(d) log.Printf("[INFO] Creating custom inspection control with request\n%+v\n", req) @@ -284,7 +295,7 @@ func resourceInspectionCustomControlsCreate(d *schema.ResourceData, m interface{ if err := validateRules(req); err != nil { return err } - resp, _, err := zClient.inspection_custom_controls.Create(req) + resp, _, err := inspection_custom_controls.Create(service, req) if err != nil { return err } @@ -297,8 +308,9 @@ func resourceInspectionCustomControlsCreate(d *schema.ResourceData, m interface{ func resourceInspectionCustomControlsRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionCustomControls - resp, _, err := zClient.inspection_custom_controls.Get(d.Id()) + resp, _, err := inspection_custom_controls.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing custom inspection control %s from state because it no longer exists in ZPA", d.Id()) @@ -330,6 +342,7 @@ func resourceInspectionCustomControlsRead(d *schema.ResourceData, m interface{}) func resourceInspectionCustomControlsUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionCustomControls id := d.Id() log.Printf("[INFO] Updating custom inspection control ID: %v\n", id) @@ -338,14 +351,14 @@ func resourceInspectionCustomControlsUpdate(d *schema.ResourceData, m interface{ return err } - if _, _, err := zClient.inspection_custom_controls.Get(id); err != nil { + if _, _, err := inspection_custom_controls.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.inspection_custom_controls.Update(id, &req); err != nil { + if _, err := inspection_custom_controls.Update(service, id, &req); err != nil { return err } updateInspectionProfile(zClient, id, &req) @@ -354,15 +367,16 @@ func resourceInspectionCustomControlsUpdate(d *schema.ResourceData, m interface{ func resourceInspectionCustomControlsDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionCustomControls log.Printf("[INFO] Deleting custom inspection control ID: %v\n", d.Id()) // First de-associate it from all inspection profiles - c, _, err := zClient.inspection_custom_controls.Get(d.Id()) + c, _, err := inspection_custom_controls.Get(service, d.Id()) if err != nil { return err } for _, inspectionProfile := range c.AssociatedInspectionProfileNames { - inspectionProfileRemote, _, err := zClient.inspection_profile.Get(inspectionProfile.ID) + inspectionProfileRemote, _, err := inspection_profile.Get(service, inspectionProfile.ID) if err != nil { continue } @@ -375,9 +389,9 @@ func resourceInspectionCustomControlsDelete(d *schema.ResourceData, m interface{ new = append(new, tmp) } inspectionProfileRemote.CustomControls = new - zClient.inspection_profile.Update(inspectionProfile.ID, inspectionProfileRemote) + inspection_profile.Update(service, inspectionProfile.ID, inspectionProfileRemote) } - if _, err := zClient.inspection_custom_controls.Delete(d.Id()); err != nil { + if _, err := inspection_custom_controls.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_inspection_custom_controls_test.go b/zpa/resource_zpa_inspection_custom_controls_test.go index 0b44717a..efebb34e 100644 --- a/zpa/resource_zpa_inspection_custom_controls_test.go +++ b/zpa/resource_zpa_inspection_custom_controls_test.go @@ -67,7 +67,7 @@ func testAccCheckInspectionCustomControlsDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.inspection_custom_controls.Get(rs.Primary.ID) + rule, _, err := inspection_custom_controls.Get(apiClient.InspectionCustomControls, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -92,7 +92,7 @@ func testAccCheckInspectionCustomControlsExists(resource string, rule *inspectio } apiClient := testAccProvider.Meta().(*Client) - receivedControl, _, err := apiClient.inspection_custom_controls.Get(rs.Primary.ID) + receivedControl, _, err := inspection_custom_controls.Get(apiClient.InspectionCustomControls, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_inspection_profile.go b/zpa/resource_zpa_inspection_profile.go index 24134391..19397021 100644 --- a/zpa/resource_zpa_inspection_profile.go +++ b/zpa/resource_zpa_inspection_profile.go @@ -21,6 +21,7 @@ func resourceInspectionProfile() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.InspectionProfile id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -28,7 +29,7 @@ func resourceInspectionProfile() *schema.Resource { // assume if the passed value is an int d.Set("profile_id", id) } else { - resp, _, err := zClient.inspection_profile.GetByName(id) + resp, _, err := inspection_profile.GetByName(service, id) if err == nil { d.SetId(resp.ID) d.Set("profile_id", resp.ID) @@ -253,6 +254,7 @@ func validateInspectionProfile(profile *inspection_profile.InspectionProfile) er func resourceInspectionProfileCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionProfile req := expandInspectionProfile(d) log.Printf("[INFO] Creating inspection profile with request\n%+v\n", req) @@ -260,7 +262,7 @@ func resourceInspectionProfileCreate(d *schema.ResourceData, m interface{}) erro return err } // injectPredefinedControls(zClient, &req) - resp, _, err := zClient.inspection_profile.Create(req) + resp, _, err := inspection_profile.Create(service, req) if err != nil { return err } @@ -268,19 +270,20 @@ func resourceInspectionProfileCreate(d *schema.ResourceData, m interface{}) erro d.SetId(resp.ID) if v, ok := d.GetOk("associate_all_controls"); ok && v.(bool) { - p, _, err := zClient.inspection_profile.Get(resp.ID) + p, _, err := inspection_profile.Get(service, resp.ID) if err != nil { return err } - zClient.inspection_profile.PutAssociate(resp.ID, p) + inspection_profile.PutAssociate(service, resp.ID, p) } return resourceInspectionProfileRead(d, m) } func resourceInspectionProfileRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionProfile - resp, _, err := zClient.inspection_profile.Get(d.Id()) + resp, _, err := inspection_profile.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing inspection profile %s from state because it no longer exists in ZPA", d.Id()) @@ -367,6 +370,7 @@ func flattenCustomControlsSimple(customControl []inspection_profile.InspectionCu func resourceInspectionProfileUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionProfile id := d.Id() log.Printf("[INFO] Updating inspection profile ID: %v\n", id) @@ -375,7 +379,7 @@ func resourceInspectionProfileUpdate(d *schema.ResourceData, m interface{}) erro return err } - if _, _, err := zClient.inspection_profile.Get(id); err != nil { + if _, _, err := inspection_profile.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil @@ -383,25 +387,26 @@ func resourceInspectionProfileUpdate(d *schema.ResourceData, m interface{}) erro } // injectPredefinedControls(zClient, &req) - if _, err := zClient.inspection_profile.Update(id, &req); err != nil { + if _, err := inspection_profile.Update(service, id, &req); err != nil { return err } if v, ok := d.GetOk("associate_all_controls"); ok && v.(bool) { - p, _, err := zClient.inspection_profile.Get(req.ID) + p, _, err := inspection_profile.Get(service, req.ID) if err != nil { return err } - zClient.inspection_profile.PutAssociate(req.ID, p) + inspection_profile.PutAssociate(service, req.ID, p) } return resourceInspectionProfileRead(d, m) } func resourceInspectionProfileDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.InspectionProfile log.Printf("[INFO] Deleting inspection profile ID: %v\n", d.Id()) - if _, err := zClient.inspection_profile.Delete(d.Id()); err != nil { + if _, err := inspection_profile.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_inspection_profile_test.go b/zpa/resource_zpa_inspection_profile_test.go index b3bb0e2b..f79c975f 100644 --- a/zpa/resource_zpa_inspection_profile_test.go +++ b/zpa/resource_zpa_inspection_profile_test.go @@ -61,7 +61,7 @@ func testAccCheckInspectionProfileDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.inspection_profile.Get(rs.Primary.ID) + rule, _, err := inspection_profile.Get(apiClient.InspectionProfile, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -86,7 +86,7 @@ func testAccCheckInspectionProfileExists(resource string, rule *inspection_profi } apiClient := testAccProvider.Meta().(*Client) - receivedProfile, _, err := apiClient.inspection_profile.Get(rs.Primary.ID) + receivedProfile, _, err := inspection_profile.Get(apiClient.InspectionProfile, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_lss_config_controller.go b/zpa/resource_zpa_lss_config_controller.go index 7f17af19..e3f21b0d 100644 --- a/zpa/resource_zpa_lss_config_controller.go +++ b/zpa/resource_zpa_lss_config_controller.go @@ -102,6 +102,7 @@ func resourceLSSConfigController() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.LSSConfigController id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -109,7 +110,7 @@ func resourceLSSConfigController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.lssconfigcontroller.GetByName(id) + resp, _, err := lssconfigcontroller.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -236,6 +237,7 @@ func resourceLSSConfigController() *schema.Resource { func resourceLSSConfigControllerCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController req := expandLSSResource(d) log.Printf("[INFO] Creating zpa lss config controller with request\n%+v\n", req) @@ -300,7 +302,7 @@ func resourceLSSConfigControllerCreate(d *schema.ResourceData, m interface{}) er } } - resp, _, err := zClient.lssconfigcontroller.Create(&req) + resp, _, err := lssconfigcontroller.Create(service, &req) if err != nil { return err } @@ -313,8 +315,9 @@ func resourceLSSConfigControllerCreate(d *schema.ResourceData, m interface{}) er func resourceLSSConfigControllerRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController - resp, _, err := zClient.lssconfigcontroller.Get(d.Id()) + resp, _, err := lssconfigcontroller.Get(service, d.Id()) if err != nil { if err.(*client.ErrorResponse).IsObjectNotFound() { log.Printf("[WARN] Removing lss config controller %s from state because it no longer exists in ZPA", d.Id()) @@ -337,6 +340,7 @@ func resourceLSSConfigControllerRead(d *schema.ResourceData, m interface{}) erro func resourceLSSConfigControllerUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController id := d.Id() req := expandLSSResource(d) @@ -402,7 +406,7 @@ func resourceLSSConfigControllerUpdate(d *schema.ResourceData, m interface{}) er } } - if _, _, err := zClient.lssconfigcontroller.Get(id); err != nil { + if _, _, err := lssconfigcontroller.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil @@ -410,7 +414,7 @@ func resourceLSSConfigControllerUpdate(d *schema.ResourceData, m interface{}) er return err } - if _, err := zClient.lssconfigcontroller.Update(id, &req); err != nil { + if _, err := lssconfigcontroller.Update(service, id, &req); err != nil { return err } @@ -419,10 +423,11 @@ func resourceLSSConfigControllerUpdate(d *schema.ResourceData, m interface{}) er func resourceLSSConfigControllerDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.LSSConfigController log.Printf("[INFO] Deleting lss config controller ID: %v\n", d.Id()) - if _, err := zClient.lssconfigcontroller.Delete(d.Id()); err != nil { + if _, err := lssconfigcontroller.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_lss_config_controller_test.go b/zpa/resource_zpa_lss_config_controller_test.go index 7449a9e6..5b2de67d 100644 --- a/zpa/resource_zpa_lss_config_controller_test.go +++ b/zpa/resource_zpa_lss_config_controller_test.go @@ -59,14 +59,14 @@ func TestAccResourceLSSConfigControllerBasic(t *testing.T) { } func testAccCheckLSSConfigControllerDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*Client) + apiClient := testAccProvider.Meta().(*Client) for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPALSSController { continue } - lss, _, err := client.lssconfigcontroller.Get(rs.Primary.ID) + lss, _, err := lssconfigcontroller.Get(apiClient.LSSConfigController, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s still exists", rs.Primary.ID) } @@ -87,8 +87,8 @@ func testAccCheckLSSConfigControllerExists(resource string, lss *lssconfigcontro if rs.Primary.ID == "" { return fmt.Errorf("no Application Segment ID is set") } - client := testAccProvider.Meta().(*Client) - receivedLss, _, err := client.lssconfigcontroller.Get(rs.Primary.ID) + apiClient := testAccProvider.Meta().(*Client) + receivedLss, _, err := lssconfigcontroller.Get(apiClient.LSSConfigController, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Received error: %s", resource, err) } diff --git a/zpa/resource_zpa_microtenant_controller.go b/zpa/resource_zpa_microtenant_controller.go index 24f77a99..927c2a6b 100644 --- a/zpa/resource_zpa_microtenant_controller.go +++ b/zpa/resource_zpa_microtenant_controller.go @@ -18,6 +18,7 @@ func resourceMicrotenantController() *schema.Resource { Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { zClient := m.(*Client) + service := zClient.MicroTenants id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -25,7 +26,7 @@ func resourceMicrotenantController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := zClient.microtenants.GetByName(id) + resp, _, err := microtenants.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -97,11 +98,12 @@ func resourceMicrotenantController() *schema.Resource { func resourceMicrotenantCreate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.MicroTenants req := expandMicroTenant(d) log.Printf("[INFO] Creating microtenant with request\n%+v\n", req) - microTenant, _, err := zClient.microtenants.Create(req) + microTenant, _, err := microtenants.Create(service, req) if err != nil { return err } @@ -118,8 +120,9 @@ func resourceMicrotenantCreate(d *schema.ResourceData, m interface{}) error { func resourceMicrotenantRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.MicroTenants - resp, _, err := zClient.microtenants.Get(d.Id()) + resp, _, err := microtenants.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing microtenant %s from state because it no longer exists in ZPA", d.Id()) @@ -150,19 +153,20 @@ func resourceMicrotenantRead(d *schema.ResourceData, m interface{}) error { func resourceMicrotenantUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.MicroTenants id := d.Id() log.Printf("[INFO] Updating microtenant ID: %v\n", id) req := expandMicroTenant(d) - if _, _, err := zClient.microtenants.Get(id); err != nil { + if _, _, err := microtenants.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := zClient.microtenants.Update(id, &req); err != nil { + if _, err := microtenants.Update(service, id, &req); err != nil { return err } @@ -171,10 +175,11 @@ func resourceMicrotenantUpdate(d *schema.ResourceData, m interface{}) error { func resourceMicrotenantDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.MicroTenants log.Printf("[INFO] Deleting microtenant ID: %v\n", d.Id()) - if _, err := zClient.microtenants.Delete(d.Id()); err != nil { + if _, err := microtenants.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_policy_access_forwarding_rule.go b/zpa/resource_zpa_policy_access_forwarding_rule.go index 4f0a6dc9..4f97d9d9 100644 --- a/zpa/resource_zpa_policy_access_forwarding_rule.go +++ b/zpa/resource_zpa_policy_access_forwarding_rule.go @@ -53,7 +53,14 @@ func resourcePolicyForwardingRule() *schema.Resource { } func resourcePolicyForwardingRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -62,7 +69,7 @@ func resourcePolicyForwardingRuleCreate(d *schema.ResourceData, m interface{}) e policySetID = v.(string) } else { // Fetch policy_set_id based on the policy_type - policySetID, err = fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -72,32 +79,36 @@ func resourcePolicyForwardingRuleCreate(d *schema.ResourceData, m interface{}) e return err } log.Printf("[INFO] Creating zpa policy forwarding rule with request\n%+v\n", req) - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - policysetcontroller, _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).CreateRule(req) + resp, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } - d.SetId(policysetcontroller.ID) + d.SetId(resp.ID) return resourcePolicyForwardingRuleRead(d, m) } func resourcePolicyForwardingRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - policySetID, err := fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontroller.WithMicroTenant(microTenantID) + service := zClient.PolicySetController + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontroller.GetPolicyRule(service, policySetID, d.Id()) if err != nil { // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { @@ -107,7 +118,6 @@ func resourcePolicyForwardingRuleRead(d *schema.ResourceData, m interface{}) err } return err } - log.Printf("[INFO] Got Policy Set Forwarding Rule:\n%+v\n", resp) d.SetId(resp.ID) _ = d.Set("name", resp.Name) @@ -128,7 +138,14 @@ func resourcePolicyForwardingRuleRead(d *schema.ResourceData, m interface{}) err } func resourcePolicyForwardingRuleUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -136,7 +153,7 @@ func resourcePolicyForwardingRuleUpdate(d *schema.ResourceData, m interface{}) e if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - policySetID, err = fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -148,11 +165,10 @@ func resourcePolicyForwardingRuleUpdate(d *schema.ResourceData, m interface{}) e return err } // Replace ValidatePolicyRuleConditions with ValidateConditions - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(policySetID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -160,7 +176,14 @@ func resourcePolicyForwardingRuleUpdate(d *schema.ResourceData, m interface{}) e } func resourcePolicyForwardingRuleDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -169,7 +192,7 @@ func resourcePolicyForwardingRuleDelete(d *schema.ResourceData, m interface{}) e policySetID = v.(string) } else { // Assuming "CLIENT_FORWARDING_POLICY" as policy type for demonstration - policySetID, err = fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -177,7 +200,7 @@ func resourcePolicyForwardingRuleDelete(d *schema.ResourceData, m interface{}) e log.Printf("[INFO] Deleting policy forwarding rule with id %v\n", d.Id()) - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).Delete(policySetID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_forwarding_rule_test.go b/zpa/resource_zpa_policy_access_forwarding_rule_test.go index dbe8990b..d1493c97 100644 --- a/zpa/resource_zpa_policy_access_forwarding_rule_test.go +++ b/zpa/resource_zpa_policy_access_forwarding_rule_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyForwardingRuleBasic(t *testing.T) { @@ -58,16 +59,16 @@ func TestAccResourcePolicyForwardingRuleBasic(t *testing.T) { func testAccCheckPolicyForwardingRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("CLIENT_FORWARDING_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "CLIENT_FORWARDING_POLICY") if err != nil { - return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Recevied error: %s", err) + return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Received error: %s", err) } for _, rs := range s.RootModule().Resources { if rs.Type != resourcetype.ZPAPolicyAccessRule { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -92,13 +93,13 @@ func testAccCheckPolicyForwardingRuleExists(resource string) resource.TestCheckF } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("CLIENT_FORWARDING_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "CLIENT_FORWARDING_POLICY") if err != nil { - return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Recevied error: %s", err) + return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Received error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { - return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) + return fmt.Errorf("failed fetching resource %s. Received error: %s", resource, err) } return nil } diff --git a/zpa/resource_zpa_policy_access_forwarding_rule_v2.go b/zpa/resource_zpa_policy_access_forwarding_rule_v2.go index 4d499ea3..a5f88705 100644 --- a/zpa/resource_zpa_policy_access_forwarding_rule_v2.go +++ b/zpa/resource_zpa_policy_access_forwarding_rule_v2.go @@ -137,11 +137,15 @@ func resourcePolicyForwardingRuleV2() *schema.Resource { } func resourcePolicyForwardingRuleV2Create(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "CLIENT_FORWARDING_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -159,29 +163,33 @@ func resourcePolicyForwardingRuleV2Create(d *schema.ResourceData, m interface{}) return err } - resp, _, err := service.CreateRule(req) + resp, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } d.SetId(resp.ID) + return resourcePolicyForwardingRuleV2Read(d, m) } func resourcePolicyForwardingRuleV2Read(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -190,7 +198,8 @@ func resourcePolicyForwardingRuleV2Read(d *schema.ResourceData, m interface{}) e return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) + d.SetId(resp.ID) d.Set("name", v2PolicyRule.Name) d.Set("description", v2PolicyRule.Description) @@ -203,11 +212,16 @@ func resourcePolicyForwardingRuleV2Read(d *schema.ResourceData, m interface{}) e } func resourcePolicyForwardingRuleV2Update(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "CLIENT_FORWARDING_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -227,7 +241,7 @@ func resourcePolicyForwardingRuleV2Update(d *schema.ResourceData, m interface{}) } // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -236,8 +250,7 @@ func resourcePolicyForwardingRuleV2Update(d *schema.ResourceData, m interface{}) return err } - _, err = service.UpdateRule(policySetID, ruleID, req) - if err != nil { + if _, err := policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -245,18 +258,21 @@ func resourcePolicyForwardingRuleV2Update(d *schema.ResourceData, m interface{}) } func resourcePolicyForwardingRuleV2Delete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "CLIENT_FORWARDING_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "CLIENT_FORWARDING_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CLIENT_FORWARDING_POLICY", microTenantID) if err != nil { return err } - log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_forwarding_rule_v2_test.go b/zpa/resource_zpa_policy_access_forwarding_rule_v2_test.go index 80fdef22..787e5727 100644 --- a/zpa/resource_zpa_policy_access_forwarding_rule_v2_test.go +++ b/zpa/resource_zpa_policy_access_forwarding_rule_v2_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyForwardingRuleV2Basic(t *testing.T) { @@ -56,7 +57,7 @@ func TestAccResourcePolicyForwardingRuleV2Basic(t *testing.T) { func testAccCheckPolicyForwardingRuleV2Destroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CLIENT_FORWARDING_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CLIENT_FORWARDING_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Recevied error: %s", err) } @@ -65,7 +66,7 @@ func testAccCheckPolicyForwardingRuleV2Destroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -90,11 +91,11 @@ func testAccCheckPolicyForwardingRuleV2Exists(resource string) resource.TestChec } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CLIENT_FORWARDING_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CLIENT_FORWARDING_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CLIENT_FORWARDING_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_inspection_rule.go b/zpa/resource_zpa_policy_access_inspection_rule.go index 473e4857..f4a8d41f 100644 --- a/zpa/resource_zpa_policy_access_inspection_rule.go +++ b/zpa/resource_zpa_policy_access_inspection_rule.go @@ -49,7 +49,14 @@ func resourcePolicyInspectionRule() *schema.Resource { } func resourcePolicyInspectionRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -58,7 +65,7 @@ func resourcePolicyInspectionRuleCreate(d *schema.ResourceData, m interface{}) e policySetID = v.(string) } else { // Fetch policy_set_id based on the policy_type - policySetID, err = fetchPolicySetIDByType(client, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -69,30 +76,35 @@ func resourcePolicyInspectionRuleCreate(d *schema.ResourceData, m interface{}) e } log.Printf("[INFO] Creating zpa policy inspection rule with request\n%+v\n", req) - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - policysetcontroller, _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).CreateRule(req) + resp, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } - d.SetId(policysetcontroller.ID) + + d.SetId(resp.ID) return resourcePolicyInspectionRuleRead(d, m) } func resourcePolicyInspectionRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - policySetID, err := fetchPolicySetIDByType(client, "INSPECTION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontroller.WithMicroTenant(microTenantID) + service := zClient.PolicySetController + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontroller.GetPolicyRule(service, policySetID, d.Id()) if err != nil { // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { @@ -121,7 +133,14 @@ func resourcePolicyInspectionRuleRead(d *schema.ResourceData, m interface{}) err } func resourcePolicyInspectionRuleUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -129,7 +148,7 @@ func resourcePolicyInspectionRuleUpdate(d *schema.ResourceData, m interface{}) e if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - policySetID, err = fetchPolicySetIDByType(client, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -141,18 +160,26 @@ func resourcePolicyInspectionRuleUpdate(d *schema.ResourceData, m interface{}) e return err } // Replace ValidatePolicyRuleConditions with ValidateConditions - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(policySetID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } + return resourcePolicyInspectionRuleRead(d, m) } func resourcePolicyInspectionRuleDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -161,14 +188,14 @@ func resourcePolicyInspectionRuleDelete(d *schema.ResourceData, m interface{}) e policySetID = v.(string) } else { // Assuming "INSPECTION_POLICY" as policy type for demonstration - policySetID, err = fetchPolicySetIDByType(client, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } } log.Printf("[INFO] Deleting policy inspection rule with id %v\n", d.Id()) - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).Delete(policySetID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_inspection_rule_test.go b/zpa/resource_zpa_policy_access_inspection_rule_test.go index 596de154..adc127ac 100644 --- a/zpa/resource_zpa_policy_access_inspection_rule_test.go +++ b/zpa/resource_zpa_policy_access_inspection_rule_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyInspectionRuleBasic(t *testing.T) { @@ -69,7 +70,7 @@ func TestAccResourcePolicyInspectionRuleBasic(t *testing.T) { func testAccCheckPolicyInspectionRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("INSPECTION_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "INSPECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource INSPECTION_POLICY. Recevied error: %s", err) } @@ -78,7 +79,7 @@ func testAccCheckPolicyInspectionRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -103,11 +104,11 @@ func testAccCheckPolicyInspectionRuleExists(resource string) resource.TestCheckF } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("INSPECTION_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "INSPECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource INSPECTION_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_inspection_rule_v2.go b/zpa/resource_zpa_policy_access_inspection_rule_v2.go index fc47946c..3b244a3c 100644 --- a/zpa/resource_zpa_policy_access_inspection_rule_v2.go +++ b/zpa/resource_zpa_policy_access_inspection_rule_v2.go @@ -138,11 +138,15 @@ func resourcePolicyInspectionRuleV2() *schema.Resource { } func resourcePolicyInspectionRuleV2Create(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "INSPECTION_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -160,29 +164,33 @@ func resourcePolicyInspectionRuleV2Create(d *schema.ResourceData, m interface{}) return err } - resp, _, err := service.CreateRule(req) + resp, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } d.SetId(resp.ID) + return resourcePolicyInspectionRuleV2Read(d, m) } func resourcePolicyInspectionRuleV2Read(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "INSPECTION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -191,7 +199,8 @@ func resourcePolicyInspectionRuleV2Read(d *schema.ResourceData, m interface{}) e return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) + d.SetId(resp.ID) d.Set("name", v2PolicyRule.Name) d.Set("description", v2PolicyRule.Description) @@ -205,11 +214,16 @@ func resourcePolicyInspectionRuleV2Read(d *schema.ResourceData, m interface{}) e } func resourcePolicyInspectionRuleV2Update(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "INSPECTION_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -229,7 +243,7 @@ func resourcePolicyInspectionRuleV2Update(d *schema.ResourceData, m interface{}) } // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -238,8 +252,7 @@ func resourcePolicyInspectionRuleV2Update(d *schema.ResourceData, m interface{}) return err } - _, err = service.UpdateRule(policySetID, ruleID, req) - if err != nil { + if _, err := policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -247,19 +260,23 @@ func resourcePolicyInspectionRuleV2Update(d *schema.ResourceData, m interface{}) } func resourcePolicyInspectionRuleV2Delete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "INSPECTION_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "INSPECTION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "INSPECTION_POLICY", microTenantID) if err != nil { return err } log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_inspection_rule_v2_test.go b/zpa/resource_zpa_policy_access_inspection_rule_v2_test.go index 3dbe3ba6..28074f15 100644 --- a/zpa/resource_zpa_policy_access_inspection_rule_v2_test.go +++ b/zpa/resource_zpa_policy_access_inspection_rule_v2_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyInspectionRuleV2Basic(t *testing.T) { @@ -67,7 +68,7 @@ func TestAccResourcePolicyInspectionRuleV2Basic(t *testing.T) { func testAccCheckPolicyInspectionRuleV2Destroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("INSPECTION_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "INSPECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource INSPECTION_POLICY. Recevied error: %s", err) } @@ -76,7 +77,7 @@ func testAccCheckPolicyInspectionRuleV2Destroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -101,11 +102,11 @@ func testAccCheckPolicyInspectionRuleV2Exists(resource string) resource.TestChec } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("INSPECTION_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "INSPECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource INSPECTION_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_isolation_rule.go b/zpa/resource_zpa_policy_access_isolation_rule.go index 22f56472..d8462299 100644 --- a/zpa/resource_zpa_policy_access_isolation_rule.go +++ b/zpa/resource_zpa_policy_access_isolation_rule.go @@ -48,7 +48,14 @@ func resourcePolicyIsolationRule() *schema.Resource { } func resourcePolicyIsolationRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -57,7 +64,7 @@ func resourcePolicyIsolationRuleCreate(d *schema.ResourceData, m interface{}) er policySetID = v.(string) } else { // Fetch policy_set_id based on the policy_type - policySetID, err = fetchPolicySetIDByType(client, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -67,32 +74,36 @@ func resourcePolicyIsolationRuleCreate(d *schema.ResourceData, m interface{}) er return err } log.Printf("[INFO] Creating zpa policy isolation rule with request\n%+v\n", req) - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - policysetcontroller, _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).CreateRule(req) + resp, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } - d.SetId(policysetcontroller.ID) + d.SetId(resp.ID) return resourcePolicyIsolationRuleRead(d, m) } func resourcePolicyIsolationRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - policySetID, err := fetchPolicySetIDByType(client, "ISOLATION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontroller.WithMicroTenant(microTenantID) + service := zClient.PolicySetController + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontroller.GetPolicyRule(service, policySetID, d.Id()) if err != nil { // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { @@ -119,7 +130,14 @@ func resourcePolicyIsolationRuleRead(d *schema.ResourceData, m interface{}) erro } func resourcePolicyIsolationRuleUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -127,7 +145,7 @@ func resourcePolicyIsolationRuleUpdate(d *schema.ResourceData, m interface{}) er if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - policySetID, err = fetchPolicySetIDByType(client, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -139,11 +157,11 @@ func resourcePolicyIsolationRuleUpdate(d *schema.ResourceData, m interface{}) er return err } // Replace ValidatePolicyRuleConditions with ValidateConditions - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, GetString(d.Get("microtenant_id"))); err != nil { return err } - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(policySetID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -151,7 +169,14 @@ func resourcePolicyIsolationRuleUpdate(d *schema.ResourceData, m interface{}) er } func resourcePolicyIsolationRuleDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error @@ -160,7 +185,7 @@ func resourcePolicyIsolationRuleDelete(d *schema.ResourceData, m interface{}) er policySetID = v.(string) } else { // Assuming "ISOLATION_POLICY" as policy type for demonstration - policySetID, err = fetchPolicySetIDByType(client, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -168,7 +193,7 @@ func resourcePolicyIsolationRuleDelete(d *schema.ResourceData, m interface{}) er log.Printf("[INFO] Deleting policy isolation rule with id %v\n", d.Id()) - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).Delete(policySetID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_isolation_rule_test.go b/zpa/resource_zpa_policy_access_isolation_rule_test.go index bfa5c7ef..f04b7d6e 100644 --- a/zpa/resource_zpa_policy_access_isolation_rule_test.go +++ b/zpa/resource_zpa_policy_access_isolation_rule_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyIsolationRuleBasic(t *testing.T) { @@ -58,7 +59,7 @@ func TestAccResourcePolicyIsolationRuleBasic(t *testing.T) { func testAccCheckPolicyIsolationRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("ISOLATION_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "ISOLATION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ISOLATION_POLICY. Received error: %s", err) } @@ -67,7 +68,7 @@ func testAccCheckPolicyIsolationRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -92,11 +93,11 @@ func testAccCheckPolicyIsolationRuleExists(resource string) resource.TestCheckFu } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("ISOLATION_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "ISOLATION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ISOLATION_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_isolation_rule_v2.go b/zpa/resource_zpa_policy_access_isolation_rule_v2.go index bf6a9e40..5f1a56d1 100644 --- a/zpa/resource_zpa_policy_access_isolation_rule_v2.go +++ b/zpa/resource_zpa_policy_access_isolation_rule_v2.go @@ -137,11 +137,16 @@ func resourcePolicyIsolationRuleV2() *schema.Resource { } func resourcePolicyIsolationRuleV2Create(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "ISOLATION_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -159,29 +164,33 @@ func resourcePolicyIsolationRuleV2Create(d *schema.ResourceData, m interface{}) return err } - resp, _, err := service.CreateRule(req) + resp, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } d.SetId(resp.ID) + return resourcePolicyIsolationRuleV2Read(d, m) } func resourcePolicyIsolationRuleV2Read(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "ISOLATION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -190,7 +199,7 @@ func resourcePolicyIsolationRuleV2Read(d *schema.ResourceData, m interface{}) er return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) d.SetId(resp.ID) d.Set("name", v2PolicyRule.Name) d.Set("description", v2PolicyRule.Description) @@ -204,11 +213,16 @@ func resourcePolicyIsolationRuleV2Read(d *schema.ResourceData, m interface{}) er } func resourcePolicyIsolationRuleV2Update(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "ISOLATION_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -228,7 +242,7 @@ func resourcePolicyIsolationRuleV2Update(d *schema.ResourceData, m interface{}) } // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -237,8 +251,7 @@ func resourcePolicyIsolationRuleV2Update(d *schema.ResourceData, m interface{}) return err } - _, err = service.UpdateRule(policySetID, ruleID, req) - if err != nil { + if _, err := policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -246,19 +259,23 @@ func resourcePolicyIsolationRuleV2Update(d *schema.ResourceData, m interface{}) } func resourcePolicyIsolationRuleV2Delete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "ISOLATION_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "ISOLATION_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ISOLATION_POLICY", microTenantID) if err != nil { return err } log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_isolation_rule_v2_test.go b/zpa/resource_zpa_policy_access_isolation_rule_v2_test.go index b57d3a8b..57fea094 100644 --- a/zpa/resource_zpa_policy_access_isolation_rule_v2_test.go +++ b/zpa/resource_zpa_policy_access_isolation_rule_v2_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyIsolationRuleV2Basic(t *testing.T) { @@ -56,7 +57,7 @@ func TestAccResourcePolicyIsolationRuleV2Basic(t *testing.T) { func testAccCheckPolicyIsolationRuleV2Destroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("ISOLATION_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "ISOLATION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ISOLATION_POLICY. Recevied error: %s", err) } @@ -65,7 +66,7 @@ func testAccCheckPolicyIsolationRuleV2Destroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -90,11 +91,11 @@ func testAccCheckPolicyIsolationRuleV2Exists(resource string) resource.TestCheck } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("ISOLATION_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "ISOLATION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ISOLATION_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_redirection_rule.go b/zpa/resource_zpa_policy_access_redirection_rule.go index 8e99acde..05c0bdd0 100644 --- a/zpa/resource_zpa_policy_access_redirection_rule.go +++ b/zpa/resource_zpa_policy_access_redirection_rule.go @@ -84,7 +84,7 @@ func resourcePolicyRedictionRuleCreate(d *schema.ResourceData, m interface{}) er } zClient := m.(*Client) - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + service := zClient.PolicySetController.WithMicroTenant(GetString(d.Get("microtenant_id"))) req, err := expandCreatePolicyRedirectionRule(d) if err != nil { @@ -92,7 +92,7 @@ func resourcePolicyRedictionRuleCreate(d *schema.ResourceData, m interface{}) er } log.Printf("[INFO] Creating zpa policy redirection rule with request\n%+v\n", req) if err := ValidateConditions(req.Conditions, zClient, req.MicroTenantID); err == nil { - policysetcontroller, _, err := service.CreateRule(req) + policysetcontroller, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } @@ -105,14 +105,14 @@ func resourcePolicyRedictionRuleCreate(d *schema.ResourceData, m interface{}) er } func resourcePolicyRedictionRuleRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) + service := m.(*Client).PolicySetController.WithMicroTenant(GetString(d.Get("microtenant_id"))) - globalPolicySet, _, err := service.GetByPolicyType("REDIRECTION_POLICY") + globalPolicySet, _, err := policysetcontroller.GetByPolicyType(service, "REDIRECTION_POLICY") if err != nil { return err } log.Printf("[INFO] Getting Policy Set Rule: globalPolicySet:%s id: %s\n", globalPolicySet.ID, d.Id()) - resp, _, err := service.GetPolicyRule(globalPolicySet.ID, d.Id()) + resp, _, err := policysetcontroller.GetPolicyRule(service, globalPolicySet.ID, d.Id()) if err != nil { if obj, ok := err.(*client.ErrorResponse); ok && obj.IsObjectNotFound() { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) @@ -143,8 +143,8 @@ func resourcePolicyRedictionRuleUpdate(d *schema.ResourceData, m interface{}) er } zClient := m.(*Client) - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) - globalPolicySet, _, err := service.GetByPolicyType("REDIRECTION_POLICY") + service := zClient.PolicySetController.WithMicroTenant(GetString(d.Get("microtenant_id"))) + globalPolicySet, _, err := policysetcontroller.GetByPolicyType(service, "REDIRECTION_POLICY") if err != nil { return err } @@ -155,14 +155,14 @@ func resourcePolicyRedictionRuleUpdate(d *schema.ResourceData, m interface{}) er return err } if err := ValidateConditions(req.Conditions, zClient, req.MicroTenantID); err == nil { - if _, _, err := service.GetPolicyRule(globalPolicySet.ID, ruleID); err != nil { + if _, _, err := policysetcontroller.GetPolicyRule(service, globalPolicySet.ID, ruleID); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.UpdateRule(globalPolicySet.ID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, globalPolicySet.ID, ruleID, req); err != nil { return err } @@ -173,15 +173,15 @@ func resourcePolicyRedictionRuleUpdate(d *schema.ResourceData, m interface{}) er } func resourcePolicyRedictionRuleDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) - globalPolicySet, _, err := service.GetByPolicyType("REDIRECTION_POLICY") + service := m.(*Client).PolicySetController.WithMicroTenant(GetString(d.Get("microtenant_id"))) + globalPolicySet, _, err := policysetcontroller.GetByPolicyType(service, "REDIRECTION_POLICY") if err != nil { return err } log.Printf("[INFO] Deleting policy redirection rule with id %v\n", d.Id()) - if _, err := service.Delete(globalPolicySet.ID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, globalPolicySet.ID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_redirection_rule_test.go b/zpa/resource_zpa_policy_access_redirection_rule_test.go index e5ea7968..36791da0 100644 --- a/zpa/resource_zpa_policy_access_redirection_rule_test.go +++ b/zpa/resource_zpa_policy_access_redirection_rule_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyRedictionRuleBasic(t *testing.T) { @@ -64,7 +65,7 @@ func TestAccResourcePolicyRedictionRuleBasic(t *testing.T) { func testAccCheckPolicyRedictionRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("REDIRECTION_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "REDIRECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource REDIRECTION_POLICY. Received error: %s", err) } @@ -73,7 +74,7 @@ func testAccCheckPolicyRedictionRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -98,11 +99,11 @@ func testAccCheckPolicyRedictionRuleExists(resource string) resource.TestCheckFu } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("REDIRECTION_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "REDIRECTION_POLICY") if err != nil { return fmt.Errorf("failed fetching resource REDIRECTION_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_rule.go b/zpa/resource_zpa_policy_access_rule.go index 6780b0a5..5b1e928b 100644 --- a/zpa/resource_zpa_policy_access_rule.go +++ b/zpa/resource_zpa_policy_access_rule.go @@ -88,58 +88,64 @@ func resourcePolicyAccessRule() *schema.Resource { } func resourcePolicyAccessCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - // Fetch policy_set_id based on the policy_type - policySetID, err = fetchPolicySetIDByType(client, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } } - // Preparing the request body with the obtained or provided policySetID - req, err := expandCreatePolicyRule(d, policySetID) // Ensure this function now accepts policySetID as a parameter + req, err := expandCreatePolicyRule(d, policySetID) if err != nil { return err } log.Printf("[INFO] Creating ZPA policy access rule with request\n%+v\n", req) - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, microTenantID); err != nil { return err } - // Make API call to create the policy access rule - policysetcontroller, _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).CreateRule(req) + resp, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } - d.SetId(policysetcontroller.ID) + d.SetId(resp.ID) return resourcePolicyAccessRead(d, m) } func resourcePolicyAccessRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - policySetID, err := fetchPolicySetIDByType(client, "ACCESS_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontroller.WithMicroTenant(microTenantID) + service := zClient.PolicySetController + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontroller.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -170,32 +176,37 @@ func resourcePolicyAccessRead(d *schema.ResourceData, m interface{}) error { } func resourcePolicyAccessUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user, otherwise fetch it if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - policySetID, err = fetchPolicySetIDByType(client, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } } ruleID := d.Id() - req, err := expandCreatePolicyRule(d, policySetID) // Ensure expandCreatePolicyRule now accepts policySetID + req, err := expandCreatePolicyRule(d, policySetID) if err != nil { return err } - // Replace ValidatePolicyRuleConditions with ValidateConditions - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, microTenantID); err != nil { return err } - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(policySetID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -203,16 +214,21 @@ func resourcePolicyAccessUpdate(d *schema.ResourceData, m interface{}) error { } func resourcePolicyAccessDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user, otherwise fetch it based on policy_type if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - // Assuming "ACCESS_POLICY" as policy type for demonstration - policySetID, err = fetchPolicySetIDByType(client, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } @@ -220,8 +236,7 @@ func resourcePolicyAccessDelete(d *schema.ResourceData, m interface{}) error { log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) - // Now using the potentially fetched policySetID in the delete call - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).Delete(policySetID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_rule_reorder.go b/zpa/resource_zpa_policy_access_rule_reorder.go index 31243ab8..f38eaee4 100644 --- a/zpa/resource_zpa_policy_access_rule_reorder.go +++ b/zpa/resource_zpa_policy_access_rule_reorder.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) // Define the Terraform resource for reordering policy access rules. @@ -131,9 +132,16 @@ func getRules(d *schema.ResourceData) (*RulesOrders, error) { func resourcePolicyAccessReorderRead(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + policyType := d.Get("policy_type").(string) - currentRules, _, err := zClient.policysetcontroller.GetAllByType(policyType) + currentRules, _, err := policysetcontroller.GetAllByType(service, policyType) if err != nil { log.Printf("[ERROR] failed to get rules: %v\n", err) d.SetId("") @@ -179,8 +187,14 @@ func resourcePolicyAccessReorderRead(d *schema.ResourceData, m interface{}) erro func resourcePolicyAccessReorderUpdate(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - existingRules, _, err := zClient.policysetcontroller.GetAllByType(d.Get("policy_type").(string)) + existingRules, _, err := policysetcontroller.GetAllByType(service, d.Get("policy_type").(string)) if err != nil { log.Printf("[ERROR] Failed to get existing rules: %v\n", err) return err @@ -217,7 +231,7 @@ func resourcePolicyAccessReorderUpdate(d *schema.ResourceData, m interface{}) er ruleIdToOrder[id] = order + baseOrder - 1 } - if _, err := zClient.policysetcontroller.BulkReorder(d.Get("policy_type").(string), ruleIdToOrder); err != nil { + if _, err := policysetcontroller.BulkReorder(service, d.Get("policy_type").(string), ruleIdToOrder); err != nil { log.Printf("[ERROR] Bulk reordering rules failed: %v", err) return err } diff --git a/zpa/resource_zpa_policy_access_rule_test.go b/zpa/resource_zpa_policy_access_rule_test.go index ed4db1ef..5b929697 100644 --- a/zpa/resource_zpa_policy_access_rule_test.go +++ b/zpa/resource_zpa_policy_access_rule_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyAccessRuleBasic(t *testing.T) { @@ -67,7 +68,7 @@ func TestAccResourcePolicyAccessRuleBasic(t *testing.T) { func testAccCheckPolicyAccessRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("ACCESS_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "ACCESS_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ACCESS_POLICY. Recevied error: %s", err) } @@ -76,7 +77,7 @@ func testAccCheckPolicyAccessRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -101,11 +102,11 @@ func testAccCheckPolicyAccessRuleExists(resource string) resource.TestCheckFunc } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("ACCESS_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "ACCESS_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ACCESS_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_rule_v2.go b/zpa/resource_zpa_policy_access_rule_v2.go index 147b1130..22340b4f 100755 --- a/zpa/resource_zpa_policy_access_rule_v2.go +++ b/zpa/resource_zpa_policy_access_rule_v2.go @@ -186,11 +186,16 @@ func resourcePolicyAccessRuleV2() *schema.Resource { } func resourcePolicyAccessV2Create(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "ACCESS_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -208,7 +213,7 @@ func resourcePolicyAccessV2Create(d *schema.ResourceData, m interface{}) error { return err } - policysetcontrollerv2, _, err := service.CreateRule(req) + policysetcontrollerv2, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } @@ -218,18 +223,22 @@ func resourcePolicyAccessV2Create(d *schema.ResourceData, m interface{}) error { } func resourcePolicyAccessV2Read(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "ACCESS_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -238,7 +247,7 @@ func resourcePolicyAccessV2Read(d *schema.ResourceData, m interface{}) error { return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) // Set Terraform state log.Printf("[INFO] Got Policy Set Rule:\n%+v\n", resp) @@ -257,11 +266,16 @@ func resourcePolicyAccessV2Read(d *schema.ResourceData, m interface{}) error { } func resourcePolicyAccessV2Update(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "ACCESS_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "ACCESS_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -279,8 +293,8 @@ func resourcePolicyAccessV2Update(d *schema.ResourceData, m interface{}) error { if err := ValidatePolicyRuleConditions(d); err != nil { return err } - // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -288,7 +302,7 @@ func resourcePolicyAccessV2Update(d *schema.ResourceData, m interface{}) error { } return err } - _, err = service.UpdateRule(policySetID, ruleID, req) + _, err = policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req) if err != nil { return err } @@ -297,19 +311,23 @@ func resourcePolicyAccessV2Update(d *schema.ResourceData, m interface{}) error { } func resourcePolicyAccessV2Delete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "ACCESS_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "ACCESS_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "ACCESS_POLICY", microTenantID) if err != nil { return err } log.Printf("[INFO] Deleting access policy set rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_rule_v2_test.go b/zpa/resource_zpa_policy_access_rule_v2_test.go index 1a0a78bf..fc33d34b 100644 --- a/zpa/resource_zpa_policy_access_rule_v2_test.go +++ b/zpa/resource_zpa_policy_access_rule_v2_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyAccessRuleV2Basic(t *testing.T) { @@ -67,7 +68,7 @@ func TestAccResourcePolicyAccessRuleV2Basic(t *testing.T) { func testAccCheckPolicyAccessRuleV2Destroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("ACCESS_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "ACCESS_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ACCESS_POLICY. Recevied error: %s", err) } @@ -76,7 +77,7 @@ func testAccCheckPolicyAccessRuleV2Destroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -101,11 +102,11 @@ func testAccCheckPolicyAccessRuleV2Exists(resource string) resource.TestCheckFun } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("ACCESS_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "ACCESS_POLICY") if err != nil { return fmt.Errorf("failed fetching resource ACCESS_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_timeout_rule.go b/zpa/resource_zpa_policy_access_timeout_rule.go index 3019810e..c05ca609 100644 --- a/zpa/resource_zpa_policy_access_timeout_rule.go +++ b/zpa/resource_zpa_policy_access_timeout_rule.go @@ -47,16 +47,21 @@ func resourcePolicyTimeoutRule() *schema.Resource { } func resourcePolicyTimeoutRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - // Fetch policy_set_id based on the policy_type - policySetID, err = fetchPolicySetIDByType(client, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } @@ -67,34 +72,37 @@ func resourcePolicyTimeoutRuleCreate(d *schema.ResourceData, m interface{}) erro return err } log.Printf("[INFO] Creating zpa policy timeout rule with request\n%+v\n", req) - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + if err := ValidateConditions(req.Conditions, zClient, microTenantID); err != nil { return err } - policysetcontroller, _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).CreateRule(req) + resp, _, err := policysetcontroller.CreateRule(service, req) if err != nil { return err } - d.SetId(policysetcontroller.ID) + d.SetId(resp.ID) return resourcePolicyTimeoutRuleRead(d, m) } func resourcePolicyTimeoutRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - policySetID, err := fetchPolicySetIDByType(client, "TIMEOUT_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontroller.WithMicroTenant(microTenantID) + service := zClient.PolicySetController + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + log.Printf("[INFO] Getting Policy Set Rule: policySetID:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontroller.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -126,14 +134,20 @@ func resourcePolicyTimeoutRuleRead(d *schema.ResourceData, m interface{}) error func resourcePolicyTimeoutRuleUpdate(d *schema.ResourceData, m interface{}) error { client := m.(*Client) + service := client.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user, otherwise fetch it if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - policySetID, err = fetchPolicySetIDByType(client, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(client, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } @@ -144,12 +158,12 @@ func resourcePolicyTimeoutRuleUpdate(d *schema.ResourceData, m interface{}) erro if err != nil { return err } - // Replace ValidatePolicyRuleConditions with ValidateConditions - if err := ValidateConditions(req.Conditions, client, GetString(d.Get("microtenant_id"))); err != nil { + + if err := ValidateConditions(req.Conditions, client, microTenantID); err != nil { return err } - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).UpdateRule(policySetID, ruleID, req); err != nil { + if _, err := policysetcontroller.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } @@ -158,15 +172,20 @@ func resourcePolicyTimeoutRuleUpdate(d *schema.ResourceData, m interface{}) erro func resourcePolicyTimeoutRuleDelete(d *schema.ResourceData, m interface{}) error { client := m.(*Client) + service := client.PolicySetController + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + var policySetID string var err error - // Check if policy_set_id is provided by the user, otherwise fetch it based on policy_type if v, ok := d.GetOk("policy_set_id"); ok { policySetID = v.(string) } else { - // Assuming "TIMEOUT_POLICY" as policy type for demonstration - policySetID, err = fetchPolicySetIDByType(client, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err = fetchPolicySetIDByType(client, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } @@ -174,7 +193,7 @@ func resourcePolicyTimeoutRuleDelete(d *schema.ResourceData, m interface{}) erro log.Printf("[INFO] Deleting policy timeout rule with id %v\n", d.Id()) - if _, err := client.policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))).Delete(policySetID, d.Id()); err != nil { + if _, err := policysetcontroller.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_timeout_rule_test.go b/zpa/resource_zpa_policy_access_timeout_rule_test.go index e1715bd3..19581928 100644 --- a/zpa/resource_zpa_policy_access_timeout_rule_test.go +++ b/zpa/resource_zpa_policy_access_timeout_rule_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" ) func TestAccResourcePolicyTimeoutRuleBasic(t *testing.T) { @@ -62,7 +63,7 @@ func TestAccResourcePolicyTimeoutRuleBasic(t *testing.T) { func testAccCheckPolicyTimeoutRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontroller.GetByPolicyType("TIMEOUT_POLICY") + accessPolicy, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "TIMEOUT_POLICY") if err != nil { return fmt.Errorf("failed fetching resource TIMEOUT_POLICY. Recevied error: %s", err) } @@ -71,7 +72,7 @@ func testAccCheckPolicyTimeoutRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontroller.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontroller.GetPolicyRule(apiClient.PolicySetController, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -96,11 +97,11 @@ func testAccCheckPolicyTimeoutRuleExists(resource string) resource.TestCheckFunc } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontroller.GetByPolicyType("TIMEOUT_POLICY") + resp, _, err := policysetcontroller.GetByPolicyType(apiClient.PolicySetController, "TIMEOUT_POLICY") if err != nil { return fmt.Errorf("failed fetching resource TIMEOUT_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontroller.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontroller.GetPolicyRule(apiClient.PolicySetController, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_access_timeout_rule_v2.go b/zpa/resource_zpa_policy_access_timeout_rule_v2.go index 7fd46621..0c0370a1 100644 --- a/zpa/resource_zpa_policy_access_timeout_rule_v2.go +++ b/zpa/resource_zpa_policy_access_timeout_rule_v2.go @@ -149,11 +149,15 @@ func resourcePolicyTimeoutRuleV2() *schema.Resource { } func resourcePolicyTimeoutRuleV2Create(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "TIMEOUT_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -185,7 +189,7 @@ func resourcePolicyTimeoutRuleV2Create(d *schema.ResourceData, m interface{}) er } log.Printf("[INFO] Creating zpa policy timeout rule with request\n%+v\n", req) - policysetcontrollerv2, _, err := service.CreateRule(req) + policysetcontrollerv2, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } @@ -195,26 +199,31 @@ func resourcePolicyTimeoutRuleV2Create(d *schema.ResourceData, m interface{}) er } func resourcePolicyTimeoutRuleV2Read(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "TIMEOUT_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + log.Printf("[INFO] Getting Policy Set Rule: globalPolicySet:%s id: %s\n", policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { + log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") return nil } return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) log.Printf("[INFO] Got Policy Set Rule:\n%+v\n", resp) d.SetId(resp.ID) @@ -232,11 +241,16 @@ func resourcePolicyTimeoutRuleV2Read(d *schema.ResourceData, m interface{}) erro } func resourcePolicyTimeoutRuleV2Update(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "TIMEOUT_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -269,7 +283,7 @@ func resourcePolicyTimeoutRuleV2Update(d *schema.ResourceData, m interface{}) er } // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -277,8 +291,7 @@ func resourcePolicyTimeoutRuleV2Update(d *schema.ResourceData, m interface{}) er } return err } - - _, err = service.UpdateRule(policySetID, ruleID, req) + _, err = policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req) if err != nil { return err } @@ -287,17 +300,23 @@ func resourcePolicyTimeoutRuleV2Update(d *schema.ResourceData, m interface{}) er } func resourcePolicyTimeoutRuleV2Delete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "TIMEOUT_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "TIMEOUT_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "TIMEOUT_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) + + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_access_timeout_rule_v2_test.go b/zpa/resource_zpa_policy_access_timeout_rule_v2_test.go index 3a9fc68f..093fe58f 100644 --- a/zpa/resource_zpa_policy_access_timeout_rule_v2_test.go +++ b/zpa/resource_zpa_policy_access_timeout_rule_v2_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyTimeoutRuleV2Basic(t *testing.T) { @@ -60,7 +61,7 @@ func TestAccResourcePolicyTimeoutRuleV2Basic(t *testing.T) { func testAccCheckPolicyTimeoutRuleV2Destroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("TIMEOUT_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "TIMEOUT_POLICY") if err != nil { return fmt.Errorf("failed fetching resource TIMEOUT_POLICY. Recevied error: %s", err) } @@ -69,7 +70,7 @@ func testAccCheckPolicyTimeoutRuleV2Destroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -94,11 +95,11 @@ func testAccCheckPolicyTimeoutRuleV2Exists(resource string) resource.TestCheckFu } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("TIMEOUT_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "TIMEOUT_POLICY") if err != nil { return fmt.Errorf("failed fetching resource TIMEOUT_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_capabilities_access_rule.go b/zpa/resource_zpa_policy_capabilities_access_rule.go index 8c6b8af2..43521cd9 100644 --- a/zpa/resource_zpa_policy_capabilities_access_rule.go +++ b/zpa/resource_zpa_policy_capabilities_access_rule.go @@ -182,11 +182,15 @@ func resourcePolicyCapabilitiesAccessRule() *schema.Resource { } func resourcePolicyCapabilitiesAccessRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "CAPABILITIES_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CAPABILITIES_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "CAPABILITIES_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -204,7 +208,7 @@ func resourcePolicyCapabilitiesAccessRuleCreate(d *schema.ResourceData, m interf return err } - resp, _, err := service.CreateRule(req) + resp, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } @@ -215,19 +219,22 @@ func resourcePolicyCapabilitiesAccessRuleCreate(d *schema.ResourceData, m interf } func resourcePolicyCapabilitiesAccessRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "CAPABILITIES_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CAPABILITIES_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) log.Printf("[INFO] Getting Policy Set Rule: globalPolicySet:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -236,7 +243,7 @@ func resourcePolicyCapabilitiesAccessRuleRead(d *schema.ResourceData, m interfac return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) log.Printf("[INFO] Got Policy Set Rule:\n%+v\n", resp) d.SetId(resp.ID) @@ -253,11 +260,16 @@ func resourcePolicyCapabilitiesAccessRuleRead(d *schema.ResourceData, m interfac } func resourcePolicyCapabilitiesAccessRuleUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "CAPABILITIES_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CAPABILITIES_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "CAPABILITIES_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -277,7 +289,7 @@ func resourcePolicyCapabilitiesAccessRuleUpdate(d *schema.ResourceData, m interf } // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -285,7 +297,7 @@ func resourcePolicyCapabilitiesAccessRuleUpdate(d *schema.ResourceData, m interf } return err } - _, err = service.UpdateRule(policySetID, ruleID, req) + _, err = policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req) if err != nil { return err } @@ -294,19 +306,23 @@ func resourcePolicyCapabilitiesAccessRuleUpdate(d *schema.ResourceData, m interf } func resourcePolicyCapabilitiesAccessRuleDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) // Assume "CAPABILITIES_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "CAPABILITIES_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CAPABILITIES_POLICY", microTenantID) if err != nil { return err } log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_capabilities_access_rule_test.go b/zpa/resource_zpa_policy_capabilities_access_rule_test.go index b10108d0..eee68e99 100644 --- a/zpa/resource_zpa_policy_capabilities_access_rule_test.go +++ b/zpa/resource_zpa_policy_capabilities_access_rule_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyCapabilitiesAccessRuleBasic(t *testing.T) { @@ -57,7 +58,7 @@ func TestAccResourcePolicyCapabilitiesAccessRuleBasic(t *testing.T) { func testAccCheckPolicyCapabilitiesAccessRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CAPABILITIES_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CAPABILITIES_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CAPABILITIES_POLICY. Received error: %s", err) } @@ -66,7 +67,7 @@ func testAccCheckPolicyCapabilitiesAccessRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -91,11 +92,11 @@ func testAccCheckPolicyCapabilitiesAccessRuleExists(resource string) resource.Te } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CAPABILITIES_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CAPABILITIES_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CAPABILITIES_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_policy_credential_access_rule.go b/zpa/resource_zpa_policy_credential_access_rule.go index 702dc93a..df07b750 100644 --- a/zpa/resource_zpa_policy_credential_access_rule.go +++ b/zpa/resource_zpa_policy_credential_access_rule.go @@ -139,11 +139,16 @@ func resourcePolicyCredentialAccessRule() *schema.Resource { } func resourcePolicyCredentialAccessRuleCreate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Automatically determining policy_set_id for "CREDENTIAL_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CREDENTIAL_POLICY", GetString(d.Get("microtenant_id"))) + policySetID, err := fetchPolicySetIDByType(zClient, "CREDENTIAL_POLICY", GetString(d.Get("microtenant_id"))) if err != nil { return err } @@ -161,7 +166,7 @@ func resourcePolicyCredentialAccessRuleCreate(d *schema.ResourceData, m interfac return err } - resp, _, err := service.CreateRule(req) + resp, _, err := policysetcontrollerv2.CreateRule(service, req) if err != nil { return err } @@ -172,19 +177,22 @@ func resourcePolicyCredentialAccessRuleCreate(d *schema.ResourceData, m interfac } func resourcePolicyCredentialAccessRuleRead(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - policySetID, err := fetchPolicySetIDByType(client, "CREDENTIAL_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CREDENTIAL_POLICY", microTenantID) if err != nil { return err } - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) log.Printf("[INFO] Getting Policy Set Rule: globalPolicySet:%s id: %s\n", policySetID, d.Id()) - resp, respErr, err := service.GetPolicyRule(policySetID, d.Id()) + resp, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, d.Id()) if err != nil { - // Adjust this error handling to match how your client library exposes HTTP response details if respErr != nil && (respErr.StatusCode == 404 || respErr.StatusCode == http.StatusNotFound) { log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id()) d.SetId("") @@ -193,14 +201,14 @@ func resourcePolicyCredentialAccessRuleRead(d *schema.ResourceData, m interface{ return err } - v2PolicyRule := policysetcontrollerv2.ConvertV1ResponseToV2Request(*resp) + v2PolicyRule := ConvertV1ResponseToV2Request(*resp) log.Printf("[INFO] Got Policy Set Rule:\n%+v\n", resp) d.SetId(resp.ID) _ = d.Set("name", v2PolicyRule.Name) _ = d.Set("description", v2PolicyRule.Description) _ = d.Set("action", v2PolicyRule.Action) - _ = d.Set("policy_set_id", policySetID) // Here, you're setting it based on fetched ID + _ = d.Set("policy_set_id", policySetID) _ = d.Set("microtenant_id", v2PolicyRule.MicroTenantID) _ = d.Set("conditions", flattenConditionsV2(v2PolicyRule.Conditions)) _ = d.Set("credential", flattenCredential(resp.Credential)) @@ -209,16 +217,19 @@ func resourcePolicyCredentialAccessRuleRead(d *schema.ResourceData, m interface{ } func resourcePolicyCredentialAccessRuleUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) - service := client.policysetcontrollerv2.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PolicySetControllerV2 - // Automatically determining policy_set_id for "CREDENTIAL_POLICY" - policySetID, err := fetchPolicySetIDByType(client, "CREDENTIAL_POLICY", GetString(d.Get("microtenant_id"))) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + policySetID, err := fetchPolicySetIDByType(zClient, "CREDENTIAL_POLICY", microTenantID) if err != nil { return err } - // Setting the policy_set_id for further use d.Set("policy_set_id", policySetID) ruleID := d.Id() log.Printf("[INFO] Updating policy credential rule ID: %v\n", ruleID) @@ -230,8 +241,8 @@ func resourcePolicyCredentialAccessRuleUpdate(d *schema.ResourceData, m interfac if err := ValidatePolicyRuleConditions(d); err != nil { return err } - // Checking the current state of the rule to handle cases where it might have been deleted outside Terraform - _, respErr, err := service.GetPolicyRule(policySetID, ruleID) + + _, respErr, err := policysetcontrollerv2.GetPolicyRule(service, policySetID, ruleID) if err != nil { if respErr != nil && (respErr.StatusCode == http.StatusNotFound) { d.SetId("") @@ -239,27 +250,30 @@ func resourcePolicyCredentialAccessRuleUpdate(d *schema.ResourceData, m interfac } return err } - _, err = service.UpdateRule(policySetID, ruleID, req) - if err != nil { + + if _, err := policysetcontrollerv2.UpdateRule(service, policySetID, ruleID, req); err != nil { return err } return resourcePolicyCredentialAccessRuleRead(d, m) } func resourcePolicyCredentialAccessRuleDelete(d *schema.ResourceData, m interface{}) error { - client := m.(*Client) + zClient := m.(*Client) microTenantID := GetString(d.Get("microtenant_id")) - // Assume "CREDENTIAL_POLICY" is the policy type for this resource. Adjust as needed. - policySetID, err := fetchPolicySetIDByType(client, "CREDENTIAL_POLICY", microTenantID) + policySetID, err := fetchPolicySetIDByType(zClient, "CREDENTIAL_POLICY", microTenantID) if err != nil { return err } log.Printf("[INFO] Deleting policy credential rule with id %v\n", d.Id()) - service := client.policysetcontrollerv2.WithMicroTenant(microTenantID) - if _, err := service.Delete(policySetID, d.Id()); err != nil { + service := zClient.PolicySetControllerV2 + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + if _, err := policysetcontrollerv2.Delete(service, policySetID, d.Id()); err != nil { return err } diff --git a/zpa/resource_zpa_policy_credential_access_rule_test.go b/zpa/resource_zpa_policy_credential_access_rule_test.go index 1f1964c6..61b5b761 100644 --- a/zpa/resource_zpa_policy_credential_access_rule_test.go +++ b/zpa/resource_zpa_policy_credential_access_rule_test.go @@ -10,6 +10,7 @@ import ( "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/resourcetype" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/method" "github.com/zscaler/terraform-provider-zpa/v3/zpa/common/testing/variable" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontrollerv2" ) func TestAccResourcePolicyCredentialAccessRuleBasic(t *testing.T) { @@ -62,7 +63,7 @@ func TestAccResourcePolicyCredentialAccessRuleBasic(t *testing.T) { func testAccCheckPolicyCredentialAccessRuleDestroy(s *terraform.State) error { apiClient := testAccProvider.Meta().(*Client) - accessPolicy, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CREDENTIAL_POLICY") + accessPolicy, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CREDENTIAL_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CREDENTIAL_POLICY. Received error: %s", err) } @@ -71,7 +72,7 @@ func testAccCheckPolicyCredentialAccessRuleDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.policysetcontrollerv2.GetPolicyRule(accessPolicy.ID, rs.Primary.ID) + rule, _, err := policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, accessPolicy.ID, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -96,11 +97,11 @@ func testAccCheckPolicyCredentialAccessRuleExists(resource string) resource.Test } apiClient := testAccProvider.Meta().(*Client) - resp, _, err := apiClient.policysetcontrollerv2.GetByPolicyType("CREDENTIAL_POLICY") + resp, _, err := policysetcontrollerv2.GetByPolicyType(apiClient.PolicySetControllerV2, "CREDENTIAL_POLICY") if err != nil { return fmt.Errorf("failed fetching resource CREDENTIAL_POLICY. Recevied error: %s", err) } - _, _, err = apiClient.policysetcontrollerv2.GetPolicyRule(resp.ID, rs.Primary.ID) + _, _, err = policysetcontrollerv2.GetPolicyRule(apiClient.PolicySetControllerV2, resp.ID, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_pra_approval.go b/zpa/resource_zpa_pra_approval.go index 4fb70a37..44246f2a 100644 --- a/zpa/resource_zpa_pra_approval.go +++ b/zpa/resource_zpa_pra_approval.go @@ -20,7 +20,13 @@ func resourcePRAPrivilegedApprovalController() *schema.Resource { Delete: resourcePRAPrivilegedApprovalControllerDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PRAApproval + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -28,7 +34,7 @@ func resourcePRAPrivilegedApprovalController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByEmailID(id) + resp, _, err := praapproval.GetByEmailID(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -153,7 +159,13 @@ func resourcePRAPrivilegedApprovalController() *schema.Resource { } func resourcePRAPrivilegedApprovalControllerCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } // Convert user-provided RFC 2822 start and end times to epoch format. startTimeStr, endTimeStr := d.Get("start_time").(string), d.Get("end_time").(string) @@ -179,7 +191,7 @@ func resourcePRAPrivilegedApprovalControllerCreate(d *schema.ResourceData, m int log.Printf("[INFO] Creating privileged approval with request\n%+v\n", req) - praApproval, _, err := service.Create(&req) + praApproval, _, err := praapproval.Create(service, &req) if err != nil { return err } @@ -191,9 +203,15 @@ func resourcePRAPrivilegedApprovalControllerCreate(d *schema.ResourceData, m int } func resourcePRAPrivilegedApprovalControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := service.Get(d.Id()) + resp, _, err := praapproval.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing privileged approval %s from state because it no longer exists in ZPA", d.Id()) @@ -217,7 +235,13 @@ func resourcePRAPrivilegedApprovalControllerRead(d *schema.ResourceData, m inter } func resourcePRAPrivilegedApprovalControllerUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating privileged approval ID: %v\n", id) @@ -244,14 +268,14 @@ func resourcePRAPrivilegedApprovalControllerUpdate(d *schema.ResourceData, m int req.StartTime = fmt.Sprintf("%d", startTimeEpoch) req.EndTime = fmt.Sprintf("%d", endTimeEpoch) - if _, _, err := service.Get(id); err != nil { + if _, _, err := praapproval.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := praapproval.Update(service, id, &req); err != nil { return err } @@ -259,11 +283,17 @@ func resourcePRAPrivilegedApprovalControllerUpdate(d *schema.ResourceData, m int } func resourcePRAPrivilegedApprovalControllerDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praapproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting privileged approval ID: %v\n", d.Id()) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := praapproval.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_pra_approval_test.go b/zpa/resource_zpa_pra_approval_test.go index 0fb68888..7e1a8997 100644 --- a/zpa/resource_zpa_pra_approval_test.go +++ b/zpa/resource_zpa_pra_approval_test.go @@ -65,7 +65,7 @@ func testAccCheckPRAPrivilegedApprovalDestroy(s *terraform.State) error { continue } - group, _, err := apiClient.praapproval.Get(rs.Primary.ID) + group, _, err := praapproval.Get(apiClient.PRAApproval, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -90,7 +90,7 @@ func testAccCheckPRAPrivilegedApprovalExists(resource string, approval *praappro } apiClient := testAccProvider.Meta().(*Client) - receivedApproval, _, err := apiClient.praapproval.Get(rs.Primary.ID) + receivedApproval, _, err := praapproval.Get(apiClient.PRAApproval, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_pra_console_controller.go b/zpa/resource_zpa_pra_console_controller.go index b6f0e847..f6521193 100644 --- a/zpa/resource_zpa_pra_console_controller.go +++ b/zpa/resource_zpa_pra_console_controller.go @@ -17,7 +17,13 @@ func resourcePRAConsoleController() *schema.Resource { Delete: resourcePRAConsoleControllerDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PRAConsole + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -25,7 +31,7 @@ func resourcePRAConsoleController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := praconsole.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -109,12 +115,18 @@ func resourcePRAConsoleController() *schema.Resource { } func resourcePRAConsoleControllerCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAConsole + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandPRAConsole(d) log.Printf("[INFO] Creating pra console with request\n%+v\n", req) - praConsole, _, err := service.Create(&req) + praConsole, _, err := praconsole.Create(service, &req) if err != nil { return err } @@ -125,9 +137,15 @@ func resourcePRAConsoleControllerCreate(d *schema.ResourceData, m interface{}) e } func resourcePRAConsoleControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAConsole + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := service.Get(d.Id()) + resp, _, err := praconsole.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing pra console %s from state because it no longer exists in ZPA", d.Id()) @@ -152,20 +170,26 @@ func resourcePRAConsoleControllerRead(d *schema.ResourceData, m interface{}) err } func resourcePRAConsoleControllerUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAConsole + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating pra console ID: %v\n", id) req := expandPRAConsole(d) - if _, _, err := service.Get(id); err != nil { + if _, _, err := praconsole.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := praconsole.Update(service, id, &req); err != nil { return err } @@ -173,11 +197,17 @@ func resourcePRAConsoleControllerUpdate(d *schema.ResourceData, m interface{}) e } func resourcePRAConsoleControllerDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAConsole + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting pra console ID: %v\n", d.Id()) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := praconsole.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_pra_console_controller_test.go b/zpa/resource_zpa_pra_console_controller_test.go index a0c011c2..2b0141d8 100644 --- a/zpa/resource_zpa_pra_console_controller_test.go +++ b/zpa/resource_zpa_pra_console_controller_test.go @@ -70,7 +70,7 @@ func testAccCheckPRAConsoleControllerDestroy(s *terraform.State) error { continue } - console, _, err := apiClient.praconsole.Get(rs.Primary.ID) + console, _, err := praconsole.Get(apiClient.PRAConsole, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -95,7 +95,7 @@ func testAccCheckPRAConsoleControllerExists(resource string, console *praconsole } apiClient := testAccProvider.Meta().(*Client) - receivedConsole, _, err := apiClient.praconsole.Get(rs.Primary.ID) + receivedConsole, _, err := praconsole.Get(apiClient.PRAConsole, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_pra_credential_controller.go b/zpa/resource_zpa_pra_credential_controller.go index 376f0956..2749dac0 100644 --- a/zpa/resource_zpa_pra_credential_controller.go +++ b/zpa/resource_zpa_pra_credential_controller.go @@ -19,7 +19,13 @@ func resourcePRACredentialController() *schema.Resource { Delete: resourcePRACredentialControllerDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PRACredential + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -27,7 +33,7 @@ func resourcePRACredentialController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := pracredential.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -103,12 +109,18 @@ func resourcePRACredentialController() *schema.Resource { } func resourcePRACredentialControllerCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRACredential + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandPRACredentialController(d) log.Printf("[INFO] Creating credential controller with request\n%+v\n", req) - credController, _, err := service.Create(&req) + credController, _, err := pracredential.Create(service, &req) if err != nil { return err } @@ -120,9 +132,15 @@ func resourcePRACredentialControllerCreate(d *schema.ResourceData, m interface{} } func resourcePRACredentialControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRACredential - resp, _, err := service.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := pracredential.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing credential controller %s from state because it no longer exists in ZPA", d.Id()) @@ -149,20 +167,21 @@ func resourcePRACredentialControllerUpdate(d *schema.ResourceData, m interface{} return fmt.Errorf("changing 'credential_type' from '%s' to '%s' is not allowed", oldType, newType) } - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAApproval.WithMicroTenant(GetString(d.Get("microtenant_id"))) id := d.Id() log.Printf("[INFO] Updating credential controller ID: %v\n", id) req := expandPRACredentialController(d) - if _, _, err := service.Get(id); err != nil { + if _, _, err := pracredential.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := pracredential.Update(service, id, &req); err != nil { return err } @@ -170,11 +189,17 @@ func resourcePRACredentialControllerUpdate(d *schema.ResourceData, m interface{} } func resourcePRACredentialControllerDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).pracredential.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRACredential + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting credential controller ID: %v\n", d.Id()) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := pracredential.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_pra_credential_controller_test.go b/zpa/resource_zpa_pra_credential_controller_test.go index e4fd7309..e67a53b7 100644 --- a/zpa/resource_zpa_pra_credential_controller_test.go +++ b/zpa/resource_zpa_pra_credential_controller_test.go @@ -77,7 +77,7 @@ func testAccCheckPRACredentialControllerDestroy(s *terraform.State) error { continue } - group, _, err := apiClient.pracredential.Get(rs.Primary.ID) + group, _, err := pracredential.Get(apiClient.PRACredential, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -102,7 +102,7 @@ func testAccCheckPRACredentialControllerExists(resource string, credential *prac } apiClient := testAccProvider.Meta().(*Client) - receivedCredential, _, err := apiClient.pracredential.Get(rs.Primary.ID) + receivedCredential, _, err := pracredential.Get(apiClient.PRACredential, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_pra_portal_controller.go b/zpa/resource_zpa_pra_portal_controller.go index d331cd29..d0023713 100644 --- a/zpa/resource_zpa_pra_portal_controller.go +++ b/zpa/resource_zpa_pra_portal_controller.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praconsole" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/privilegedremoteaccess/praportal" ) @@ -19,7 +20,13 @@ func resourcePRAPortalController() *schema.Resource { Delete: resourcePRAPortalControllerDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.PRAPortal + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -27,7 +34,7 @@ func resourcePRAPortalController() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := praportal.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -90,12 +97,18 @@ func resourcePRAPortalController() *schema.Resource { } func resourcePRAPortalControllerCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAPortal + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandPRAPortalController(d) log.Printf("[INFO] Creating pra portal controller with request\n%+v\n", req) - praPortal, _, err := service.Create(&req) + praPortal, _, err := praportal.Create(service, &req) if err != nil { return err } @@ -106,9 +119,15 @@ func resourcePRAPortalControllerCreate(d *schema.ResourceData, m interface{}) er } func resourcePRAPortalControllerRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAPortal - resp, _, err := service.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := praportal.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing pra portal controller %s from state because it no longer exists in ZPA", d.Id()) @@ -133,20 +152,26 @@ func resourcePRAPortalControllerRead(d *schema.ResourceData, m interface{}) erro } func resourcePRAPortalControllerUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.PRAPortal + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating pra portal controller ID: %v\n", id) req := expandPRAPortalController(d) - if _, _, err := service.Get(id); err != nil { + if _, _, err := praportal.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := praportal.Update(service, id, &req); err != nil { return err } @@ -158,15 +183,15 @@ func resourcePRAPortalControllerDelete(d *schema.ResourceData, m interface{}) er portalID := d.Id() // Detach the portal from any consoles before attempting to delete it. - consoleService := client.praconsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) + consoleService := client.PRAConsole.WithMicroTenant(GetString(d.Get("microtenant_id"))) if err := detachAndCleanUpPRAPortals(portalID, consoleService); err != nil { return fmt.Errorf("error detaching PRAPortal with ID %s from PRAConsoleControllers: %s", portalID, err) } // Proceed with deletion of the portal after successful detachment. - service := client.praportal.WithMicroTenant(GetString(d.Get("microtenant_id"))) + service := client.PRAPortal.WithMicroTenant(GetString(d.Get("microtenant_id"))) log.Printf("[INFO] Deleting PRA Portal Controller with ID: %s", portalID) - if _, err := service.Delete(portalID); err != nil { + if _, err := praportal.Delete(service, portalID); err != nil { return fmt.Errorf("error deleting PRA Portal Controller with ID %s: %s", portalID, err) } @@ -191,9 +216,9 @@ func expandPRAPortalController(d *schema.ResourceData) praportal.PRAPortal { } // Detach and optionally delete PRAPortalControllers from PRAConsoleControllers. -func detachAndCleanUpPRAPortals(portalID string, consoleService *praconsole.Service) error { +func detachAndCleanUpPRAPortals(portalID string, consoleService *services.Service) error { // Fetch all PRAConsoleControllers - consoles, _, err := consoleService.GetAll() + consoles, _, err := praconsole.GetAll(consoleService) if err != nil { return fmt.Errorf("failed to list all PRAConsoleControllers: %s", err) } @@ -220,7 +245,7 @@ func detachAndCleanUpPRAPortals(portalID string, consoleService *praconsole.Serv if len(updatedPortals) == 0 { // Delete the console if it no longer contains any portals - _, err = consoleService.Delete(console.ID) + _, err = praconsole.Delete(consoleService, console.ID) if err != nil { return fmt.Errorf("failed to delete PRAConsoleController with ID %s: %s", console.ID, err) } @@ -228,7 +253,7 @@ func detachAndCleanUpPRAPortals(portalID string, consoleService *praconsole.Serv } else { // Update the console with the remaining portals console.PRAPortals = updatedPortals - _, err = consoleService.Update(console.ID, &console) + _, err = praconsole.Update(consoleService, console.ID, &console) if err != nil { return fmt.Errorf("failed to update PRAConsoleController with ID %s: %s", console.ID, err) } diff --git a/zpa/resource_zpa_pra_portal_controller_test.go b/zpa/resource_zpa_pra_portal_controller_test.go index 38b1ecdd..c452dbe1 100644 --- a/zpa/resource_zpa_pra_portal_controller_test.go +++ b/zpa/resource_zpa_pra_portal_controller_test.go @@ -70,7 +70,7 @@ func testAccCheckPRAPortalControllerDestroy(s *terraform.State) error { continue } - group, _, err := apiClient.praportal.Get(rs.Primary.ID) + group, _, err := praportal.Get(apiClient.PRAPortal, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -95,7 +95,7 @@ func testAccCheckPRAPortalControllerExists(resource string, portal *praportal.PR } apiClient := testAccProvider.Meta().(*Client) - receivedPortal, _, err := apiClient.praportal.Get(rs.Primary.ID) + receivedPortal, _, err := praportal.Get(apiClient.PRAPortal, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_provisioning_key.go b/zpa/resource_zpa_provisioning_key.go index 864d0c38..640471f2 100644 --- a/zpa/resource_zpa_provisioning_key.go +++ b/zpa/resource_zpa_provisioning_key.go @@ -19,7 +19,14 @@ func resourceProvisioningKey() *schema.Resource { Delete: resourceProvisioningKeyDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) _, associationTypeSet := d.GetOk("association_type") @@ -27,7 +34,7 @@ func resourceProvisioningKey() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) if !associationTypeSet { - _, assoc_type, _, err := service.GetByIDAllAssociations(id) + _, assoc_type, _, err := provisioningkey.GetByIDAllAssociations(service, id) if err != nil { return []*schema.ResourceData{d}, err } else { @@ -35,7 +42,7 @@ func resourceProvisioningKey() *schema.Resource { } } } else { - resp, assoc_type, _, err := service.GetByNameAllAssociations(id) + resp, assoc_type, _, err := provisioningkey.GetByNameAllAssociations(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -142,7 +149,14 @@ func getAssociationType(d *schema.ResourceData) (string, bool) { } func resourceProvisioningKeyCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + associationType, ok := getAssociationType(d) if !ok { return fmt.Errorf("associationType is required") @@ -150,7 +164,7 @@ func resourceProvisioningKeyCreate(d *schema.ResourceData, m interface{}) error req := expandProvisioningKey(d) log.Printf("[INFO] Creating zpa provisining key with request\n%+v\n", req) - resp, _, err := service.Create(associationType, &req) + resp, _, err := provisioningkey.Create(service, associationType, &req) if err != nil { return err } @@ -161,12 +175,19 @@ func resourceProvisioningKeyCreate(d *schema.ResourceData, m interface{}) error } func resourceProvisioningKeyRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + associationType, ok := getAssociationType(d) if !ok { return fmt.Errorf("associationType is required") } - resp, _, err := service.Get(associationType, d.Id()) + resp, _, err := provisioningkey.Get(service, associationType, d.Id()) if err != nil { if obj, ok := err.(*client.ErrorResponse); ok && obj.IsObjectNotFound() { log.Printf("[WARN] Removing provisining key %s from state because it no longer exists in ZPA", d.Id()) @@ -195,7 +216,14 @@ func resourceProvisioningKeyRead(d *schema.ResourceData, m interface{}) error { } func resourceProvisioningKeyUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + associationType, ok := getAssociationType(d) if !ok { return fmt.Errorf("associationType is required") @@ -203,14 +231,14 @@ func resourceProvisioningKeyUpdate(d *schema.ResourceData, m interface{}) error id := d.Id() log.Printf("[INFO] Updating provisining key ID: %v\n", id) req := expandProvisioningKey(d) - if _, _, err := service.Get(associationType, id); err != nil { + if _, _, err := provisioningkey.Get(service, associationType, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(associationType, id, &req); err != nil { + if _, err := provisioningkey.Update(service, associationType, id, &req); err != nil { return err } @@ -218,14 +246,21 @@ func resourceProvisioningKeyUpdate(d *schema.ResourceData, m interface{}) error } func resourceProvisioningKeyDelete(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).provisioningkey.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ProvisioningKey + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + associationType, ok := getAssociationType(d) if !ok { return fmt.Errorf("associationType is required") } log.Printf("[INFO] Deleting provisining key ID: %v\n", d.Id()) - if _, err := service.Delete(associationType, d.Id()); err != nil { + if _, err := provisioningkey.Delete(service, associationType, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_provisioning_key_test.go b/zpa/resource_zpa_provisioning_key_test.go index 33ebf01e..a45d783c 100644 --- a/zpa/resource_zpa_provisioning_key_test.go +++ b/zpa/resource_zpa_provisioning_key_test.go @@ -72,7 +72,7 @@ func testAccCheckProvisioningKeyDestroyAppConnector(s *terraform.State) error { continue } - rule, _, err := apiClient.provisioningkey.GetByName(rs.Primary.Attributes["association_type"], rs.Primary.Attributes["name"]) + rule, _, err := provisioningkey.GetByName(apiClient.ProvisioningKey, rs.Primary.Attributes["association_type"], rs.Primary.Attributes["name"]) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -86,7 +86,7 @@ func testAccCheckProvisioningKeyDestroyAppConnector(s *terraform.State) error { return nil } -func testAccCheckProvisioningKeyAppConnectorExists(resource string, provisioningkey *provisioningkey.ProvisioningKey) resource.TestCheckFunc { +func testAccCheckProvisioningKeyAppConnectorExists(resource string, provisioningKey *provisioningkey.ProvisioningKey) resource.TestCheckFunc { return func(state *terraform.State) error { rs, ok := state.RootModule().Resources[resource] if !ok { @@ -97,11 +97,11 @@ func testAccCheckProvisioningKeyAppConnectorExists(resource string, provisioning } apiClient := testAccProvider.Meta().(*Client) - receivedKey, _, err := apiClient.provisioningkey.GetByName(rs.Primary.Attributes["association_type"], rs.Primary.Attributes["name"]) + receivedKey, _, err := provisioningkey.GetByName(apiClient.ProvisioningKey, rs.Primary.Attributes["association_type"], rs.Primary.Attributes["name"]) if err != nil { - return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) + return fmt.Errorf("failed fetching resource %s. Received error: %s", resource, err) } - *provisioningkey = *receivedKey + *provisioningKey = *receivedKey return nil } diff --git a/zpa/resource_zpa_segment_group.go b/zpa/resource_zpa_segment_group.go index 7abdd0ce..3cfcc8a9 100644 --- a/zpa/resource_zpa_segment_group.go +++ b/zpa/resource_zpa_segment_group.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" ) @@ -19,7 +20,13 @@ func resourceSegmentGroup() *schema.Resource { Delete: resourceSegmentGroupDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.SegmentGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -27,7 +34,7 @@ func resourceSegmentGroup() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := segmentgroup.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -82,12 +89,18 @@ func resourceSegmentGroup() *schema.Resource { } func resourceSegmentGroupCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.SegmentGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandSegmentGroup(d) log.Printf("[INFO] Creating segment group with request\n%+v\n", req) - segmentgroup, _, err := service.Create(&req) + segmentgroup, _, err := segmentgroup.Create(service, &req) if err != nil { return err } @@ -98,9 +111,15 @@ func resourceSegmentGroupCreate(d *schema.ResourceData, m interface{}) error { } func resourceSegmentGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.SegmentGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := service.Get(d.Id()) + resp, _, err := segmentgroup.Get(service, d.Id()) if err != nil { if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { log.Printf("[WARN] Removing segment group %s from state because it no longer exists in ZPA", d.Id()) @@ -135,37 +154,45 @@ func flattenSegmentGroupApplicationsSimple(segmentGroup *segmentgroup.SegmentGro } func resourceSegmentGroupUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.SegmentGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() log.Printf("[INFO] Updating segment group ID: %v\n", id) req := expandSegmentGroup(d) - if _, _, err := service.Get(id); err != nil { + if _, _, err := segmentgroup.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := segmentgroup.Update(service, id, &req); err != nil { return err } return resourceSegmentGroupRead(d, m) } -func detachSegmentGroupFromAllPolicyRules(id string, policySetControllerService *policysetcontroller.Service) { +func detachSegmentGroupFromAllPolicyRules(id string, policySetControllerService *services.Service) { policyRulesDetchLock.Lock() defer policyRulesDetchLock.Unlock() + var rules []policysetcontroller.PolicyRule types := []string{"ACCESS_POLICY", "TIMEOUT_POLICY", "SIEM_POLICY", "CLIENT_FORWARDING_POLICY", "INSPECTION_POLICY"} + for _, t := range types { - policySet, _, err := policySetControllerService.GetByPolicyType(t) + policySet, _, err := policysetcontroller.GetByPolicyType(policySetControllerService, t) if err != nil { continue } - r, _, err := policySetControllerService.GetAllByType(t) + r, _, err := policysetcontroller.GetAllByType(policySetControllerService, t) if err != nil { continue } @@ -174,6 +201,7 @@ func detachSegmentGroupFromAllPolicyRules(id string, policySetControllerService rules = append(rules, rule) } } + for _, rule := range rules { changed := false for i, condition := range rule.Conditions { @@ -191,7 +219,7 @@ func detachSegmentGroupFromAllPolicyRules(id string, policySetControllerService rule.Conditions = []policysetcontroller.Conditions{} } if changed { - if _, err := policySetControllerService.UpdateRule(rule.PolicySetID, rule.ID, &rule); err != nil { + if _, err := policysetcontroller.UpdateRule(policySetControllerService, rule.PolicySetID, rule.ID, &rule); err != nil { continue } } @@ -200,13 +228,15 @@ func detachSegmentGroupFromAllPolicyRules(id string, policySetControllerService func resourceSegmentGroupDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) - policySetControllerService := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) - service := zClient.segmentgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + microTenantID := GetString(d.Get("microtenant_id")) + policySetControllerService := zClient.PolicySetController.WithMicroTenant(microTenantID) + service := zClient.SegmentGroup.WithMicroTenant(microTenantID) + log.Printf("[INFO] Deleting segment group ID: %v\n", d.Id()) detachSegmentGroupFromAllPolicyRules(d.Id(), policySetControllerService) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := segmentgroup.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_segment_group_test.go b/zpa/resource_zpa_segment_group_test.go index 499ab836..42c2dfe1 100644 --- a/zpa/resource_zpa_segment_group_test.go +++ b/zpa/resource_zpa_segment_group_test.go @@ -64,7 +64,7 @@ func testAccCheckSegmentGroupDestroy(s *terraform.State) error { continue } - group, _, err := apiClient.segmentgroup.Get(rs.Primary.ID) + group, _, err := segmentgroup.Get(apiClient.SegmentGroup, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -89,7 +89,7 @@ func testAccCheckSegmentGroupExists(resource string, group *segmentgroup.Segment } apiClient := testAccProvider.Meta().(*Client) - receivedGroup, _, err := apiClient.segmentgroup.Get(rs.Primary.ID) + receivedGroup, _, err := segmentgroup.Get(apiClient.SegmentGroup, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_server_group.go b/zpa/resource_zpa_server_group.go index 3a91de76..765cad60 100644 --- a/zpa/resource_zpa_server_group.go +++ b/zpa/resource_zpa_server_group.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/appconnectorgroup" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/applicationsegment" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/policysetcontroller" @@ -25,7 +26,13 @@ func resourceServerGroup() *schema.Resource { Delete: resourceServerGroupDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.ServerGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -33,7 +40,7 @@ func resourceServerGroup() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := servergroup.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -144,7 +151,13 @@ func resourceServerGroup() *schema.Resource { } func resourceServerGroupCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServerGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } req := expandServerGroup(d) log.Printf("[INFO] Creating zpa server group with request\n%+v\n", req) @@ -156,7 +169,7 @@ func resourceServerGroupCreate(d *schema.ResourceData, m interface{}) error { log.Printf("[ERROR] Servers must not be empty when DynamicDiscovery is disabled\n") return fmt.Errorf("servers must not be empty when DynamicDiscovery is disabled") } - resp, _, err := service.Create(&req) + resp, _, err := servergroup.Create(service, &req) if err != nil { return err } @@ -167,9 +180,15 @@ func resourceServerGroupCreate(d *schema.ResourceData, m interface{}) error { } func resourceServerGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServerGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } - resp, _, err := service.Get(d.Id()) + resp, _, err := servergroup.Get(service, d.Id()) if err != nil { if err.(*client.ErrorResponse).IsObjectNotFound() { log.Printf("[WARN] Removing server group %s from state because it no longer exists in ZPA", d.Id()) @@ -222,7 +241,14 @@ func flattenServerGroupApplicationsSimple(apps []servergroup.Applications) []int } func resourceServerGroupUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServerGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + id := d.Id() log.Printf("[INFO] Updating server group ID: %v\n", id) req := expandServerGroup(d) @@ -235,27 +261,62 @@ func resourceServerGroupUpdate(d *schema.ResourceData, m interface{}) error { return fmt.Errorf("can't update server group: servers must not be empty when DynamicDiscovery is disabled") } - if _, _, err := service.Get(id); err != nil { + if _, _, err := servergroup.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := servergroup.Update(service, id, &req); err != nil { return err } return resourceServerGroupRead(d, m) } -func detachServerGroupFromAllAccessPolicyRules(id string, policySetControllerService *policysetcontroller.Service) { +func resourceServerGroupDelete(d *schema.ResourceData, m interface{}) error { + zClient := m.(*Client) + microTenantID := GetString(d.Get("microtenant_id")) + + applicationSegmentService := zClient.ApplicationSegment + policySetControllerService := zClient.PolicySetController + appConnectorGroupService := zClient.AppConnectorGroup + service := zClient.ServerGroup + + if microTenantID != "" { + applicationSegmentService = applicationSegmentService.WithMicroTenant(microTenantID) + policySetControllerService = policySetControllerService.WithMicroTenant(microTenantID) + appConnectorGroupService = appConnectorGroupService.WithMicroTenant(microTenantID) + service = service.WithMicroTenant(microTenantID) + } + + log.Printf("[INFO] Deleting server group ID: %v\n", d.Id()) + + err := detachServerGroupFromAppConnectorGroups(d.Id(), service, appConnectorGroupService) + if err != nil { + log.Printf("[ERROR] Detaching server group ID: %v from app connector groups failed: %v\n", d.Id(), err) + } + + detachServerGroupFromAllAccessPolicyRules(d.Id(), policySetControllerService) + detachServerGroupFromAllAppSegments(d.Id(), applicationSegmentService) + + if _, err := servergroup.Delete(service, d.Id()); err != nil { + return err + } + d.SetId("") + log.Printf("[INFO] Server group deleted") + return nil +} + +func detachServerGroupFromAllAccessPolicyRules(id string, policySetControllerService *services.Service) { policyRulesDetchLock.Lock() defer policyRulesDetchLock.Unlock() - accessPolicySet, _, err := policySetControllerService.GetByPolicyType("ACCESS_POLICY") + + accessPolicySet, _, err := policysetcontroller.GetByPolicyType(policySetControllerService, "ACCESS_POLICY") if err != nil { return } - accessPolicyRules, _, err := policySetControllerService.GetAllByType("ACCESS_POLICY") + accessPolicyRules, _, err := policysetcontroller.GetAllByType(policySetControllerService, "ACCESS_POLICY") if err != nil { return } @@ -273,68 +334,48 @@ func detachServerGroupFromAllAccessPolicyRules(id string, policySetControllerSer } accessPolicyRule.AppServerGroups = ids if changed { - if _, err := policySetControllerService.UpdateRule(accessPolicySet.ID, accessPolicyRule.ID, &accessPolicyRule); err != nil { + if _, err := policysetcontroller.UpdateRule(policySetControllerService, accessPolicySet.ID, accessPolicyRule.ID, &accessPolicyRule); err != nil { continue } } } } -func detachServerGroupFromAllAppSegments(id string, applicationSegmentService *applicationsegment.Service) { - apps, _, err := applicationSegmentService.GetAll() +func detachServerGroupFromAllAppSegments(id string, applicationSegmentService *services.Service) { + apps, _, err := applicationsegment.GetAll(applicationSegmentService) if err != nil { return } for _, app := range apps { ids := []applicationsegment.AppServerGroups{} - for _, app := range app.ServerGroups { - if app.ID == id { + for _, appServerGroup := range app.ServerGroups { + if appServerGroup.ID == id { continue } ids = append(ids, applicationsegment.AppServerGroups{ - ID: app.ID, + ID: appServerGroup.ID, }) } app.ServerGroups = ids - if _, err := applicationSegmentService.Update(app.ID, app); err != nil { + if _, err := applicationsegment.Update(applicationSegmentService, app.ID, app); err != nil { continue } } } -func resourceServerGroupDelete(d *schema.ResourceData, m interface{}) error { - applicationSegmentService := m.(*Client).applicationsegment.WithMicroTenant(GetString(d.Get("microtenant_id"))) - policySetControllerService := m.(*Client).policysetcontroller.WithMicroTenant(GetString(d.Get("microtenant_id"))) - appConnectorGroupService := m.(*Client).appconnectorgroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) - service := m.(*Client).servergroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) - log.Printf("[INFO] Deleting server group ID: %v\n", d.Id()) - err := detachServerGroupFromAppConnectorGroups(d.Id(), service, appConnectorGroupService) +func detachServerGroupFromAppConnectorGroups(serverGroupID string, serverGroupService *services.Service, appConnectorGroupService *services.Service) error { + log.Printf("[INFO] Detaching Server Group %s from App Connector Groups\n", serverGroupID) + serverGroup, _, err := servergroup.Get(serverGroupService, serverGroupID) if err != nil { - log.Printf("[ERROR] Detaching server group ID: %v from app connector groups failed:%v\n", d.Id(), err) - } - - detachServerGroupFromAllAccessPolicyRules(d.Id(), policySetControllerService) - detachServerGroupFromAllAppSegments(d.Id(), applicationSegmentService) - - if _, err := service.Delete(d.Id()); err != nil { return err } - d.SetId("") - log.Printf("[INFO] server group deleted") - return nil -} -func detachServerGroupFromAppConnectorGroups(serverGroupID string, serevrGroupService *servergroup.Service, apponnectorGroupService *appconnectorgroup.Service) error { - log.Printf("[INFO] Detaching Server Group %s from App Connector Groups\n", serverGroupID) - serverGroup, _, err := serevrGroupService.Get(serverGroupID) - if err != nil { - return err - } // lock to avoid updating app connector group with a deleted server group ID when running in parallel detachLock.Lock() defer detachLock.Unlock() + for _, appConnectorGroup := range serverGroup.AppConnectorGroups { - app, _, err := apponnectorGroupService.Get(appConnectorGroup.ID) + app, _, err := appconnectorgroup.Get(appConnectorGroupService, appConnectorGroup.ID) if err != nil { continue } @@ -346,7 +387,7 @@ func detachServerGroupFromAppConnectorGroups(serverGroupID string, serevrGroupSe appServerGroups = append(appServerGroups, s) } app.AppServerGroup = appServerGroups - _, err = apponnectorGroupService.Update(app.ID, app) + _, err = appconnectorgroup.Update(appConnectorGroupService, app.ID, app) if err != nil { continue } diff --git a/zpa/resource_zpa_server_group_test.go b/zpa/resource_zpa_server_group_test.go index ee7baa60..52756a1a 100644 --- a/zpa/resource_zpa_server_group_test.go +++ b/zpa/resource_zpa_server_group_test.go @@ -66,7 +66,7 @@ func testAccCheckServerGroupDestroy(s *terraform.State) error { continue } - rule, _, err := apiClient.servergroup.Get(rs.Primary.ID) + rule, _, err := servergroup.Get(apiClient.ServerGroup, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -91,7 +91,7 @@ func testAccCheckServerGroupExists(resource string, rule *servergroup.ServerGrou } apiClient := testAccProvider.Meta().(*Client) - receivedGroup, _, err := apiClient.servergroup.Get(rs.Primary.ID) + receivedGroup, _, err := servergroup.Get(apiClient.ServerGroup, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/resource_zpa_service_edge_assistant_schedule.go b/zpa/resource_zpa_service_edge_assistant_schedule.go new file mode 100644 index 00000000..6706ccb3 --- /dev/null +++ b/zpa/resource_zpa_service_edge_assistant_schedule.go @@ -0,0 +1,176 @@ +package zpa + +import ( + "fmt" + "log" + "os" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + client "github.com/zscaler/zscaler-sdk-go/v2/zpa" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/serviceedgeschedule" +) + +func resourceServiceEdgeAssistantSchedule() *schema.Resource { + return &schema.Resource{ + Create: resourceServiceEdgeAssistantScheduleCreate, + Read: resourceServiceEdgeAssistantScheduleRead, + Update: resourceServiceEdgeAssistantScheduleUpdate, + Delete: resourceServiceEdgeAssistantScheduleDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "customer_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, // Keep this to allow the value to be computed if not set + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "delete_disabled": { + Type: schema.TypeBool, + Optional: true, + }, + "frequency": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "days", + }, false), + }, + "frequency_interval": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "5", + "7", + "14", + "30", + "60", + "90", + }, false), + }, + }, + } +} + +func resourceServiceEdgeAssistantScheduleCreate(d *schema.ResourceData, m interface{}) error { + zClient := m.(*Client) + service := zClient.ServiceEdgeSchedule + + req, err := expandServiceEdgeAssistantSchedule(d) + if err != nil { + return err + } + + // Use = instead of := because err is already declared + _, _, err = serviceedgeschedule.CreateSchedule(service, req) + if err != nil { + // Assuming err.Error() returns a string representation of the error + errStr := err.Error() + + // Check if the error string contains the specific message indicating the resource already exists + if strings.Contains(errStr, "resource.already.exist") { + log.Printf("[INFO] Resource already exists. Updating instead.") + + // Get the current state of the resource + resp, _, err := serviceedgeschedule.GetSchedule(service) + if err != nil { + return fmt.Errorf("failed to retrieve existing resource for update: %v", err) + } + + // Set the resource ID in the Terraform state + d.SetId(resp.ID) + + // Proceed to update the resource + return resourceServiceEdgeAssistantScheduleUpdate(d, m) + } + return err + } + log.Printf("[INFO] Created service edge assistant schedule request. ID: %v\n", req.ID) + d.SetId(req.ID) + + return resourceServiceEdgeAssistantScheduleRead(d, m) +} + +func resourceServiceEdgeAssistantScheduleRead(d *schema.ResourceData, m interface{}) error { + zClient := m.(*Client) + service := zClient.ServiceEdgeSchedule + + resp, _, err := serviceedgeschedule.GetSchedule(service) + if err != nil { + if errResp, ok := err.(*client.ErrorResponse); ok && errResp.IsObjectNotFound() { + log.Printf("[WARN] Removing service edge assistant schedule %s from state because it no longer exists in ZPA", d.Id()) + d.SetId("") + return nil + } + + return err + } + + log.Printf("[INFO] Getting application server:\n%+v\n", resp) + _ = d.Set("customer_id", resp.CustomerID) + _ = d.Set("enabled", resp.Enabled) + _ = d.Set("delete_disabled", resp.DeleteDisabled) + _ = d.Set("frequency", resp.Frequency) + _ = d.Set("frequency_interval", resp.FrequencyInterval) + return nil +} + +func resourceServiceEdgeAssistantScheduleUpdate(d *schema.ResourceData, m interface{}) error { + zClient := m.(*Client) + service := zClient.ServiceEdgeSchedule + + id := d.Id() + log.Printf("[INFO] Updating service edge ID: %v\n", id) + req, err := expandServiceEdgeAssistantSchedule(d) + if err != nil { + return err + } + + if _, _, err := serviceedgeschedule.GetSchedule(service); err != nil { + if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { + d.SetId("") + return nil + } + } + + if _, err := serviceedgeschedule.UpdateSchedule(service, id, &req); err != nil { + return err + } + + return resourceServiceEdgeAssistantScheduleRead(d, m) +} + +func resourceServiceEdgeAssistantScheduleDelete(d *schema.ResourceData, m interface{}) error { + return nil +} + +func expandServiceEdgeAssistantSchedule(d *schema.ResourceData) (serviceedgeschedule.AssistantSchedule, error) { + var customerID string + if id, exists := d.GetOk("customer_id"); exists { + customerID = id.(string) + } else if id := os.Getenv("ZPA_CUSTOMER_ID"); id != "" { + customerID = id + } else { + return serviceedgeschedule.AssistantSchedule{}, fmt.Errorf("customer_id must be provided either in the HCL or as an environment variable ZPA_CUSTOMER_ID") + } + + scheduler := serviceedgeschedule.AssistantSchedule{ + ID: d.Get("id").(string), + CustomerID: customerID, // Now guaranteed to be non-empty + Enabled: d.Get("enabled").(bool), + DeleteDisabled: d.Get("delete_disabled").(bool), + FrequencyInterval: d.Get("frequency_interval").(string), + Frequency: d.Get("frequency").(string), + } + return scheduler, nil +} diff --git a/zpa/resource_zpa_service_edge_group.go b/zpa/resource_zpa_service_edge_group.go index b932b436..623d97da 100644 --- a/zpa/resource_zpa_service_edge_group.go +++ b/zpa/resource_zpa_service_edge_group.go @@ -20,7 +20,13 @@ func resourceServiceEdgeGroup() *schema.Resource { Delete: resourceServiceEdgeGroupDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { - service := m.(*Client).serviceedgegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + client := m.(*Client) + service := client.ServiceEdgeGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } id := d.Id() _, parseIDErr := strconv.ParseInt(id, 10, 64) @@ -28,7 +34,7 @@ func resourceServiceEdgeGroup() *schema.Resource { // assume if the passed value is an int _ = d.Set("id", id) } else { - resp, _, err := service.GetByName(id) + resp, _, err := serviceedgegroup.GetByName(service, id) if err == nil { d.SetId(resp.ID) _ = d.Set("id", resp.ID) @@ -220,7 +226,13 @@ func resourceServiceEdgeGroup() *schema.Resource { } func resourceServiceEdgeGroupCreate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).serviceedgegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServiceEdgeGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } if err := validateAndSetProfileNameID(d); err != nil { return err @@ -228,7 +240,7 @@ func resourceServiceEdgeGroupCreate(d *schema.ResourceData, m interface{}) error req := expandServiceEdgeGroup(d) log.Printf("[INFO] Creating zpa service edge group with request\n%+v\n", req) - resp, _, err := service.Create(req) + resp, _, err := serviceedgegroup.Create(service, req) if err != nil { return err } @@ -239,9 +251,15 @@ func resourceServiceEdgeGroupCreate(d *schema.ResourceData, m interface{}) error } func resourceServiceEdgeGroupRead(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).serviceedgegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServiceEdgeGroup - resp, _, err := service.Get(d.Id()) + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } + + resp, _, err := serviceedgegroup.Get(service, d.Id()) if err != nil { if err.(*client.ErrorResponse).IsObjectNotFound() { log.Printf("[WARN] Removing service edge group %s from state because it no longer exists in ZPA", d.Id()) @@ -283,7 +301,13 @@ func resourceServiceEdgeGroupRead(d *schema.ResourceData, m interface{}) error { } func resourceServiceEdgeGroupUpdate(d *schema.ResourceData, m interface{}) error { - service := m.(*Client).serviceedgegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + zClient := m.(*Client) + service := zClient.ServiceEdgeGroup + + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } if err := validateAndSetProfileNameID(d); err != nil { return err @@ -292,14 +316,14 @@ func resourceServiceEdgeGroupUpdate(d *schema.ResourceData, m interface{}) error log.Printf("[INFO] Updating service edge group ID: %v\n", id) req := expandServiceEdgeGroup(d) - if _, _, err := service.Get(id); err != nil { + if _, _, err := serviceedgegroup.Get(service, id); err != nil { if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() { d.SetId("") return nil } } - if _, err := service.Update(id, &req); err != nil { + if _, err := serviceedgegroup.Update(service, id, &req); err != nil { return err } @@ -308,11 +332,15 @@ func resourceServiceEdgeGroupUpdate(d *schema.ResourceData, m interface{}) error func resourceServiceEdgeGroupDelete(d *schema.ResourceData, m interface{}) error { zClient := m.(*Client) - service := zClient.serviceedgegroup.WithMicroTenant(GetString(d.Get("microtenant_id"))) + service := zClient.ServiceEdgeGroup + microTenantID := GetString(d.Get("microtenant_id")) + if microTenantID != "" { + service = service.WithMicroTenant(microTenantID) + } log.Printf("[INFO] Deleting service edge group ID: %v\n", d.Id()) - if _, err := service.Delete(d.Id()); err != nil { + if _, err := serviceedgegroup.Delete(service, d.Id()); err != nil { return err } d.SetId("") diff --git a/zpa/resource_zpa_service_edge_group_test.go b/zpa/resource_zpa_service_edge_group_test.go index 6c00e40e..b4c8a3b4 100644 --- a/zpa/resource_zpa_service_edge_group_test.go +++ b/zpa/resource_zpa_service_edge_group_test.go @@ -74,7 +74,7 @@ func testAccCheckServiceEdgeGroupDestroy(s *terraform.State) error { continue } - group, _, err := apiClient.serviceedgegroup.Get(rs.Primary.ID) + group, _, err := serviceedgegroup.Get(apiClient.ServiceEdgeGroup, rs.Primary.ID) if err == nil { return fmt.Errorf("id %s already exists", rs.Primary.ID) @@ -99,7 +99,7 @@ func testAccCheckServiceEdgeGroupExists(resource string, group *serviceedgegroup } apiClient := testAccProvider.Meta().(*Client) - receivedGroup, _, err := apiClient.serviceedgegroup.Get(rs.Primary.ID) + receivedGroup, _, err := serviceedgegroup.Get(apiClient.ServiceEdgeGroup, rs.Primary.ID) if err != nil { return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) } diff --git a/zpa/utils.go b/zpa/utils.go index 4f9131f6..1cdc0de0 100755 --- a/zpa/utils.go +++ b/zpa/utils.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/common" + "github.com/zscaler/zscaler-sdk-go/v2/zpa/services/segmentgroup" ) func ValidateLatitude(val interface{}, _ string) (warns []string, errs []error) { @@ -275,3 +276,23 @@ func pluralize(count int, singular, plural string) string { } return plural } + +func detachSegmentGroup(client *Client, segmentID, segmentGroupID string) error { + log.Printf("[INFO] Detaching application segment %s from segment group: %s\n", segmentID, segmentGroupID) + service := client.SegmentGroup + + segGroup, _, err := segmentgroup.Get(service, segmentGroupID) + if err != nil { + log.Printf("[error] Error while getting segment group id: %s", segmentGroupID) + return err + } + adaptedApplications := []segmentgroup.Application{} + for _, app := range segGroup.Applications { + if app.ID != segmentID { + adaptedApplications = append(adaptedApplications, app) + } + } + segGroup.Applications = adaptedApplications + _, err = segmentgroup.Update(service, segmentGroupID, segGroup) + return err +}