diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0580bc834..e7bccb846 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,7 @@ jobs: - name: Lint uses: golangci/golangci-lint-action@v2 with: - args: --timeout 30m --build-tags unit,tf_acc_sysdig_monitor,tf_acc_sysdig_secure,tf_acc_ibm_monitor,tf_acc_ibm_secure + args: --timeout 30m test: name: Unit Tests diff --git a/.gitignore b/.gitignore index bbd52a210..c4a42665e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .DS_Store .envrc .env +.direnv/ example.tf terraform.tfplan terraform.tfstate diff --git a/GNUmakefile b/GNUmakefile index fcbb6a5b3..0c034d94b 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -1,6 +1,5 @@ SWEEP?=us-east-1,us-west-2 TEST?=./... -TEST_SUITE?=tf_acc_sysdig_monitor,tf_acc_sysdig_secure PKG_NAME=sysdig WEBSITE_REPO=github.com/hashicorp/terraform-website VERSION=$(shell [ ! -z `git tag -l --contains HEAD` ] && git tag -l --contains HEAD || git rev-parse --short HEAD) @@ -35,14 +34,14 @@ sweep: go test $(TEST) -v -sweep=$(SWEEP) $(SWEEPARGS) test: fmtcheck - go test $(TEST) -tags=unit -timeout=30s -parallel=4 + go test $(TEST) -timeout=30s -parallel=4 testacc: fmtcheck - CGO_ENABLED=1 TF_ACC=1 go test $(TEST) -v $(TESTARGS) -tags=$(TEST_SUITE) -timeout 120m -race -parallel=1 + CGO_ENABLED=1 TF_ACC=1 go test $(TEST) -v $(TESTARGS) -timeout 120m -race -parallel=1 junit-report: fmtcheck @go install github.com/jstemmer/go-junit-report/v2@latest - CGO_ENABLED=1 TF_ACC=1 TF_LOG=DEBUG go test $(TEST) -v $(TESTARGS) -tags=$(TEST_SUITE) -timeout 120m -race -parallel=1 2>&1 | tee output.txt + CGO_ENABLED=1 TF_ACC=1 TF_LOG=DEBUG go test $(TEST) -v $(TESTARGS) -timeout 120m -race -parallel=1 2>&1 | tee output.txt ! grep -q "\[build failed\]" output.txt go-junit-report -in output.txt -out junit-report.xml diff --git a/buildinfo/ibm_monitor.go b/buildinfo/ibm_monitor.go index 8ef0f33f7..7a04a1bb7 100644 --- a/buildinfo/ibm_monitor.go +++ b/buildinfo/ibm_monitor.go @@ -1,5 +1,3 @@ -//go:build tf_acc_ibm_monitor - package buildinfo func init() { diff --git a/buildinfo/ibm_secure.go b/buildinfo/ibm_secure.go index eb748b5ea..254b26250 100644 --- a/buildinfo/ibm_secure.go +++ b/buildinfo/ibm_secure.go @@ -1,5 +1,3 @@ -//go:build tf_acc_ibm_secure - package buildinfo func init() { diff --git a/buildinfo/onprem_monitor.go b/buildinfo/onprem_monitor.go index 91558bfee..3081ed7aa 100644 --- a/buildinfo/onprem_monitor.go +++ b/buildinfo/onprem_monitor.go @@ -1,5 +1,3 @@ -//go:build tf_acc_onprem_monitor - package buildinfo func init() { diff --git a/buildinfo/onprem_secure.go b/buildinfo/onprem_secure.go index 5c386218c..495fb12c7 100644 --- a/buildinfo/onprem_secure.go +++ b/buildinfo/onprem_secure.go @@ -1,5 +1,3 @@ -//go:build tf_acc_onprem_secure - package buildinfo func init() { diff --git a/buildinfo/sysdig_monitor.go b/buildinfo/sysdig_monitor.go index fded6485a..0d6d2b1d9 100644 --- a/buildinfo/sysdig_monitor.go +++ b/buildinfo/sysdig_monitor.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor - package buildinfo func init() { diff --git a/buildinfo/sysdig_secure.go b/buildinfo/sysdig_secure.go index 2f1fd3f13..5313f878c 100644 --- a/buildinfo/sysdig_secure.go +++ b/buildinfo/sysdig_secure.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package buildinfo func init() { diff --git a/go.mod b/go.mod index 8f77735e0..db4d62fe0 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/hashicorp/terraform-plugin-log v0.8.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.26.1 github.com/jmespath/go-jmespath v0.4.0 - github.com/pkg/errors v0.9.1 github.com/rs/zerolog v1.29.1 github.com/spf13/cast v1.5.1 github.com/stretchr/testify v1.8.4 @@ -63,6 +62,7 @@ require ( github.com/oklog/run v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc3 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sysdiglabs/agent-kilt/pkg v0.0.0-20240201123620-2272de6dee9f // indirect diff --git a/main.go b/main.go index 1aa588110..eb25c3160 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,8 @@ package main import ( + "log/slog" + "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" "github.com/draios/terraform-provider-sysdig/sysdig" @@ -8,7 +10,12 @@ import ( func main() { sysdigClient := sysdig.NewSysdigClients() - defer sysdigClient.Close() + defer func() { + err := sysdigClient.Close() + if err != nil { + slog.Default().Error("error closing the provider", "error", err) + } + }() provider := &sysdig.SysdigProvider{SysdigClient: sysdigClient} plugin.Serve(&plugin.ServeOpts{ProviderFunc: provider.Provider}) diff --git a/scripts/oanc/main.go b/scripts/oanc/main.go index 342e42fcf..2fe38ec89 100644 --- a/scripts/oanc/main.go +++ b/scripts/oanc/main.go @@ -98,7 +98,12 @@ func main() { if err != nil { log.Fatal(err) } - defer response.Body.Close() + defer func() { + err := response.Body.Close() + if err != nil { + log.Fatalf("error closing response body: %s", err) + } + }() if response.StatusCode != http.StatusOK { log.Fatal(errors.New(response.Status)) diff --git a/sysdig/cfn_preprocess_template.go b/sysdig/cfn_preprocess_template.go index 13eadb2a6..fd8008637 100644 --- a/sysdig/cfn_preprocess_template.go +++ b/sysdig/cfn_preprocess_template.go @@ -1,11 +1,3 @@ -/* -This file contains definition for the following functions. - -terraformPreModifications is used to modify the container definitions passed to the cfn patcher such that it modifies casing issues in any ECS json content so that it can be processed by the kilt patcher. - -GetValueFromTemplate is used to obtain key, value information from JSON object -*/ - package sysdig import ( @@ -39,7 +31,7 @@ func capitalize(key string) string { return string(r) } -// updateKey recursively capitalizes the first letter of each key in the input object +// updateKeys recursively capitalizes the first letter of each key in the input object func updateKeys(inputMap gabs.Container) error { // in this case, the object is probably an array, so update each child if len(inputMap.ChildrenMap()) == 0 { @@ -87,7 +79,7 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte passthrough, _ := GetValueFromTemplate(container.S("image")) _, err = container.Set(passthrough, "Image") if err != nil { - return nil, fmt.Errorf("Could not update Image field: %v", err) + return nil, fmt.Errorf("could not update Image field: %v", err) } err = container.Delete("image") @@ -100,7 +92,7 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte passthrough, _ := GetValueFromTemplate(container.S("name")) _, err = container.Set(passthrough, "Name") if err != nil { - return nil, fmt.Errorf("Could not update Name field: %v", err) + return nil, fmt.Errorf("could not update Name field: %v", err) } err = container.Delete("name") @@ -115,22 +107,22 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte name, _ := env.S("name").Data().(string) err = env.Delete("name") if err != nil { - return nil, fmt.Errorf("Could not delete \"name\" key in Environment: %v", err) + return nil, fmt.Errorf("could not delete \"name\" key in Environment: %v", err) } _, err = env.Set(name, "Name") if err != nil { - return nil, fmt.Errorf("Could not assign \"Name\" key in Environment: %v", err) + return nil, fmt.Errorf("could not assign \"Name\" key in Environment: %v", err) } } if env.Exists("value") { value, _ := env.S("value").Data().(string) err = env.Delete("value") if err != nil { - return nil, fmt.Errorf("Could not delete \"value\" key in Environment: %v", err) + return nil, fmt.Errorf("could not delete \"value\" key in Environment: %v", err) } _, err = env.Set(value, "Value") if err != nil { - return nil, fmt.Errorf("Could not assign \"Value\" key in Environment: %v", err) + return nil, fmt.Errorf("could not assign \"Value\" key in Environment: %v", err) } } } @@ -139,7 +131,7 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte parsedPassthrough, _ := gabs.ParseJSON([]byte(passthrough)) _, err = container.Set(parsedPassthrough, "Environment") if err != nil { - return nil, fmt.Errorf("Could not update Environment field: %v", err) + return nil, fmt.Errorf("could not update Environment field: %v", err) } err = container.Delete("environment") @@ -153,7 +145,7 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte parsedPassthrough, _ := gabs.ParseJSON([]byte(passthrough)) _, err = container.Set(parsedPassthrough, "EntryPoint") if err != nil { - return nil, fmt.Errorf("Could not update EntryPoint field: %v", err) + return nil, fmt.Errorf("could not update EntryPoint field: %v", err) } err = container.Delete("entryPoint") @@ -167,7 +159,7 @@ func terraformPreModifications(ctx context.Context, patchedStack []byte) ([]byte parsedPassthrough, _ := gabs.ParseJSON([]byte(passthrough)) _, err = container.Set(parsedPassthrough, "Command") if err != nil { - return nil, fmt.Errorf("Could not update Command field: %v", err) + return nil, fmt.Errorf("could not update Command field: %v", err) } err = container.Delete("command") diff --git a/sysdig/common.go b/sysdig/common.go index a730401ad..d924e8e82 100644 --- a/sysdig/common.go +++ b/sysdig/common.go @@ -55,7 +55,7 @@ const ( SchemaRoleKey = "role" SchemaSystemRoleKey = "system_role" SchemaRulesKey = "rules" - SchemaApiKeyKey = "api_key" + SchemaAPIKeyKey = "api_key" SchemaPermissionsKey = "permissions" SchemaMonitorPermKey = "monitor_permissions" SchemaSecurePermKey = "secure_permissions" @@ -79,10 +79,10 @@ const ( SchemaEnabled = "enabled" SchemaComponents = "components" SchemaComponent = "component" - SchemaCloudProviderId = "provider_id" + SchemaCloudProviderID = "provider_id" SchemaCloudProviderType = "provider_type" SchemaFeature = "feature" - SchemaManagementAccountId = "management_account_id" + SchemaManagementAccountID = "management_account_id" SchemaOrganizationIDKey = "organization_id" SchemaOrganizationalUnitIds = "organizational_unit_ids" SchemaIncludedOrganizationalGroups = "included_organizational_groups" @@ -91,9 +91,9 @@ const ( SchemaExcludedCloudAccounts = "excluded_cloud_accounts" SchemaOrganizationRootID = "organization_root_id" SchemaAutomaticOnboarding = "automatic_onboarding" - SchemaCloudProviderTenantId = "provider_tenant_id" + SchemaCloudProviderTenantID = "provider_tenant_id" SchemaCloudProviderAlias = "provider_alias" - SchemaAccountId = "account_id" + SchemaAccountID = "account_id" SchemaFeatureFlags = "flags" SchemaProviderPartition = "provider_partition" ) diff --git a/sysdig/data_source_agent_access_keys.go b/sysdig/data_source_agent_access_keys.go index 4c8bce609..3a089957c 100644 --- a/sysdig/data_source_agent_access_keys.go +++ b/sysdig/data_source_agent_access_keys.go @@ -61,14 +61,14 @@ func dataSourceSysdigAgentAccessKey() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigAgentAccessKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigAgentAccessKeyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) } - agentKeyId := d.Get("id").(int) - agentAccessKey, err := client.GetAgentAccessKeyByID(ctx, strconv.Itoa(agentKeyId)) + agentKeyID := d.Get("id").(int) + agentAccessKey, err := client.GetAgentAccessKeyByID(ctx, strconv.Itoa(agentKeyID)) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/data_source_agent_access_keys_test.go b/sysdig/data_source_agent_access_keys_test.go index 5aa1c2495..3d7478c33 100644 --- a/sysdig/data_source_agent_access_keys_test.go +++ b/sysdig/data_source_agent_access_keys_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_current_user.go b/sysdig/data_source_sysdig_current_user.go index 7e4f3990e..38f0cf889 100644 --- a/sysdig/data_source_sysdig_current_user.go +++ b/sysdig/data_source_sysdig_current_user.go @@ -41,7 +41,7 @@ func dataSourceSysdigCurrentUser() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigCurrentUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigCurrentUserRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_current_user_test.go b/sysdig/data_source_sysdig_current_user_test.go index c89aa7847..d28b8a651 100644 --- a/sysdig/data_source_sysdig_current_user_test.go +++ b/sysdig/data_source_sysdig_current_user_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_ibm_monitor || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_custom_role.go b/sysdig/data_source_sysdig_custom_role.go index 738c99378..13e880955 100644 --- a/sysdig/data_source_sysdig_custom_role.go +++ b/sysdig/data_source_sysdig_custom_role.go @@ -46,7 +46,7 @@ func dataSourceSysdigCustomRole() *schema.Resource { } } -func dataSourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func dataSourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_custom_role_permissions_common.go b/sysdig/data_source_sysdig_custom_role_permissions_common.go index a0da17516..c235a5a0e 100644 --- a/sysdig/data_source_sysdig_custom_role_permissions_common.go +++ b/sysdig/data_source_sysdig_custom_role_permissions_common.go @@ -31,12 +31,12 @@ func dataSourceSysdigCustomRoleSchema() map[string]*schema.Schema { } func getDataSourceSysdigCustomRoleMonitorPermissionsRead(product v2.Product) schema.ReadContextFunc { - return func(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + return func(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) } - rp := d.Get(SchemaRequestedPermKey).([]interface{}) + rp := d.Get(SchemaRequestedPermKey).([]any) rps := readPermissions(rp) dependencies, err := client.GetPermissionsDependencies(ctx, product, rps) @@ -57,7 +57,7 @@ func getDataSourceSysdigCustomRoleMonitorPermissionsRead(product v2.Product) sch } } -func readPermissions(rp []interface{}) []string { +func readPermissions(rp []any) []string { permissions := make([]string, len(rp)) for i, permission := range rp { permissions[i] = permission.(string) diff --git a/sysdig/data_source_sysdig_custom_role_test.go b/sysdig/data_source_sysdig_custom_role_test.go index e01e70d63..3c2576e9d 100644 --- a/sysdig/data_source_sysdig_custom_role_test.go +++ b/sysdig/data_source_sysdig_custom_role_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_fargate_ECS_test.go b/sysdig/data_source_sysdig_fargate_ECS_test.go index 1352abf0c..1701bcc39 100644 --- a/sysdig/data_source_sysdig_fargate_ECS_test.go +++ b/sysdig/data_source_sysdig_fargate_ECS_test.go @@ -1,5 +1,3 @@ -//go:build unit - package sysdig import ( @@ -21,10 +19,10 @@ import ( // sortContainerEnv goes into a container definition and sorts the environment variables func sortContainerEnv(json []byte) string { jsonObject, _ := gabs.ParseJSON(json) - containers, _ := jsonObject.Data().([]interface{}) + containers, _ := jsonObject.Data().([]any) for _, container := range containers { - if env, ok := container.(map[string]interface{})["Environment"]; ok { - envSort := env.([]interface{}) + if env, ok := container.(map[string]any)["Environment"]; ok { + envSort := env.([]any) sort.Slice(envSort, func(i, j int) bool { return gabs.Wrap(envSort[i]).S("Name").Data().(string) < gabs.Wrap(envSort[j]).S("Name").Data().(string) }) @@ -137,22 +135,22 @@ func TestNewPatchOptions(t *testing.T) { data := resource.Data(nil) var err error - err = data.Set("bare_pdig_on_containers", []interface{}{ + err = data.Set("bare_pdig_on_containers", []any{ "gimme", "fried", "chicken", }) if err != nil { assert.FailNow(t, fmt.Sprintf("Could not set bare_pdig_on_containers, got error: %v", err)) } - err = data.Set("ignore_containers", []interface{}{ + err = data.Set("ignore_containers", []any{ "gimme", "fried", "chicken", }) if err != nil { assert.FailNow(t, fmt.Sprintf("Could not set ignore_containers, got error: %v", err)) } - err = data.Set("log_configuration", []interface{}{ - map[string]interface{}{ + err = data.Set("log_configuration", []any{ + map[string]any{ "group": "gimme", "stream_prefix": "fried", "region": "chicken", @@ -166,7 +164,7 @@ func TestNewPatchOptions(t *testing.T) { expectedPatchOptions := &patchOptions{ BarePdigOnContainers: []string{"gimme", "fried", "chicken"}, IgnoreContainers: []string{"gimme", "fried", "chicken"}, - LogConfiguration: map[string]interface{}{ + LogConfiguration: map[string]any{ "group": "gimme", "stream_prefix": "fried", "region": "chicken", @@ -289,7 +287,7 @@ func TestPatchFargateTaskDefinition(t *testing.T) { { testName: `fargate_log_group`, patchOpts: &patchOptions{ - LogConfiguration: map[string]interface{}{ + LogConfiguration: map[string]any{ "group": "test_log_group", "stream_prefix": "test_prefix", "region": "test_region", diff --git a/sysdig/data_source_sysdig_fargate_workload_agent.go b/sysdig/data_source_sysdig_fargate_workload_agent.go index a14074841..a53c2c121 100644 --- a/sysdig/data_source_sysdig_fargate_workload_agent.go +++ b/sysdig/data_source_sysdig_fargate_workload_agent.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strings" "github.com/Jeffail/gabs/v2" @@ -180,9 +181,9 @@ type cfnTag struct { } type cfnProperties struct { - RequiresCompatibilities []string `json:"RequiresCompatibilities"` - ContainerDefinitions []map[string]interface{} `json:"ContainerDefinitions"` - Tags []cfnTag `json:"Tags"` + RequiresCompatibilities []string `json:"RequiresCompatibilities"` + ContainerDefinitions []map[string]any `json:"ContainerDefinitions"` + Tags []cfnTag `json:"Tags"` } type cfnResource struct { @@ -195,12 +196,7 @@ type cfnStack struct { } func contains(items []string, target string) bool { - for _, item := range items { - if item == target { - return true - } - } - return false + return slices.Contains(items, target) } // fargatePostKiltModifications performs any additional changes needed after Kilt has applied it's transformations @@ -247,8 +243,8 @@ func fargatePostKiltModifications(patchedBytes []byte, patchOpts *patchOptions) } } - if patchOpts.CpuShares != 0 { - _, err := container.Set(patchOpts.CpuShares, "cpu") + if patchOpts.CPUShares != 0 { + _, err := container.Set(patchOpts.CPUShares, "cpu") if err != nil { return nil, fmt.Errorf("failed to set cpu shares: %s", err) } @@ -270,7 +266,7 @@ func fargatePostKiltModifications(patchedBytes []byte, patchOpts *patchOptions) } else { // Use bare pdig in the current workload container if instrumented if contains(patchOpts.BarePdigOnContainers, containerName) && !contains(patchOpts.IgnoreContainers, containerName) { - envars := map[string]interface{}{ + envars := map[string]any{ "Name": "__INSTRUMENTATION_WRAPPER", "Value": "/opt/draios/bin/pdig,-C,-t,-1", } @@ -287,7 +283,7 @@ func fargatePostKiltModifications(patchedBytes []byte, patchOpts *patchOptions) // PatchFargateTaskDefinition modifies the container definitions func patchFargateTaskDefinition(ctx context.Context, containerDefinitions string, kiltConfig *cfnpatcher.Configuration, patchOpts *patchOptions) (patched *string, err error) { - var cdefs []map[string]interface{} + var cdefs []map[string]any err = json.Unmarshal([]byte(containerDefinitions), &cdefs) if err != nil { return nil, err @@ -376,9 +372,9 @@ type KiltRecipeConfig struct { type patchOptions struct { BarePdigOnContainers []string IgnoreContainers []string - LogConfiguration map[string]interface{} + LogConfiguration map[string]any Essential bool - CpuShares int + CPUShares int MemoryLimit int MemoryReservation int } @@ -387,11 +383,11 @@ func newPatchOptions(d *schema.ResourceData) *patchOptions { opts := &patchOptions{ BarePdigOnContainers: []string{}, IgnoreContainers: []string{}, - LogConfiguration: map[string]interface{}{}, + LogConfiguration: map[string]any{}, } if items := d.Get("bare_pdig_on_containers"); items != nil { - for _, itemRaw := range items.([]interface{}) { + for _, itemRaw := range items.([]any) { if itemStr, ok := itemRaw.(string); ok { opts.BarePdigOnContainers = append(opts.BarePdigOnContainers, strings.TrimSpace(itemStr)) } @@ -399,7 +395,7 @@ func newPatchOptions(d *schema.ResourceData) *patchOptions { } if items := d.Get("ignore_containers"); items != nil { - for _, itemRaw := range items.([]interface{}) { + for _, itemRaw := range items.([]any) { if itemStr, ok := itemRaw.(string); ok { opts.IgnoreContainers = append(opts.IgnoreContainers, strings.TrimSpace(itemStr)) } @@ -407,7 +403,7 @@ func newPatchOptions(d *schema.ResourceData) *patchOptions { } if logConfiguration := d.Get("log_configuration").(*schema.Set).List(); len(logConfiguration) > 0 { - opts.LogConfiguration = logConfiguration[0].(map[string]interface{}) + opts.LogConfiguration = logConfiguration[0].(map[string]any) } if essential := d.Get("instrumentation_essential"); essential != nil { @@ -418,9 +414,9 @@ func newPatchOptions(d *schema.ResourceData) *patchOptions { } if cpuShares := d.Get("instrumentation_cpu"); cpuShares != nil { - opts.CpuShares = cpuShares.(int) + opts.CPUShares = cpuShares.(int) } else { - opts.CpuShares = 0 + opts.CPUShares = 0 } if memoryLimit := d.Get("instrumentation_memory_limit"); memoryLimit != nil { @@ -438,7 +434,7 @@ func newPatchOptions(d *schema.ResourceData) *patchOptions { return opts } -func dataSourceSysdigFargateWorkloadAgentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigFargateWorkloadAgentRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { priority := d.Get("priority").(string) if priority != "security" && priority != "availability" { return diag.Errorf("Invalid priority: %s. must be either \"security\" or \"availability\"", priority) @@ -496,9 +492,5 @@ func dataSourceSysdigFargateWorkloadAgentRead(ctx context.Context, d *schema.Res cdefChecksum := sha256.Sum256([]byte(containerDefinitions)) d.SetId(fmt.Sprintf("%x", cdefChecksum)) _ = d.Set("output_container_definitions", *outputContainerDefinitions) - if err != nil { - return diag.FromErr(err) - } - return nil } diff --git a/sysdig/data_source_sysdig_fargate_workload_agent_test.go b/sysdig/data_source_sysdig_fargate_workload_agent_test.go index 4c7a5756b..55168300c 100644 --- a/sysdig/data_source_sysdig_fargate_workload_agent_test.go +++ b/sysdig/data_source_sysdig_fargate_workload_agent_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_custom_role_permissions_test.go b/sysdig/data_source_sysdig_monitor_custom_role_permissions_test.go index ce640b15e..a77e9c779 100644 --- a/sysdig/data_source_sysdig_monitor_custom_role_permissions_test.go +++ b/sysdig/data_source_sysdig_monitor_custom_role_permissions_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook.go b/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook.go index 0c52d00f9..97ce4faec 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook.go @@ -44,7 +44,7 @@ func dataSourceSysdigMonitorNotificationChannelCustomWebhook() *schema.Resource } } -func dataSourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook_test.go index 40e64d8e2..184d33935 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_custom_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_email.go b/sysdig/data_source_sysdig_monitor_notification_channel_email.go index 053ab5bb6..c33d55736 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_email.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_email.go @@ -29,7 +29,7 @@ func dataSourceSysdigMonitorNotificationChannelEmail() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_email_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_email_test.go index 7fa9c4fd9..9f465a7ff 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_email_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_google_chat.go b/sysdig/data_source_sysdig_monitor_notification_channel_google_chat.go index 06f6aba29..5406db210 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_google_chat.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_google_chat.go @@ -28,7 +28,7 @@ func dataSourceSysdigMonitorNotificationChannelGoogleChat() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_google_chat_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_google_chat_test.go index 56aeea2ce..412899ec1 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_google_chat_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_google_chat_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification.go b/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification.go index 645313e44..8fef7702e 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification.go @@ -28,7 +28,7 @@ func dataSourceSysdigMonitorNotificationChannelIBMEventNotification() *schema.Re } } -func dataSourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification_test.go index 5a7cbd1a5..75ea66b69 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_ibm_event_notification_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_msteams.go b/sysdig/data_source_sysdig_monitor_notification_channel_msteams.go index f1ef1630f..0accc6aa8 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_msteams.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_msteams.go @@ -28,7 +28,7 @@ func dataSourceSysdigMonitorNotificationChannelMSTeams() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_msteams_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_msteams_test.go index c14a26f98..358fc4835 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_msteams_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_msteams_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie.go b/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie.go index 852214af4..da33f9513 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie.go @@ -32,7 +32,7 @@ func dataSourceSysdigMonitorNotificationChannelOpsGenie() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie_test.go index a780df238..cf61f6b1b 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_opsgenie_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty.go b/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty.go index aba889f6b..1f65ad995 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty.go @@ -36,7 +36,7 @@ func dataSourceSysdigMonitorNotificationChannelPagerduty() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty_test.go index 966624beb..8855f4097 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_pagerduty_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager.go b/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager.go index b8d577ba1..407bcf670 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager.go @@ -36,7 +36,7 @@ func dataSourceSysdigMonitorNotificationChannelPrometheusAlertManager() *schema. } } -func dataSourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go index 5f0f8730f..92a4dc07e 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_slack.go b/sysdig/data_source_sysdig_monitor_notification_channel_slack.go index 321d71760..935b1f685 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_slack.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_slack.go @@ -69,7 +69,7 @@ func dataSourceSysdigMonitorNotificationChannelSlack() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_slack_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_slack_test.go index 7d1d131cb..083778627 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_slack_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_slack_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_sns.go b/sysdig/data_source_sysdig_monitor_notification_channel_sns.go index d69c67c9b..fe480dd83 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_sns.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_sns.go @@ -29,7 +29,7 @@ func dataSourceSysdigMonitorNotificationChannelSNS() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_sns_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_sns_test.go index 40e39ad2d..897b71bbd 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_sns_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_sns_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_team_email.go b/sysdig/data_source_sysdig_monitor_notification_channel_team_email.go index 04490a322..5969ab4c4 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_team_email.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_team_email.go @@ -28,7 +28,7 @@ func dataSourceSysdigMonitorNotificationChannelTeamEmail() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_team_email_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_team_email_test.go index 26bc25a53..3d77f3e30 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_team_email_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_team_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_victorops.go b/sysdig/data_source_sysdig_monitor_notification_channel_victorops.go index 69379e301..52e1c5d19 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_victorops.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_victorops.go @@ -32,7 +32,7 @@ func dataSourceSysdigMonitorNotificationChannelVictorOps() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_victorops_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_victorops_test.go index 5d1525eeb..68d9e0ef8 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_victorops_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_victorops_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_webhook.go b/sysdig/data_source_sysdig_monitor_notification_channel_webhook.go index 447b2b881..e779879b2 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_webhook.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_webhook.go @@ -40,7 +40,7 @@ func dataSourceSysdigMonitorNotificationChannelWebhook() *schema.Resource { } } -func dataSourceSysdigMonitorNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_monitor_notification_channel_webhook_test.go b/sysdig/data_source_sysdig_monitor_notification_channel_webhook_test.go index 3f9f6e7ab..2152f8452 100644 --- a/sysdig/data_source_sysdig_monitor_notification_channel_webhook_test.go +++ b/sysdig/data_source_sysdig_monitor_notification_channel_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_team.go b/sysdig/data_source_sysdig_monitor_team.go index a18b3847f..7cfd8cf03 100644 --- a/sysdig/data_source_sysdig_monitor_team.go +++ b/sysdig/data_source_sysdig_monitor_team.go @@ -108,7 +108,7 @@ func dataSourceSysdigMonitorTeam() *schema.Resource { } } -func dataSourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorTeamClient(clients) if err != nil { @@ -120,7 +120,7 @@ func dataSourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(err) } - team, err := client.GetTeamById(ctx, id) + team, err := client.GetTeamByID(ctx, id) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/data_source_sysdig_monitor_team_ibm_test.go b/sysdig/data_source_sysdig_monitor_team_ibm_test.go index 257634f6e..c48a8ff52 100644 --- a/sysdig/data_source_sysdig_monitor_team_ibm_test.go +++ b/sysdig/data_source_sysdig_monitor_team_ibm_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_ibm_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_team_test.go b/sysdig/data_source_sysdig_monitor_team_test.go index 4dc1fe6fc..9a50cc214 100644 --- a/sysdig/data_source_sysdig_monitor_team_test.go +++ b/sysdig/data_source_sysdig_monitor_team_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_monitor_teams.go b/sysdig/data_source_sysdig_monitor_teams.go index 043e4808a..a1251f591 100644 --- a/sysdig/data_source_sysdig_monitor_teams.go +++ b/sysdig/data_source_sysdig_monitor_teams.go @@ -31,7 +31,7 @@ func dataSourceSysdigMonitorTeams() *schema.Resource { } } -func dataSourceSysdigMonitorTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigMonitorTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorTeamClient(clients) if err != nil { @@ -43,9 +43,9 @@ func dataSourceSysdigMonitorTeamsRead(ctx context.Context, d *schema.ResourceDat return diag.FromErr(err) } - var result []map[string]interface{} + var result []map[string]any for _, team := range teams { - result = append(result, map[string]interface{}{ + result = append(result, map[string]any{ "id": team.ID, "name": team.Name, }) diff --git a/sysdig/data_source_sysdig_monitor_teams_test.go b/sysdig/data_source_sysdig_monitor_teams_test.go index e4de6a48f..05727915a 100644 --- a/sysdig/data_source_sysdig_monitor_teams_test.go +++ b/sysdig/data_source_sysdig_monitor_teams_test.go @@ -1,12 +1,11 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_onprem_monitor || tf_acc_ibm_monitor - package sysdig_test import ( "fmt" + "testing" + "github.com/draios/terraform-provider-sysdig/sysdig" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) diff --git a/sysdig/data_source_sysdig_secure_aws_ml_policy.go b/sysdig/data_source_sysdig_secure_aws_ml_policy.go index 72f3407c4..0335eb8dc 100644 --- a/sysdig/data_source_sysdig_secure_aws_ml_policy.go +++ b/sysdig/data_source_sysdig_secure_aws_ml_policy.go @@ -23,7 +23,7 @@ func dataSourceSysdigSecureAWSMLPolicy() *schema.Resource { } } -func dataSourceSysdigSecureAWSMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureAWSMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return awsMLPolicyDataSourceRead(ctx, d, meta, "custom AWS ML policy", isCustomCompositePolicy) } @@ -59,7 +59,7 @@ func createAWSMLPolicyDataSourceSchema() map[string]*schema.Schema { } } -func awsMLPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { +func awsMLPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { policy, err := compositePolicyDataSourceRead(ctx, d, meta, resourceName, policyTypeAWSML, validationFunc) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_aws_ml_policy_test.go b/sysdig/data_source_sysdig_secure_aws_ml_policy_test.go index 39b44f201..ff294e707 100644 --- a/sysdig/data_source_sysdig_secure_aws_ml_policy_test.go +++ b/sysdig/data_source_sysdig_secure_aws_ml_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_current_connection.go b/sysdig/data_source_sysdig_secure_current_connection.go index 607a89ed3..ec9c56b8b 100644 --- a/sysdig/data_source_sysdig_secure_current_connection.go +++ b/sysdig/data_source_sysdig_secure_current_connection.go @@ -28,18 +28,18 @@ func dataSourceSysdigSecureConnection() *schema.Resource { } } -func dataSourceSecureConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSecureConnectionRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { endpoint, err := meta.(SysdigClients).GetSecureEndpoint() if err != nil { return diag.FromErr(err) } - apiToken, err := meta.(SysdigClients).GetSecureApiToken() + apiToken, err := meta.(SysdigClients).GetSecureAPIToken() if err != nil { return diag.FromErr(err) } - d.SetId(fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s,%s", endpoint, apiToken))))) + d.SetId(fmt.Sprintf("%x", sha256.Sum256(fmt.Appendf(nil, "%s,%s", endpoint, apiToken)))) err = d.Set("secure_url", endpoint) if err != nil { diff --git a/sysdig/data_source_sysdig_secure_current_connection_test.go b/sysdig/data_source_sysdig_secure_current_connection_test.go index f7723d599..c90175fe8 100644 --- a/sysdig/data_source_sysdig_secure_current_connection_test.go +++ b/sysdig/data_source_sysdig_secure_current_connection_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_custom_policy.go b/sysdig/data_source_sysdig_secure_custom_policy.go index 80400ce96..19f825123 100644 --- a/sysdig/data_source_sysdig_secure_custom_policy.go +++ b/sysdig/data_source_sysdig_secure_custom_policy.go @@ -23,10 +23,10 @@ func dataSourceSysdigSecureCustomPolicy() *schema.Resource { } } -func dataSourceSysdigSecureCustomPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureCustomPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSecurePolicyRead(ctx, d, meta, "custom policy", isCustomPolicy) } func isCustomPolicy(policy v2.Policy) bool { - return !policy.IsDefault && policy.TemplateId == 0 + return !policy.IsDefault && policy.TemplateID == 0 } diff --git a/sysdig/data_source_sysdig_secure_custom_policy_test.go b/sysdig/data_source_sysdig_secure_custom_policy_test.go index 38e1fe0ae..5862b45c6 100644 --- a/sysdig/data_source_sysdig_secure_custom_policy_test.go +++ b/sysdig/data_source_sysdig_secure_custom_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_custom_role_permissions_test.go b/sysdig/data_source_sysdig_secure_custom_role_permissions_test.go index e118735e5..bbb9c1d34 100644 --- a/sysdig/data_source_sysdig_secure_custom_role_permissions_test.go +++ b/sysdig/data_source_sysdig_secure_custom_role_permissions_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_drift_policy.go b/sysdig/data_source_sysdig_secure_drift_policy.go index 77094c52b..108dd0ebf 100644 --- a/sysdig/data_source_sysdig_secure_drift_policy.go +++ b/sysdig/data_source_sysdig_secure_drift_policy.go @@ -23,7 +23,7 @@ func dataSourceSysdigSecureDriftPolicy() *schema.Resource { } } -func dataSourceSysdigSecureDriftPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureDriftPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return driftPolicyDataSourceRead(ctx, d, meta, "custom drift policy", isCustomCompositePolicy) } @@ -73,7 +73,7 @@ func createDriftPolicyDataSourceSchema() map[string]*schema.Schema { } } -func driftPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { +func driftPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { policy, err := compositePolicyDataSourceRead(ctx, d, meta, resourceName, policyTypeDrift, validationFunc) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_drift_policy_test.go b/sysdig/data_source_sysdig_secure_drift_policy_test.go index 50064436f..86f8bc932 100644 --- a/sysdig/data_source_sysdig_secure_drift_policy_test.go +++ b/sysdig/data_source_sysdig_secure_drift_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_malware_policy.go b/sysdig/data_source_sysdig_secure_malware_policy.go index cd358c081..37a0aeba9 100644 --- a/sysdig/data_source_sysdig_secure_malware_policy.go +++ b/sysdig/data_source_sysdig_secure_malware_policy.go @@ -23,12 +23,12 @@ func dataSourceSysdigSecureMalwarePolicy() *schema.Resource { } } -func dataSourceSysdigSecureMalwarePolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureMalwarePolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return malwarePolicyDataSourceRead(ctx, d, meta, "custom malware policy", isCustomCompositePolicy) } func isCustomCompositePolicy(policy v2.PolicyRulesComposite) bool { - return !policy.Policy.IsDefault && policy.Policy.TemplateId == 0 + return !policy.Policy.IsDefault && policy.Policy.TemplateID == 0 } func createMalwarePolicyDataSourceSchema() map[string]*schema.Schema { @@ -76,7 +76,7 @@ func createMalwarePolicyDataSourceSchema() map[string]*schema.Schema { } } -func malwarePolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { +func malwarePolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { policy, err := compositePolicyDataSourceRead(ctx, d, meta, resourceName, policyTypeMalware, validationFunc) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_malware_policy_test.go b/sysdig/data_source_sysdig_secure_malware_policy_test.go index aeca1de82..98ac79e30 100644 --- a/sysdig/data_source_sysdig_secure_malware_policy_test.go +++ b/sysdig/data_source_sysdig_secure_malware_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_managed_policy.go b/sysdig/data_source_sysdig_secure_managed_policy.go index 9c259fda9..48e490a57 100644 --- a/sysdig/data_source_sysdig_secure_managed_policy.go +++ b/sysdig/data_source_sysdig_secure_managed_policy.go @@ -23,7 +23,7 @@ func dataSourceSysdigSecureManagedPolicy() *schema.Resource { } } -func dataSourceSysdigSecureManagedPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureManagedPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSecurePolicyRead(ctx, d, meta, "managed policy", isManagedPolicy) } diff --git a/sysdig/data_source_sysdig_secure_managed_policy_test.go b/sysdig/data_source_sysdig_secure_managed_policy_test.go index e5a85caa2..2176c0427 100644 --- a/sysdig/data_source_sysdig_secure_managed_policy_test.go +++ b/sysdig/data_source_sysdig_secure_managed_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_managed_ruleset.go b/sysdig/data_source_sysdig_secure_managed_ruleset.go index 29e8b59dd..ffa8fbb5e 100644 --- a/sysdig/data_source_sysdig_secure_managed_ruleset.go +++ b/sysdig/data_source_sysdig_secure_managed_ruleset.go @@ -23,10 +23,10 @@ func dataSourceSysdigSecureManagedRuleset() *schema.Resource { } } -func dataSourceSysdigManagedRulesetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigManagedRulesetRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSecurePolicyRead(ctx, d, meta, "managed ruleset", isManagedRuleset) } func isManagedRuleset(policy v2.Policy) bool { - return !policy.IsDefault && policy.TemplateId != 0 + return !policy.IsDefault && policy.TemplateID != 0 } diff --git a/sysdig/data_source_sysdig_secure_managed_ruleset_test.go b/sysdig/data_source_sysdig_secure_managed_ruleset_test.go index 21738a7dc..b5e9bd9a6 100644 --- a/sysdig/data_source_sysdig_secure_managed_ruleset_test.go +++ b/sysdig/data_source_sysdig_secure_managed_ruleset_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_ml_policy.go b/sysdig/data_source_sysdig_secure_ml_policy.go index 03f8bd25b..731e808dc 100644 --- a/sysdig/data_source_sysdig_secure_ml_policy.go +++ b/sysdig/data_source_sysdig_secure_ml_policy.go @@ -25,7 +25,7 @@ func dataSourceSysdigSecureMLPolicy() *schema.Resource { } } -func dataSourceSysdigSecureMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return mlPolicyDataSourceRead(ctx, d, meta, "custom ML policy", isCustomCompositePolicy) } @@ -61,8 +61,7 @@ func createMLPolicyDataSourceSchema() map[string]*schema.Schema { } } -func mlPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { - +func mlPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, validationFunc func(v2.PolicyRulesComposite) bool) diag.Diagnostics { policy, err := compositePolicyDataSourceRead(ctx, d, meta, resourceName, policyTypeML, validationFunc) if err != nil { return diag.FromErr(err) @@ -75,7 +74,7 @@ func mlPolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta in return nil } -func compositePolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, policyType string, validationFunc func(v2.PolicyRulesComposite) bool) (*v2.PolicyRulesComposite, error) { +func compositePolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, policyType string, validationFunc func(v2.PolicyRulesComposite) bool) (*v2.PolicyRulesComposite, error) { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -83,14 +82,14 @@ func compositePolicyDataSourceRead(ctx context.Context, d *schema.ResourceData, policyName := d.Get("name").(string) - policies, _, err := client.FilterCompositePoliciesByNameAndType(ctx, policyType, policyName) + policies, _, err := client.ListCompositePoliciesByNameAndType(ctx, policyType, policyName) if err != nil { return nil, err } var policy v2.PolicyRulesComposite for _, existingPolicy := range policies { - tflog.Debug(ctx, "Filtered policies", map[string]interface{}{"name": existingPolicy.Policy.Name}) + tflog.Debug(ctx, "Filtered policies", map[string]any{"name": existingPolicy.Policy.Name}) if existingPolicy.Policy.Name == policyName && existingPolicy.Policy.Type == policyType { if !validationFunc(existingPolicy) { diff --git a/sysdig/data_source_sysdig_secure_ml_policy_test.go b/sysdig/data_source_sysdig_secure_ml_policy_test.go index cbea34e72..96158dfe0 100644 --- a/sysdig/data_source_sysdig_secure_ml_policy_test.go +++ b/sysdig/data_source_sysdig_secure_ml_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel.go b/sysdig/data_source_sysdig_secure_notification_channel.go index 9789ab5ee..21a6741c8 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel.go +++ b/sysdig/data_source_sysdig_secure_notification_channel.go @@ -12,26 +12,26 @@ import ( ) const ( - NOTIFICATION_CHANNEL_TYPE_EMAIL = "EMAIL" - NOTIFICATION_CHANNEL_TYPE_AMAZON_SNS = "SNS" - NOTIFICATION_CHANNEL_TYPE_OPSGENIE = "OPSGENIE" - NOTIFICATION_CHANNEL_TYPE_VICTOROPS = "VICTOROPS" - NOTIFICATION_CHANNEL_TYPE_WEBHOOK = "WEBHOOK" - NOTIFICATION_CHANNEL_TYPE_SLACK = "SLACK" - NOTIFICATION_CHANNEL_TYPE_PAGERDUTY = "PAGER_DUTY" - NOTIFICATION_CHANNEL_TYPE_MS_TEAMS = "MS_TEAMS" - NOTIFICATION_CHANNEL_TYPE_GCHAT = "GCHAT" - NOTIFICATION_CHANNEL_TYPE_PROMETHEUS_ALERT_MANAGER = "PROMETHEUS_ALERT_MANAGER" - NOTIFICATION_CHANNEL_TYPE_TEAM_EMAIL = "TEAM_EMAIL" - NOTIFICATION_CHANNEL_TYPE_CUSTOM_WEBHOOK = "POWER_WEBHOOK" - NOTIFICATION_CHANNEL_TYPE_IBM_EVENT_NOTIFICATION = "IBM_EVENT_NOTIFICATIONS" + notificationChannelTypeEmail = "EMAIL" + notificationChannelTypeAmazonSNS = "SNS" + notificationChannelTypeOpsGenie = "OPSGENIE" + notificationChannelTypeVictorOps = "VICTOROPS" + notificationChannelTypeWebhook = "WEBHOOK" + notificationChannelTypeSlack = "SLACK" + notificationChannelTypePagerduty = "PAGER_DUTY" + notificationChannelTypeMSTeams = "MS_TEAMS" + notificationChannelTypeGChat = "GCHAT" + notificationChannelTypePrometheusAlertManager = "PROMETHEUS_ALERT_MANAGER" + notificationChannelTypeTeamEmail = "TEAM_EMAIL" + notificationChannelTypeCustomWebhook = "POWER_WEBHOOK" + notificationChannelTypeIBMEventNotification = "IBM_EVENT_NOTIFICATIONS" - NOTIFICATION_CHANNEL_TYPE_SLACK_TEMPLATE_KEY_V1 = "SLACK_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v1" - NOTIFICATION_CHANNEL_TYPE_SLACK_TEMPLATE_KEY_V2 = "SLACK_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v2" - NOTIFICATION_CHANNEL_TYPE_MS_TEAMS_TEMPLATE_KEY_V1 = "MS_TEAMS_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v1" - NOTIFICATION_CHANNEL_TYPE_MS_TEAMS_TEMPLATE_KEY_V2 = "MS_TEAMS_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v2" + notificationChannelTypeSlackTemplateKeyV1 = "SLACK_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v1" + notificationChannelTypeSlackTemplateKeyV2 = "SLACK_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v2" + notificationChannelTypeMSTeamsTemplateKeyV1 = "MS_TEAMS_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v1" + notificationChannelTypeMSTeamsTemplateKeyV2 = "MS_TEAMS_SECURE_EVENT_NOTIFICATION_TEMPLATE_METADATA_v2" - NOTIFICATION_CHANNEL_SECURE_EVENT_NOTIFICATION_CONTENT_SECTION = "SECURE_EVENT_NOTIFICATION_CONTENT" + notificationChannelSecureEventNotificationContentSection = "SECURE_EVENT_NOTIFICATION_CONTENT" ) func dataSourceSysdigSecureNotificationChannel() *schema.Resource { @@ -118,7 +118,7 @@ func dataSourceSysdigSecureNotificationChannel() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigNotificationChannelRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigNotificationChannelRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -137,7 +137,7 @@ func dataSourceSysdigNotificationChannelRead(ctx context.Context, d *schema.Reso _ = d.Set("recipients", strings.Join(nc.Options.EmailRecipients, ",")) _ = d.Set("topics", strings.Join(nc.Options.SnsTopicARNs, ",")) _ = d.Set("api_key", nc.Options.APIKey) - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("channel", nc.Options.Channel) _ = d.Set("account", nc.Options.Account) _ = d.Set("service_key", nc.Options.ServiceKey) @@ -154,12 +154,12 @@ func dataSourceSysdigNotificationChannelRead(ctx context.Context, d *schema.Reso // didn't change at all. // We need to extract the key from the url the API gives us // to avoid this Terraform's behaviour. - if nc.Type == NOTIFICATION_CHANNEL_TYPE_OPSGENIE { + if nc.Type == notificationChannelTypeOpsGenie { regex, err := regexp.Compile("apiKey=(.*)?$") if err != nil { return diag.FromErr(err) } - key := regex.FindStringSubmatch(nc.Options.Url)[1] + key := regex.FindStringSubmatch(nc.Options.URL)[1] _ = d.Set("api_key", key) _ = d.Set("url", "") diff --git a/sysdig/data_source_sysdig_secure_notification_channel_email.go b/sysdig/data_source_sysdig_secure_notification_channel_email.go index 01c6eb5a3..be03a686d 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_email.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_email.go @@ -29,7 +29,7 @@ func dataSourceSysdigSecureNotificationChannelEmail() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_email_test.go b/sysdig/data_source_sysdig_secure_notification_channel_email_test.go index be6bf6585..cd447eeff 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_email_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_msteams.go b/sysdig/data_source_sysdig_secure_notification_channel_msteams.go index 46f47bc98..21cc94f00 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_msteams.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_msteams.go @@ -32,7 +32,7 @@ func dataSourceSysdigSecureNotificationChannelMSTeams() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_msteams_test.go b/sysdig/data_source_sysdig_secure_notification_channel_msteams_test.go index 1dfb9b8e7..aa36536cd 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_msteams_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_msteams_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_opsgenie.go b/sysdig/data_source_sysdig_secure_notification_channel_opsgenie.go index ba30537c0..8aee5b169 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_opsgenie.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_opsgenie.go @@ -32,7 +32,7 @@ func dataSourceSysdigSecureNotificationChannelOpsGenie() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_opsgenie_test.go b/sysdig/data_source_sysdig_secure_notification_channel_opsgenie_test.go index 3a874a4d2..34cab9464 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_opsgenie_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_opsgenie_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_pagerduty.go b/sysdig/data_source_sysdig_secure_notification_channel_pagerduty.go index 373109ed8..c72b65c57 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_pagerduty.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_pagerduty.go @@ -36,7 +36,7 @@ func dataSourceSysdigSecureNotificationChannelPagerduty() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_pagerduty_test.go b/sysdig/data_source_sysdig_secure_notification_channel_pagerduty_test.go index 14b484dfe..dc15c82b3 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_pagerduty_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_pagerduty_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager.go b/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager.go index e597e48ec..85353ad70 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager.go @@ -36,7 +36,7 @@ func dataSourceSysdigSecureNotificationChannelPrometheusAlertManager() *schema.R } } -func dataSourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager_test.go b/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager_test.go index b69599fab..0d43a9324 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_prometheus_alert_manager_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_slack.go b/sysdig/data_source_sysdig_secure_notification_channel_slack.go index 48694398d..7213275bf 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_slack.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_slack.go @@ -45,7 +45,7 @@ func dataSourceSysdigSecureNotificationChannelSlack() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_slack_test.go b/sysdig/data_source_sysdig_secure_notification_channel_slack_test.go index 72a6d2aa2..f46284b62 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_slack_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_slack_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_sns.go b/sysdig/data_source_sysdig_secure_notification_channel_sns.go index 1dbd7ab36..ca684fe21 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_sns.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_sns.go @@ -29,7 +29,7 @@ func dataSourceSysdigSecureNotificationChannelSNS() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_sns_test.go b/sysdig/data_source_sysdig_secure_notification_channel_sns_test.go index f82a370bf..0580320fb 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_sns_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_sns_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_team_email.go b/sysdig/data_source_sysdig_secure_notification_channel_team_email.go index f5590f1c6..d44b8f419 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_team_email.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_team_email.go @@ -28,7 +28,7 @@ func dataSourceSysdigSecureNotificationChannelTeamEmail() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_team_email_test.go b/sysdig/data_source_sysdig_secure_notification_channel_team_email_test.go index bd0b0aa46..64bc89790 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_team_email_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_team_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_test.go b/sysdig/data_source_sysdig_secure_notification_channel_test.go index c576a45a5..3a1e060c6 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_victorops.go b/sysdig/data_source_sysdig_secure_notification_channel_victorops.go index 1a22f920d..b9d2d8c38 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_victorops.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_victorops.go @@ -32,7 +32,7 @@ func dataSourceSysdigSecureNotificationChannelVictorOps() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_victorops_test.go b/sysdig/data_source_sysdig_secure_notification_channel_victorops_test.go index daf204bcb..f5c5ef8d6 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_victorops_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_victorops_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_notification_channel_webhook.go b/sysdig/data_source_sysdig_secure_notification_channel_webhook.go index 9b42b6c29..595d4f6b8 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_webhook.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_webhook.go @@ -40,7 +40,7 @@ func dataSourceSysdigSecureNotificationChannelWebhook() *schema.Resource { } } -func dataSourceSysdigSecureNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_webhook_test.go b/sysdig/data_source_sysdig_secure_notification_channel_webhook_test.go index f2c9bdc0c..657d55ff2 100644 --- a/sysdig/data_source_sysdig_secure_notification_channel_webhook_test.go +++ b/sysdig/data_source_sysdig_secure_notification_channel_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_onboarding.go b/sysdig/data_source_sysdig_secure_onboarding.go index 6d2cc3b9f..b1bb20c26 100644 --- a/sysdig/data_source_sysdig_secure_onboarding.go +++ b/sysdig/data_source_sysdig_secure_onboarding.go @@ -72,7 +72,7 @@ func dataSourceSysdigSecureTrustedCloudIdentity() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigSecureTrustedCloudIdentityRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTrustedCloudIdentityRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -181,7 +181,7 @@ func dataSourceSysdigSecureTrustedAzureApp() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigSecureTrustedAzureAppRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTrustedAzureAppRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -224,19 +224,19 @@ func dataSourceSysdigSecureTenantExternalID() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigSecureTenantExternalIDRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTenantExternalIDRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } - externalId, err := client.GetTenantExternalIDSecure(ctx) + externalID, err := client.GetTenantExternalIDSecure(ctx) if err != nil { return diag.FromErr(err) } - d.SetId(externalId) - err = d.Set("external_id", externalId) + d.SetId(externalID) + err = d.Set("external_id", externalID) if err != nil { return diag.FromErr(err) } @@ -288,7 +288,7 @@ func dataSourceSysdigSecureAgentlessScanningAssets() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigSecureAgentlessScanningAssetsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureAgentlessScanningAssetsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -299,33 +299,33 @@ func dataSourceSysdigSecureAgentlessScanningAssetsRead(ctx context.Context, d *s return diag.FromErr(err) } - assetsAws, _ := assets["aws"].(map[string]interface{}) - assetsAzure, _ := assets["azure"].(map[string]interface{}) - assetsBackend, _ := assets["backend"].(map[string]interface{}) - assetsGcp, _ := assets["gcp"].(map[string]interface{}) + assetsAws, _ := assets["aws"].(map[string]any) + assetsAzure, _ := assets["azure"].(map[string]any) + assetsBackend, _ := assets["backend"].(map[string]any) + assetsGcp, _ := assets["gcp"].(map[string]any) d.SetId("agentlessScanningAssets") - err = d.Set("aws", map[string]interface{}{ + err = d.Set("aws", map[string]any{ "account_id": assetsAws["accountId"], }) if err != nil { return diag.FromErr(err) } - err = d.Set("azure", map[string]interface{}{ + err = d.Set("azure", map[string]any{ "service_principal_id": assetsAzure["servicePrincipalId"], "tenant_id": assetsAzure["tenantId"], }) if err != nil { return diag.FromErr(err) } - err = d.Set("backend", map[string]interface{}{ + err = d.Set("backend", map[string]any{ "cloud_id": assetsBackend["cloudId"], "type": assetsBackend["type"], }) if err != nil { return diag.FromErr(err) } - err = d.Set("gcp", map[string]interface{}{ + err = d.Set("gcp", map[string]any{ "worker_identity": assetsGcp["workerIdentity"], }) if err != nil { @@ -379,7 +379,7 @@ func dataSourceSysdigSecureCloudIngestionAssets() *schema.Resource { } // Retrieves the information of a resource form the file and loads it in Terraform -func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -408,7 +408,7 @@ func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *sche d.SetId("cloudIngestionAssets") // Set GCP data if available - if gcpAssets, ok := assets["gcp"].(map[string]interface{}); ok { + if gcpAssets, ok := assets["gcp"].(map[string]any); ok { if routingKey, exists := gcpAssets["routingKey"]; exists { if err := d.Set("gcp_routing_key", routingKey); err != nil { return diag.FromErr(err) @@ -423,8 +423,8 @@ func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *sche } // Set AWS data if available - if awsAssets, ok := assets["aws"].(map[string]interface{}); ok { - awsData := map[string]interface{}{ + if awsAssets, ok := assets["aws"].(map[string]any); ok { + awsData := map[string]any{ "eventBusARN": awsAssets["eventBusARN"], "eventBusARNGov": awsAssets["eventBusARNGov"], } @@ -434,7 +434,7 @@ func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *sche awsData["sns_routing_key"] = awsAssets["snsRoutingKey"] } - if snsMetadata, ok := awsAssets["snsMetadata"].(map[string]interface{}); ok && snsMetadata != nil { + if snsMetadata, ok := awsAssets["snsMetadata"].(map[string]any); ok && snsMetadata != nil { if ingestionURL, exists := snsMetadata["ingestionURL"]; exists { awsData["sns_routing_url"] = ingestionURL } @@ -445,7 +445,7 @@ func dataSourceSysdigSecureCloudIngestionAssetsRead(ctx context.Context, d *sche awsData["eb_routing_key"] = awsAssets["ebRoutingKey"] } - if ebMetadata, ok := awsAssets["ebMetadata"].(map[string]interface{}); ok && ebMetadata != nil { + if ebMetadata, ok := awsAssets["ebMetadata"].(map[string]any); ok && ebMetadata != nil { if ingestionURL, exists := ebMetadata["ingestionURL"]; exists { awsData["eb_routing_url"] = ingestionURL } @@ -495,7 +495,7 @@ func dataSourceSysdigSecureTrustedOracleApp() *schema.Resource { } // Retrieves the information of a resource from the file and loads it in Terraform -func dataSourceSysdigSecureTrustedOracleAppRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTrustedOracleAppRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureOnboardingClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_onboarding_test.go b/sysdig/data_source_sysdig_secure_onboarding_test.go index aa86ab593..a5c3deb87 100644 --- a/sysdig/data_source_sysdig_secure_onboarding_test.go +++ b/sysdig/data_source_sysdig_secure_onboarding_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_policy.go b/sysdig/data_source_sysdig_secure_policy.go index 806458f61..859eec797 100644 --- a/sysdig/data_source_sysdig_secure_policy.go +++ b/sysdig/data_source_sysdig_secure_policy.go @@ -141,11 +141,12 @@ func policyDataSourceToResourceData(policy v2.Policy, d *schema.ResourceData) { _ = d.Set("notification_channels", policy.NotificationChannelIds) _ = d.Set("runbook", policy.Runbook) - actions := []map[string]interface{}{{}} + actions := []map[string]any{{}} for _, action := range policy.Actions { - if action.Type == "POLICY_ACTION_CAPTURE" { - actions[0]["capture"] = []map[string]interface{}{{ + switch action.Type { + case "POLICY_ACTION_CAPTURE": + actions[0]["capture"] = []map[string]any{{ "seconds_after_event": action.AfterEventNs / 1000000000, "seconds_before_event": action.BeforeEventNs / 1000000000, "name": action.Name, @@ -154,9 +155,9 @@ func policyDataSourceToResourceData(policy v2.Policy, d *schema.ResourceData) { "folder": action.Folder, }} - } else if action.Type == "POLICY_ACTION_KILL_PROCESS" { + case "POLICY_ACTION_KILL_PROCESS": actions[0]["kill_process"] = "true" - } else { + default: action := strings.Replace(action.Type, "POLICY_ACTION_", "", 1) actions[0]["container"] = strings.ToLower(action) } @@ -164,10 +165,10 @@ func policyDataSourceToResourceData(policy v2.Policy, d *schema.ResourceData) { _ = d.Set("actions", actions) - rules := []map[string]interface{}{} + rules := []map[string]any{} for _, rule := range policy.Rules { - rules = append(rules, map[string]interface{}{ + rules = append(rules, map[string]any{ "name": rule.Name, "enabled": rule.Enabled, }) @@ -176,7 +177,7 @@ func policyDataSourceToResourceData(policy v2.Policy, d *schema.ResourceData) { _ = d.Set("rules", rules) } -func commonDataSourceSecurePolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}, resourceName string, isPolicyCorrectType func(v2.Policy) bool) diag.Diagnostics { +func commonDataSourceSecurePolicyRead(ctx context.Context, d *schema.ResourceData, meta any, resourceName string, isPolicyCorrectType func(v2.Policy) bool) diag.Diagnostics { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_posture_policies.go b/sysdig/data_source_sysdig_secure_posture_policies.go index 3cee2bc2d..4e774c3f6 100644 --- a/sysdig/data_source_sysdig_secure_posture_policies.go +++ b/sysdig/data_source_sysdig_secure_posture_policies.go @@ -123,7 +123,7 @@ func getPosturePolicyClient(c SysdigClients) (v2.PosturePolicyInterface, error) return client, nil } -func dataSourceSysdigSecurePosturePoliciesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecurePosturePoliciesRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPosturePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -134,11 +134,11 @@ func dataSourceSysdigSecurePosturePoliciesRead(ctx context.Context, d *schema.Re return diag.FromErr(err) } - policies := make([]map[string]interface{}, len(resp)) + policies := make([]map[string]any, len(resp)) for i, p := range resp { - zones := make([]map[string]interface{}, len(p.Zones)) + zones := make([]map[string]any, len(p.Zones)) for j, z := range p.Zones { - zones[j] = map[string]interface{}{ + zones[j] = map[string]any{ SchemaIDKey: z.ID, SchemaNameKey: z.Name, } @@ -147,7 +147,7 @@ func dataSourceSysdigSecurePosturePoliciesRead(ctx context.Context, d *schema.Re if err != nil { return diag.FromErr(err) } - policies[i] = map[string]interface{}{ + policies[i] = map[string]any{ SchemaIDKey: policyID, SchemaNameKey: p.Name, SchemaTypeKey: p.Type, diff --git a/sysdig/data_source_sysdig_secure_posture_policies_test.go b/sysdig/data_source_sysdig_secure_posture_policies_test.go index fa3c8aed0..457544975 100644 --- a/sysdig/data_source_sysdig_secure_posture_policies_test.go +++ b/sysdig/data_source_sysdig_secure_posture_policies_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_posture_policy.go b/sysdig/data_source_sysdig_secure_posture_policy.go index d6e32812c..695e5684a 100644 --- a/sysdig/data_source_sysdig_secure_posture_policy.go +++ b/sysdig/data_source_sysdig_secure_posture_policy.go @@ -61,7 +61,7 @@ func dataSourceSysdigSecurePosturePolicy() *schema.Resource { } } -func dataSourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPosturePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -71,7 +71,7 @@ func dataSourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.Reso if err != nil { return diag.FromErr(err) } - policy, err := client.GetPosturePolicy(ctx, id) + policy, err := client.GetPosturePolicyByID(ctx, id) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/data_source_sysdig_secure_posture_policy_test.go b/sysdig/data_source_sysdig_secure_posture_policy_test.go index 96e46a624..f83e0f47a 100644 --- a/sysdig/data_source_sysdig_secure_posture_policy_test.go +++ b/sysdig/data_source_sysdig_secure_posture_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_posture_zone.go b/sysdig/data_source_sysdig_secure_posture_zone.go index a44cc78b2..fc07cc934 100644 --- a/sysdig/data_source_sysdig_secure_posture_zone.go +++ b/sysdig/data_source_sysdig_secure_posture_zone.go @@ -64,7 +64,7 @@ func dataSourceSysdigSecurePostureZone() *schema.Resource { } } -func dataSourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureZoneClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -75,7 +75,7 @@ func dataSourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - postureZone, err := client.GetPostureZone(ctx, id) + postureZone, err := client.GetPostureZoneByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -119,9 +119,9 @@ func dataSourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - scopes := make([]map[string]interface{}, len(postureZone.Scopes)) + scopes := make([]map[string]any, len(postureZone.Scopes)) for i, s := range postureZone.Scopes { - scopes[i] = map[string]interface{}{ + scopes[i] = map[string]any{ "target_type": s.TargetType, "rules": s.Rules, } diff --git a/sysdig/data_source_sysdig_secure_posture_zone_test.go b/sysdig/data_source_sysdig_secure_posture_zone_test.go index 6cf26e122..edbf9d30a 100644 --- a/sysdig/data_source_sysdig_secure_posture_zone_test.go +++ b/sysdig/data_source_sysdig_secure_posture_zone_test.go @@ -1,13 +1,12 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure || tf_acc_onprem_secure - package sysdig_test import ( "fmt" + "testing" + "github.com/draios/terraform-provider-sysdig/sysdig" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" diff --git a/sysdig/data_source_sysdig_secure_rule.go b/sysdig/data_source_sysdig_secure_rule.go index 607556c20..c53a920e1 100644 --- a/sysdig/data_source_sysdig_secure_rule.go +++ b/sysdig/data_source_sysdig_secure_rule.go @@ -52,7 +52,7 @@ func ruleDataSourceToResourceData(rule v2.Rule, d *schema.ResourceData) { _ = d.Set("version", rule.Version) } -func commonDataSourceSysdigRuleRead(ctx context.Context, d *schema.ResourceData, meta interface{}, ruleType string, setResourceData func(v2.Rule, *schema.ResourceData) diag.Diagnostics) diag.Diagnostics { +func commonDataSourceSysdigRuleRead(ctx context.Context, d *schema.ResourceData, meta any, ruleType string, setResourceData func(v2.Rule, *schema.ResourceData) diag.Diagnostics) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_rule_container.go b/sysdig/data_source_sysdig_secure_rule_container.go index eb4d7b08b..2d264cf3c 100644 --- a/sysdig/data_source_sysdig_secure_rule_container.go +++ b/sysdig/data_source_sysdig_secure_rule_container.go @@ -35,7 +35,7 @@ func dataSourceSysdigSecureRuleContainer() *schema.Resource { } } -func dataSourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSysdigRuleRead(ctx, d, meta, v2.RuleTypeContainer, containerRuleDataSourceToResourceData) } diff --git a/sysdig/data_source_sysdig_secure_rule_container_test.go b/sysdig/data_source_sysdig_secure_rule_container_test.go index 9343cc2bb..c1138fc15 100644 --- a/sysdig/data_source_sysdig_secure_rule_container_test.go +++ b/sysdig/data_source_sysdig_secure_rule_container_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_falco.go b/sysdig/data_source_sysdig_secure_rule_falco.go index f67f2396c..9ea2c89d7 100644 --- a/sysdig/data_source_sysdig_secure_rule_falco.go +++ b/sysdig/data_source_sysdig_secure_rule_falco.go @@ -81,7 +81,7 @@ func dataSourceSysdigSecureRuleFalco() *schema.Resource { } } -func dataSourceSysdigRuleFalcoRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleFalcoRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_rule_falco_count.go b/sysdig/data_source_sysdig_secure_rule_falco_count.go index 2c437ee04..52b5cf1fa 100644 --- a/sysdig/data_source_sysdig_secure_rule_falco_count.go +++ b/sysdig/data_source_sysdig_secure_rule_falco_count.go @@ -38,7 +38,7 @@ func dataSourceSysdigSecureRuleFalcoCount() *schema.Resource { } } -func dataSourceSysdigRuleFalcoCountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleFalcoCountRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_rule_falco_count_test.go b/sysdig/data_source_sysdig_secure_rule_falco_count_test.go index f6c53aa2b..fe0d514f9 100644 --- a/sysdig/data_source_sysdig_secure_rule_falco_count_test.go +++ b/sysdig/data_source_sysdig_secure_rule_falco_count_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_falco_test.go b/sysdig/data_source_sysdig_secure_rule_falco_test.go index 6d02359ce..698086542 100644 --- a/sysdig/data_source_sysdig_secure_rule_falco_test.go +++ b/sysdig/data_source_sysdig_secure_rule_falco_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_filesystem.go b/sysdig/data_source_sysdig_secure_rule_filesystem.go index 6c25d9385..7f6daec22 100644 --- a/sysdig/data_source_sysdig_secure_rule_filesystem.go +++ b/sysdig/data_source_sysdig_secure_rule_filesystem.go @@ -62,7 +62,7 @@ func dataSourceSysdigSecureRuleFilesystem() *schema.Resource { } } -func dataSourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -88,13 +88,13 @@ func dataSourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceD ruleDataSourceToResourceData(rule, d) if len(rule.Details.ReadPaths.Items) > 0 { - _ = d.Set("read_only", []map[string]interface{}{{ + _ = d.Set("read_only", []map[string]any{{ "matching": rule.Details.ReadPaths.MatchItems, "paths": rule.Details.ReadPaths.Items, }}) } if len(rule.Details.ReadWritePaths.Items) > 0 { - _ = d.Set("read_write", []map[string]interface{}{{ + _ = d.Set("read_write", []map[string]any{{ "matching": rule.Details.ReadWritePaths.MatchItems, "paths": rule.Details.ReadWritePaths.Items, }}) diff --git a/sysdig/data_source_sysdig_secure_rule_filesystem_test.go b/sysdig/data_source_sysdig_secure_rule_filesystem_test.go index 95b11b1ba..fb67c9b53 100644 --- a/sysdig/data_source_sysdig_secure_rule_filesystem_test.go +++ b/sysdig/data_source_sysdig_secure_rule_filesystem_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_network.go b/sysdig/data_source_sysdig_secure_rule_network.go index 344e0f9c8..484b82b4f 100644 --- a/sysdig/data_source_sysdig_secure_rule_network.go +++ b/sysdig/data_source_sysdig_secure_rule_network.go @@ -71,7 +71,7 @@ func dataSourceSysdigSecureRuleNetwork() *schema.Resource { } } -func dataSourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSysdigRuleRead(ctx, d, meta, v2.RuleTypeNetwork, networkRuleDataSourceToResourceData) } @@ -96,7 +96,7 @@ func networkRuleDataSourceToResourceData(rule v2.Rule, d *schema.ResourceData) d } tcpPorts = append(tcpPorts, intPort) } - _ = d.Set("tcp", []map[string]interface{}{{ + _ = d.Set("tcp", []map[string]any{{ "matching": rule.Details.TCPListenPorts.MatchItems, "ports": tcpPorts, }}) @@ -110,7 +110,7 @@ func networkRuleDataSourceToResourceData(rule v2.Rule, d *schema.ResourceData) d } udpPorts = append(udpPorts, intPort) } - _ = d.Set("udp", []map[string]interface{}{{ + _ = d.Set("udp", []map[string]any{{ "matching": rule.Details.UDPListenPorts.MatchItems, "ports": udpPorts, }}) diff --git a/sysdig/data_source_sysdig_secure_rule_network_test.go b/sysdig/data_source_sysdig_secure_rule_network_test.go index 1be6ffe71..92d814b7c 100644 --- a/sysdig/data_source_sysdig_secure_rule_network_test.go +++ b/sysdig/data_source_sysdig_secure_rule_network_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_process.go b/sysdig/data_source_sysdig_secure_rule_process.go index 953a6369a..1fe9ce6d6 100644 --- a/sysdig/data_source_sysdig_secure_rule_process.go +++ b/sysdig/data_source_sysdig_secure_rule_process.go @@ -35,7 +35,7 @@ func dataSourceSysdigSecureRuleProcess() *schema.Resource { } } -func dataSourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSysdigRuleRead(ctx, d, meta, v2.RuleTypeProcess, processRuleDataSourceToResourceData) } diff --git a/sysdig/data_source_sysdig_secure_rule_process_test.go b/sysdig/data_source_sysdig_secure_rule_process_test.go index 532be1956..f5f12f5af 100644 --- a/sysdig/data_source_sysdig_secure_rule_process_test.go +++ b/sysdig/data_source_sysdig_secure_rule_process_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_rule_stateful.go b/sysdig/data_source_sysdig_secure_rule_stateful.go index c12cae705..f8ba4881b 100644 --- a/sysdig/data_source_sysdig_secure_rule_stateful.go +++ b/sysdig/data_source_sysdig_secure_rule_stateful.go @@ -68,7 +68,7 @@ func dataSourceSysdigSecureRuleStateful() *schema.Resource { } } -func dataSourceSysdigRuleStatefulRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleStatefulRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_rule_stateful_count.go b/sysdig/data_source_sysdig_secure_rule_stateful_count.go index 9a731dc3b..b66945932 100644 --- a/sysdig/data_source_sysdig_secure_rule_stateful_count.go +++ b/sysdig/data_source_sysdig_secure_rule_stateful_count.go @@ -37,7 +37,7 @@ func dataSourceSysdigSecureRuleStatefulCount() *schema.Resource { } } -func dataSourceSysdigRuleStatefulCountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleStatefulCountRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_secure_rule_stateful_count_test.go b/sysdig/data_source_sysdig_secure_rule_stateful_count_test.go index 0a7c3c918..87b456f93 100644 --- a/sysdig/data_source_sysdig_secure_rule_stateful_count_test.go +++ b/sysdig/data_source_sysdig_secure_rule_stateful_count_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( @@ -15,7 +13,6 @@ import ( ) func TestAccRuleStatefulCountDataSource(t *testing.T) { - if strings.HasSuffix(os.Getenv("SYSDIG_SECURE_URL"), "ibm.com") { t.Skip("Skipping stateful tests for IBM Cloud") return diff --git a/sysdig/data_source_sysdig_secure_rule_stateful_test.go b/sysdig/data_source_sysdig_secure_rule_stateful_test.go index 41278e098..27e21395c 100644 --- a/sysdig/data_source_sysdig_secure_rule_stateful_test.go +++ b/sysdig/data_source_sysdig_secure_rule_stateful_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( @@ -15,7 +13,6 @@ import ( ) func TestAccRuleStatefulDataSource(t *testing.T) { - if strings.HasSuffix(os.Getenv("SYSDIG_SECURE_URL"), "ibm.com") { t.Skip("Skipping stateful tests for IBM Cloud") return diff --git a/sysdig/data_source_sysdig_secure_rule_syscall.go b/sysdig/data_source_sysdig_secure_rule_syscall.go index d509fca7d..cc09ebf77 100644 --- a/sysdig/data_source_sysdig_secure_rule_syscall.go +++ b/sysdig/data_source_sysdig_secure_rule_syscall.go @@ -35,7 +35,7 @@ func dataSourceSysdigSecureRuleSyscall() *schema.Resource { } } -func dataSourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { return commonDataSourceSysdigRuleRead(ctx, d, meta, v2.RuleTypeSyscall, syscallRuleDataSourceToResourceData) } diff --git a/sysdig/data_source_sysdig_secure_rule_syscall_test.go b/sysdig/data_source_sysdig_secure_rule_syscall_test.go index 5e304878a..d5bbd7df3 100644 --- a/sysdig/data_source_sysdig_secure_rule_syscall_test.go +++ b/sysdig/data_source_sysdig_secure_rule_syscall_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig || tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_team.go b/sysdig/data_source_sysdig_secure_team.go index d46e1d5a8..e63ce9c9d 100644 --- a/sysdig/data_source_sysdig_secure_team.go +++ b/sysdig/data_source_sysdig_secure_team.go @@ -87,7 +87,7 @@ func dataSourceSysdigSecureTeam() *schema.Resource { } } -func dataSourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureTeamClient(clients) if err != nil { @@ -99,7 +99,7 @@ func dataSourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, return diag.FromErr(err) } - team, err := client.GetTeamById(ctx, id) + team, err := client.GetTeamByID(ctx, id) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/data_source_sysdig_secure_team_test.go b/sysdig/data_source_sysdig_secure_team_test.go index e961d7183..1eff7e23f 100644 --- a/sysdig/data_source_sysdig_secure_team_test.go +++ b/sysdig/data_source_sysdig_secure_team_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_secure_teams.go b/sysdig/data_source_sysdig_secure_teams.go index 59a5e565a..dc1bfcb19 100644 --- a/sysdig/data_source_sysdig_secure_teams.go +++ b/sysdig/data_source_sysdig_secure_teams.go @@ -31,7 +31,7 @@ func dataSourceSysdigSecureTeams() *schema.Resource { } } -func dataSourceSysdigSecureTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigSecureTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureTeamClient(clients) if err != nil { @@ -43,9 +43,9 @@ func dataSourceSysdigSecureTeamsRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(err) } - var result []map[string]interface{} + var result []map[string]any for _, team := range teams { - result = append(result, map[string]interface{}{ + result = append(result, map[string]any{ "id": team.ID, "name": team.Name, }) diff --git a/sysdig/data_source_sysdig_secure_teams_test.go b/sysdig/data_source_sysdig_secure_teams_test.go index 4f2ee453e..47c00e2d3 100644 --- a/sysdig/data_source_sysdig_secure_teams_test.go +++ b/sysdig/data_source_sysdig_secure_teams_test.go @@ -1,12 +1,11 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure || tf_acc_ibm_secure - package sysdig_test import ( "fmt" + "testing" + "github.com/draios/terraform-provider-sysdig/sysdig" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) diff --git a/sysdig/data_source_sysdig_secure_zone.go b/sysdig/data_source_sysdig_secure_zone.go index 595cd3e65..ddb2c2efa 100644 --- a/sysdig/data_source_sysdig_secure_zone.go +++ b/sysdig/data_source_sysdig_secure_zone.go @@ -73,7 +73,7 @@ func dataSourceSysdigSecureZone() *schema.Resource { } } -func dataSourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func dataSourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := getZoneClient(m.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -86,7 +86,7 @@ func dataSourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, if err != nil { return diag.FromErr(fmt.Errorf("invalid zone id: %s", err)) } - zone, err = client.GetZoneById(ctx, zoneID) + zone, err = client.GetZoneByID(ctx, zoneID) if err != nil { return diag.FromErr(fmt.Errorf("error fetching zone by ID: %s", err)) } diff --git a/sysdig/data_source_sysdig_secure_zone_test.go b/sysdig/data_source_sysdig_secure_zone_test.go index 203aad03d..8a985e22f 100644 --- a/sysdig/data_source_sysdig_secure_zone_test.go +++ b/sysdig/data_source_sysdig_secure_zone_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure || tf_acc_ibm_secure - package sysdig_test import ( diff --git a/sysdig/data_source_sysdig_user.go b/sysdig/data_source_sysdig_user.go index ab0c7a1e7..42a21d4df 100644 --- a/sysdig/data_source_sysdig_user.go +++ b/sysdig/data_source_sysdig_user.go @@ -44,7 +44,7 @@ func dataSourceSysdigUser() *schema.Resource { } } -func dataSourceSysdigUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func dataSourceSysdigUserRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/data_source_sysdig_user_test.go b/sysdig/data_source_sysdig_user_test.go index 4e66800f3..a5ce002b7 100644 --- a/sysdig/data_source_sysdig_user_test.go +++ b/sysdig/data_source_sysdig_user_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go index cc4bea680..2bac9c0c0 100644 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go +++ b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go @@ -110,7 +110,7 @@ func getDeprecatedSecureScanningPolicyClient(c SysdigClients) (v2.DeprecatedScan return c.sysdigSecureClientV2() } -func deprecatedResourceSysdigScanningPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -127,7 +127,7 @@ func deprecatedResourceSysdigScanningPolicyCreate(ctx context.Context, d *schema return nil } -func deprecatedResourceSysdigScanningPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -136,7 +136,7 @@ func deprecatedResourceSysdigScanningPolicyUpdate(ctx context.Context, d *schema scanningPolicy := deprecatedScanningPolicyFromResourceData(d) id := d.Get("id").(string) scanningPolicy.ID = id - _, err = client.UpdateDeprecatedScanningPolicyByID(ctx, scanningPolicy) + _, err = client.UpdateDeprecatedScanningPolicy(ctx, scanningPolicy) if err != nil { return diag.FromErr(err) } @@ -144,7 +144,7 @@ func deprecatedResourceSysdigScanningPolicyUpdate(ctx context.Context, d *schema return nil } -func deprecatedResourceSysdigScanningPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -161,7 +161,7 @@ func deprecatedResourceSysdigScanningPolicyRead(ctx context.Context, d *schema.R return nil } -func deprecatedResourceSysdigScanningPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -182,9 +182,9 @@ func deprecatedScanningPolicyToResourceData(scanningPolicy *v2.DeprecatedScannin _ = d.Set("version", scanningPolicy.Version) _ = d.Set("comment", scanningPolicy.Comment) _ = d.Set("isdefault", scanningPolicy.IsDefault) - _ = d.Set("policy_bundle_id", scanningPolicy.PolicyBundleId) + _ = d.Set("policy_bundle_id", scanningPolicy.PolicyBundleID) - var rules []map[string]interface{} + var rules []map[string]any for _, rule := range scanningPolicy.Rules { ruleInfo := deprecatedScanningPolicyRulesToResourceData(rule) @@ -194,17 +194,17 @@ func deprecatedScanningPolicyToResourceData(scanningPolicy *v2.DeprecatedScannin _ = d.Set("rules", rules) } -func deprecatedScanningPolicyRulesToResourceData(scanningPolicyRule v2.DeprecatedScanningGate) map[string]interface{} { - rule := map[string]interface{}{ +func deprecatedScanningPolicyRulesToResourceData(scanningPolicyRule v2.DeprecatedScanningGate) map[string]any { + rule := map[string]any{ "id": scanningPolicyRule.ID, "gate": scanningPolicyRule.Gate, "trigger": scanningPolicyRule.Trigger, "action": scanningPolicyRule.Action, } - var params []map[string]interface{} + var params []map[string]any for _, param := range scanningPolicyRule.Params { - params = append(params, map[string]interface{}{ + params = append(params, map[string]any{ "name": param.Name, "value": param.Value, }) @@ -221,7 +221,7 @@ func deprecatedScanningPolicyFromResourceData(d *schema.ResourceData) v2.Depreca Comment: d.Get("comment").(string), Version: d.Get("version").(string), IsDefault: d.Get("isdefault").(bool), - PolicyBundleId: d.Get("policy_bundle_id").(string), + PolicyBundleID: d.Get("policy_bundle_id").(string), } scanningPolicy.Rules = deprecatedScanningPolicyRulesFromResourceData(d) @@ -230,7 +230,7 @@ func deprecatedScanningPolicyFromResourceData(d *schema.ResourceData) v2.Depreca func deprecatedScanningPolicyRulesFromResourceData(d *schema.ResourceData) (rules []v2.DeprecatedScanningGate) { for _, ruleItr := range d.Get("rules").(*schema.Set).List() { - ruleInfo := ruleItr.(map[string]interface{}) + ruleInfo := ruleItr.(map[string]any) rule := v2.DeprecatedScanningGate{ Gate: ruleInfo["gate"].(string), ID: ruleInfo["id"].(string), @@ -239,7 +239,7 @@ func deprecatedScanningPolicyRulesFromResourceData(d *schema.ResourceData) (rule } var params []v2.DeprecatedScanningGateParam for _, paramsItr := range ruleInfo["params"].(*schema.Set).List() { - paramsInfo := paramsItr.(map[string]interface{}) + paramsInfo := paramsItr.(map[string]any) param := v2.DeprecatedScanningGateParam{ Name: paramsInfo["name"].(string), Value: paramsInfo["value"].(string), diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go index 3bb98b3f9..9ebab245b 100644 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go +++ b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - package sysdig_test import ( diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go index 243e90d6d..5a1a81cea 100644 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go +++ b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go @@ -100,7 +100,7 @@ func getDeprecatedSecureScanningPolicyAssignmentClient(c SysdigClients) (v2.Depr return c.sysdigSecureClientV2() } -func deprecatedResourceSysdigScanningPolicyAssignmentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyAssignmentCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -123,7 +123,7 @@ func deprecatedResourceSysdigScanningPolicyAssignmentCreate(ctx context.Context, return nil } -func deprecatedResourceSysdigScanningPolicyAssignmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyAssignmentRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -139,7 +139,7 @@ func deprecatedResourceSysdigScanningPolicyAssignmentRead(ctx context.Context, d return nil } -func deprecatedResourceSysdigScanningPolicyAssignmentUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyAssignmentUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -162,7 +162,7 @@ func deprecatedResourceSysdigScanningPolicyAssignmentUpdate(ctx context.Context, } // As Policy Assignments cannot be empty (default assignment cannot be deleted), pushing the default one -func deprecatedResourceSysdigScanningPolicyAssignmentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigScanningPolicyAssignmentDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -182,7 +182,7 @@ func deprecatedResourceSysdigScanningPolicyAssignmentDelete(ctx context.Context, } scanningPolicyAssignmentList := v2.DeprecatedScanningPolicyAssignmentList{ - PolicyBundleId: "default", // this is forced because there is no other possible value + PolicyBundleID: "default", // this is forced because there is no other possible value Items: []v2.DeprecatedScanningPolicyAssignment{defaultItem}, } @@ -195,9 +195,9 @@ func deprecatedResourceSysdigScanningPolicyAssignmentDelete(ctx context.Context, } func deprecatedScanningPolicyAssignmentListToResourceData(scanningPolicyAssignmentList *v2.DeprecatedScanningPolicyAssignmentList, d *schema.ResourceData) { - d.SetId(scanningPolicyAssignmentList.PolicyBundleId) - _ = d.Set("policy_bundle_id", scanningPolicyAssignmentList.PolicyBundleId) - var items []map[string]interface{} + d.SetId(scanningPolicyAssignmentList.PolicyBundleID) + _ = d.Set("policy_bundle_id", scanningPolicyAssignmentList.PolicyBundleID) + var items []map[string]any for _, item := range scanningPolicyAssignmentList.Items { itemInfo := deprecatedScanningPolicyAssignmentToResourceData(item) @@ -208,8 +208,8 @@ func deprecatedScanningPolicyAssignmentListToResourceData(scanningPolicyAssignme _ = d.Set("items", items) } -func deprecatedScanningPolicyAssignmentToResourceData(scanningPolicyAssignment v2.DeprecatedScanningPolicyAssignment) map[string]interface{} { - item := map[string]interface{}{ +func deprecatedScanningPolicyAssignmentToResourceData(scanningPolicyAssignment v2.DeprecatedScanningPolicyAssignment) map[string]any { + item := map[string]any{ "id": scanningPolicyAssignment.ID, "name": scanningPolicyAssignment.Name, "registry": scanningPolicyAssignment.Registry, @@ -218,7 +218,7 @@ func deprecatedScanningPolicyAssignmentToResourceData(scanningPolicyAssignment v "whitelist_ids": scanningPolicyAssignment.WhitelistIDs, } - image := []map[string]interface{}{{ + image := []map[string]any{{ "type": scanningPolicyAssignment.Image.Type, "value": scanningPolicyAssignment.Image.Value, }} @@ -230,7 +230,7 @@ func deprecatedScanningPolicyAssignmentToResourceData(scanningPolicyAssignment v func deprecatedScanningPolicyAssignmentListFromResourceData(d *schema.ResourceData) v2.DeprecatedScanningPolicyAssignmentList { scanningPolicyAssignmentList := v2.DeprecatedScanningPolicyAssignmentList{ - PolicyBundleId: "default", // this is forced because there is no other possible value + PolicyBundleID: "default", // this is forced because there is no other possible value } scanningPolicyAssignmentList.Items = deprecatedScanningPolicyAssignmentFromResourceData(d) @@ -239,8 +239,8 @@ func deprecatedScanningPolicyAssignmentListFromResourceData(d *schema.ResourceDa } func deprecatedScanningPolicyAssignmentFromResourceData(d *schema.ResourceData) (scanningPolicyAssignmentItems []v2.DeprecatedScanningPolicyAssignment) { - for _, item := range d.Get("items").([]interface{}) { - assignmentInfo := item.(map[string]interface{}) + for _, item := range d.Get("items").([]any) { + assignmentInfo := item.(map[string]any) assignment := v2.DeprecatedScanningPolicyAssignment{ Name: assignmentInfo["name"].(string), Registry: assignmentInfo["registry"].(string), @@ -248,24 +248,24 @@ func deprecatedScanningPolicyAssignmentFromResourceData(d *schema.ResourceData) } assignment.PolicyIDs = []string{} - policyIDsSet := assignmentInfo["policy_ids"].([]interface{}) + policyIDsSet := assignmentInfo["policy_ids"].([]any) for _, policy := range policyIDsSet { assignment.PolicyIDs = append(assignment.PolicyIDs, policy.(string)) } assignment.WhitelistIDs = []string{} - whitelistIDsSet := assignmentInfo["whitelist_ids"].([]interface{}) + whitelistIDsSet := assignmentInfo["whitelist_ids"].([]any) for _, policy := range whitelistIDsSet { assignment.WhitelistIDs = append(assignment.WhitelistIDs, policy.(string)) } - imageSet := assignmentInfo["image"].([]interface{}) + imageSet := assignmentInfo["image"].([]any) if len(imageSet) == 0 { return } for _, image := range imageSet { assignment.Image = v2.DeprecatedScanningPolicyAssignmentImage{ - Type: image.(map[string]interface{})["type"].(string), - Value: image.(map[string]interface{})["value"].(string), + Type: image.(map[string]any)["type"].(string), + Value: image.(map[string]any)["value"].(string), } } @@ -286,7 +286,7 @@ func deprecatedValidateScanningPolicyAssignment(scanningPolicyAssignmentList v2. // validate default assignment lastItem := scanningPolicyAssignmentList.Items[len(scanningPolicyAssignmentList.Items)-1] if lastItem.Image.Value != "*" || lastItem.Registry != "*" || lastItem.Repository != "*" { - return diag.FromErr(errors.New("Default policy assignment has to be registry='*', repository='*' and image.tag='*?")) + return diag.FromErr(errors.New("default policy assignment has to be registry='*', repository='*' and image.tag='*?")) } return nil diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go index 0baf5250f..1e05ed7ea 100644 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go +++ b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - package sysdig_test import ( diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go index 97e77b90d..211ff3406 100644 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go +++ b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go @@ -22,7 +22,7 @@ func deprecatedResourceSysdigSecureVulnerabilityException() *schema.Resource { UpdateContext: deprecatedResourceSysdigVulnerabilityExceptionUpdate, DeleteContext: deprecatedResourceSysdigVulnerabilityExceptionDelete, Importer: &schema.ResourceImporter{ - StateContext: func(ctx context.Context, data *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + StateContext: func(ctx context.Context, data *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { parts := strings.SplitN(data.Id(), "/", 2) if len(parts) != 2 || parts[0] == "" || parts[1] == "" { return nil, fmt.Errorf("unexpected format of ID (%s), expected listID:exceptionID", data.Id()) @@ -114,7 +114,7 @@ func deprecatedVulnerabilityExceptionToResourceData(exception *v2.DeprecatedVuln return nil } -func deprecatedResourceSysdigVulnerabilityExceptionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigVulnerabilityExceptionCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -135,7 +135,7 @@ func deprecatedResourceSysdigVulnerabilityExceptionCreate(ctx context.Context, d return nil } -func deprecatedResourceSysdigVulnerabilityExceptionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigVulnerabilityExceptionRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -155,7 +155,7 @@ func deprecatedResourceSysdigVulnerabilityExceptionRead(ctx context.Context, d * return nil } -func deprecatedResourceSysdigVulnerabilityExceptionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigVulnerabilityExceptionDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -169,7 +169,7 @@ func deprecatedResourceSysdigVulnerabilityExceptionDelete(ctx context.Context, d return nil } -func deprecatedResourceSysdigVulnerabilityExceptionUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func deprecatedResourceSysdigVulnerabilityExceptionUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go index 3e101d59e..ca76aa932 100644 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go +++ b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go @@ -47,7 +47,7 @@ func getSecureSecureVulnerabilityExceptionListClient(c SysdigClients) (v2.Deprec return c.sysdigSecureClientV2() } -func resourceSysdigVulnerabilityExceptionListCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigVulnerabilityExceptionListCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -68,7 +68,7 @@ func resourceSysdigVulnerabilityExceptionListCreate(ctx context.Context, d *sche return nil } -func resourceSysdigVulnerabilityExceptionListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigVulnerabilityExceptionListRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -88,7 +88,7 @@ func resourceSysdigVulnerabilityExceptionListRead(ctx context.Context, d *schema return nil } -func resourceSysdigVulnerabilityExceptionListDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigVulnerabilityExceptionListDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -102,7 +102,7 @@ func resourceSysdigVulnerabilityExceptionListDelete(ctx context.Context, d *sche return nil } -func resourceSysdigVulnerabilityExceptionListUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigVulnerabilityExceptionListUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go index b7cfb0ace..ad24fb49d 100644 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go +++ b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - package sysdig_test import ( diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go index da84a8141..7c72ba7f0 100644 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go +++ b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - package sysdig_test import ( diff --git a/sysdig/helpers.go b/sysdig/helpers.go index 6486a2281..bacee526b 100644 --- a/sysdig/helpers.go +++ b/sysdig/helpers.go @@ -14,8 +14,8 @@ import ( // // Deprecated: use your own functions, this wrapper will be removed as // soon as the new validate functions are supported by the SDK -func validateDiagFunc(validateFunc func(interface{}, string) ([]string, []error)) schema.SchemaValidateDiagFunc { - return func(i interface{}, path cty.Path) diag.Diagnostics { +func validateDiagFunc(validateFunc func(any, string) ([]string, []error)) schema.SchemaValidateDiagFunc { + return func(i any, path cty.Path) diag.Diagnostics { warnings, errs := validateFunc(i, fmt.Sprintf("%+v", path)) var diags diag.Diagnostics for _, warning := range warnings { @@ -38,7 +38,7 @@ func validateDiagFunc(validateFunc func(interface{}, string) ([]string, []error) func parseAzureCreds(azureTrustedIdentity string) (tenantID string, spID string, err error) { tokens := strings.Split(azureTrustedIdentity, ":") if len(tokens) != 2 { - return "", "", errors.New("Not a valid Azure Trusted Identity") + return "", "", errors.New("not a valid Azure Trusted Identity") } return tokens[0], tokens[1], nil } diff --git a/sysdig/internal/client/v2/agentaccesskey.go b/sysdig/internal/client/v2/agentaccesskey.go index 4aee0db12..bb2926bc0 100644 --- a/sysdig/internal/client/v2/agentaccesskey.go +++ b/sysdig/internal/client/v2/agentaccesskey.go @@ -7,10 +7,10 @@ import ( ) const ( - GetAgentAccessKeyByIdPath = "%s/platform/v1/access-keys/%s" - CreateAgentAccessKeyPath = "%s/platform/v1/access-keys" - DeleteAgentAccessKeyPath = "%s/platform/v1/access-keys/%s" - PutAgentAccessKeyPath = "%s/platform/v1/access-keys/%s" + getAgentAccessKeyByIDPath = "%s/platform/v1/access-keys/%s" + createAgentAccessKeyPath = "%s/platform/v1/access-keys" + deleteAgentAccessKeyPath = "%s/platform/v1/access-keys/%s" + putAgentAccessKeyPath = "%s/platform/v1/access-keys/%s" ) type AgentAccessKeyInterface interface { @@ -21,102 +21,101 @@ type AgentAccessKeyInterface interface { UpdateAgentAccessKey(ctx context.Context, agentAccessKey *AgentAccessKey, id string) (*AgentAccessKey, error) } -func (client *Client) GetAgentAccessKeyByID(ctx context.Context, id string) (*AgentAccessKey, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetAgentAccessKeyByIdUrl(id), nil) +func (c *Client) GetAgentAccessKeyByID(ctx context.Context, id string) (accessKey *AgentAccessKey, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getAgentAccessKeyByIDUrl(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } - agentAccessKey, err := Unmarshal[AgentAccessKey](response.Body) - if err != nil { - return nil, err - } - - return &agentAccessKey, nil + return Unmarshal[*AgentAccessKey](response.Body) } -func (client *Client) CreateAgentAccessKey(ctx context.Context, agentAccessKey *AgentAccessKey) (*AgentAccessKey, error) { +func (c *Client) CreateAgentAccessKey(ctx context.Context, agentAccessKey *AgentAccessKey) (createdAccessKey *AgentAccessKey, err error) { payload, err := Marshal(agentAccessKey) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.PostAgentAccessKeyUrl(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.postAgentAccessKeyURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusCreated { - err = client.ErrorFromResponse(response) - return nil, err - } - - createdAgentAccessKey, err := Unmarshal[AgentAccessKey](response.Body) - - if err != nil { + err = c.ErrorFromResponse(response) return nil, err } - return &createdAgentAccessKey, nil + return Unmarshal[*AgentAccessKey](response.Body) } -func (client *Client) UpdateAgentAccessKey(ctx context.Context, agentAccessKey *AgentAccessKey, id string) (*AgentAccessKey, error) { - +func (c *Client) UpdateAgentAccessKey(ctx context.Context, agentAccessKey *AgentAccessKey, id string) (updatedAccessKey *AgentAccessKey, err error) { payload, err := Marshal(agentAccessKey) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.PutAgentAccessKeyUrl(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.putAgentAccessKeyURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) - return nil, err - } - - updatedAgentAccessKey, err := Unmarshal[AgentAccessKey](response.Body) - if err != nil { + err = c.ErrorFromResponse(response) return nil, err } - return &updatedAgentAccessKey, nil + return Unmarshal[*AgentAccessKey](response.Body) } -func (client *Client) DeleteAgentAccessKey(ctx context.Context, id string) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteAgentAccessKeyUrl(id), nil) +func (c *Client) DeleteAgentAccessKey(ctx context.Context, id string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.DeleteAgentAccessKeyURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetAgentAccessKeyByIdUrl(id string) string { - return fmt.Sprintf(GetAgentAccessKeyByIdPath, client.config.url, id) +func (c *Client) getAgentAccessKeyByIDUrl(id string) string { + return fmt.Sprintf(getAgentAccessKeyByIDPath, c.config.url, id) } -func (client *Client) PostAgentAccessKeyUrl() string { - return fmt.Sprintf(CreateAgentAccessKeyPath, client.config.url) +func (c *Client) postAgentAccessKeyURL() string { + return fmt.Sprintf(createAgentAccessKeyPath, c.config.url) } -func (client *Client) PutAgentAccessKeyUrl(id string) string { - return fmt.Sprintf(PutAgentAccessKeyPath, client.config.url, id) +func (c *Client) putAgentAccessKeyURL(id string) string { + return fmt.Sprintf(putAgentAccessKeyPath, c.config.url, id) } -func (client *Client) DeleteAgentAccessKeyUrl(id string) string { - return fmt.Sprintf(DeleteAgentAccessKeyPath, client.config.url, id) +func (c *Client) DeleteAgentAccessKeyURL(id string) string { + return fmt.Sprintf(deleteAgentAccessKeyPath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/alerts.go b/sysdig/internal/client/v2/alerts.go index 5311aedd3..cce6f1c2d 100644 --- a/sysdig/internal/client/v2/alerts.go +++ b/sysdig/internal/client/v2/alerts.go @@ -7,34 +7,38 @@ import ( ) const ( - CreateAlertPath = "%s/api/alerts" - DeleteAlertPath = "%s/api/alerts/%d" - UpdateAlertPath = "%s/api/alerts/%d" - GetAlertPath = "%s/api/alerts/%d" + createAlertPath = "%s/api/alerts" + deleteAlertPath = "%s/api/alerts/%d" + updateAlertPath = "%s/api/alerts/%d" + getAlertPath = "%s/api/alerts/%d" ) type AlertInterface interface { Base CreateAlert(ctx context.Context, alert Alert) (Alert, error) - DeleteAlert(ctx context.Context, alertID int) error - UpdateAlert(ctx context.Context, alert Alert) (Alert, error) GetAlertByID(ctx context.Context, alertID int) (Alert, error) + UpdateAlert(ctx context.Context, alert Alert) (Alert, error) + DeleteAlertByID(ctx context.Context, alertID int) error } -func (client *Client) CreateAlert(ctx context.Context, alert Alert) (Alert, error) { - payload, err := Marshal[alertWrapper](alertWrapper{Alert: alert}) +func (c *Client) CreateAlert(ctx context.Context, alert Alert) (createdAlert Alert, err error) { + payload, err := Marshal(alertWrapper{Alert: alert}) if err != nil { return Alert{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateAlertURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createAlertURL(), payload) if err != nil { return Alert{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Alert{}, client.ErrorFromResponse(response) + return Alert{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[alertWrapper](response.Body) @@ -45,34 +49,42 @@ func (client *Client) CreateAlert(ctx context.Context, alert Alert) (Alert, erro return wrapper.Alert, nil } -func (client *Client) DeleteAlert(ctx context.Context, alertID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteAlertURL(alertID), nil) +func (c *Client) DeleteAlertByID(ctx context.Context, alertID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteAlertURL(alertID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) UpdateAlert(ctx context.Context, alert Alert) (Alert, error) { - payload, err := Marshal[alertWrapper](alertWrapper{Alert: alert}) +func (c *Client) UpdateAlert(ctx context.Context, alert Alert) (updatedAlert Alert, err error) { + payload, err := Marshal(alertWrapper{Alert: alert}) if err != nil { return Alert{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateAlertURL(alert.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateAlertURL(alert.ID), payload) if err != nil { return Alert{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Alert{}, client.ErrorFromResponse(response) + return Alert{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[alertWrapper](response.Body) @@ -83,15 +95,19 @@ func (client *Client) UpdateAlert(ctx context.Context, alert Alert) (Alert, erro return wrapper.Alert, nil } -func (client *Client) GetAlertByID(ctx context.Context, alertID int) (Alert, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetAlertByIDURL(alertID), nil) +func (c *Client) GetAlertByID(ctx context.Context, alertID int) (alert Alert, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getAlertByIDURL(alertID), nil) if err != nil { return Alert{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Alert{}, client.ErrorFromResponse(response) + return Alert{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[alertWrapper](response.Body) @@ -102,18 +118,18 @@ func (client *Client) GetAlertByID(ctx context.Context, alertID int) (Alert, err return wrapper.Alert, nil } -func (client *Client) CreateAlertURL() string { - return fmt.Sprintf(CreateAlertPath, client.config.url) +func (c *Client) createAlertURL() string { + return fmt.Sprintf(createAlertPath, c.config.url) } -func (client *Client) DeleteAlertURL(alertID int) string { - return fmt.Sprintf(DeleteAlertPath, client.config.url, alertID) +func (c *Client) deleteAlertURL(alertID int) string { + return fmt.Sprintf(deleteAlertPath, c.config.url, alertID) } -func (client *Client) UpdateAlertURL(alertID int) string { - return fmt.Sprintf(UpdateAlertPath, client.config.url, alertID) +func (c *Client) updateAlertURL(alertID int) string { + return fmt.Sprintf(updateAlertPath, c.config.url, alertID) } -func (client *Client) GetAlertByIDURL(alertID int) string { - return fmt.Sprintf(GetAlertPath, client.config.url, alertID) +func (c *Client) getAlertByIDURL(alertID int) string { + return fmt.Sprintf(getAlertPath, c.config.url, alertID) } diff --git a/sysdig/internal/client/v2/alerts_v2.go b/sysdig/internal/client/v2/alerts_v2.go index 3d88e23ab..556696640 100644 --- a/sysdig/internal/client/v2/alerts_v2.go +++ b/sysdig/internal/client/v2/alerts_v2.go @@ -10,7 +10,7 @@ import ( "sync" ) -var AlertV2NotFound = errors.New("alert not found") +var ErrAlertV2NotFound = errors.New("alert not found") type ( AlertV2Type string @@ -23,7 +23,9 @@ const ( alertV2Path = "%s/api/v2/alerts/%d" labelsV3Path = "%s/api/v3/labels/?limit=6000" labelsV3DescriptorsPath = "%s/api/v3/labels/descriptors/%s" +) +const ( AlertV2TypePrometheus AlertV2Type = "PROMETHEUS" AlertV2TypeManual AlertV2Type = "MANUAL" AlertV2TypeEvent AlertV2Type = "EVENT" @@ -31,12 +33,16 @@ const ( AlertV2TypeFormBasedPrometheus AlertV2Type = "FORM_BASED_PROMETHEUS" AlertV2TypeGroupOutlier AlertV2Type = "GROUP_OUTLIERS" AlertV2TypeDowntime AlertV2Type = "DOWNTIME" +) +const ( AlertV2SeverityHigh AlertV2Severity = "high" AlertV2SeverityMedium AlertV2Severity = "medium" AlertV2SeverityLow AlertV2Severity = "low" AlertV2SeverityInfo AlertV2Severity = "info" +) +const ( AlertLinkV2TypeDashboard AlertLinkV2Type = "dashboard" AlertLinkV2TypeRunbook AlertLinkV2Type = "runbook" ) @@ -61,7 +67,7 @@ type AlertV2PrometheusInterface interface { Base CreateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (AlertV2Prometheus, error) UpdateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (AlertV2Prometheus, error) - GetAlertV2Prometheus(ctx context.Context, alertID int) (AlertV2Prometheus, error) + GetAlertV2PrometheusByID(ctx context.Context, alertID int) (AlertV2Prometheus, error) DeleteAlertV2Prometheus(ctx context.Context, alertID int) error } @@ -69,7 +75,7 @@ type AlertV2EventInterface interface { Base CreateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) UpdateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) - GetAlertV2Event(ctx context.Context, alertID int) (AlertV2Event, error) + GetAlertV2EventByID(ctx context.Context, alertID int) (AlertV2Event, error) DeleteAlertV2Event(ctx context.Context, alertID int) error } @@ -77,7 +83,7 @@ type AlertV2MetricInterface interface { Base CreateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) UpdateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) - GetAlertV2Metric(ctx context.Context, alertID int) (AlertV2Metric, error) + GetAlertV2MetricByID(ctx context.Context, alertID int) (AlertV2Metric, error) DeleteAlertV2Metric(ctx context.Context, alertID int) error } @@ -85,7 +91,7 @@ type AlertV2ChangeInterface interface { Base CreateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) UpdateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) - GetAlertV2Change(ctx context.Context, alertID int) (AlertV2Change, error) + GetAlertV2ChangeByID(ctx context.Context, alertID int) (AlertV2Change, error) DeleteAlertV2Change(ctx context.Context, alertID int) error } @@ -93,7 +99,7 @@ type AlertV2FormBasedPrometheusInterface interface { Base CreateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) UpdateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) - GetAlertV2FormBasedPrometheus(ctx context.Context, alertID int) (AlertV2FormBasedPrometheus, error) + GetAlertV2FormBasedPrometheusByID(ctx context.Context, alertID int) (AlertV2FormBasedPrometheus, error) DeleteAlertV2FormBasedPrometheus(ctx context.Context, alertID int) error } @@ -101,7 +107,7 @@ type AlertV2GroupOutlierInterface interface { Base CreateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) UpdateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) - GetAlertV2GroupOutlier(ctx context.Context, alertID int) (AlertV2GroupOutlier, error) + GetAlertV2GroupOutlierByID(ctx context.Context, alertID int) (AlertV2GroupOutlier, error) DeleteAlertV2GroupOutlier(ctx context.Context, alertID int) error } @@ -109,12 +115,12 @@ type AlertV2DowntimeInterface interface { Base CreateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) UpdateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) - GetAlertV2Downtime(ctx context.Context, alertID int) (AlertV2Downtime, error) + GetAlertV2DowntimeByID(ctx context.Context, alertID int) (AlertV2Downtime, error) DeleteAlertV2Downtime(ctx context.Context, alertID int) error } -func (client *Client) CreateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (AlertV2Prometheus, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (createdAlert AlertV2Prometheus, err error) { + err = c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Prometheus{}, err } @@ -124,21 +130,15 @@ func (client *Client) CreateAlertV2Prometheus(ctx context.Context, alert AlertV2 return AlertV2Prometheus{}, err } - body, err := client.createAlertV2(ctx, payload) + wrapper, err := createAlertV2AndUnmarshal[alertV2PrometheusWrapper](ctx, c, payload) if err != nil { return AlertV2Prometheus{}, err } - - wrapper, err := Unmarshal[alertV2PrometheusWrapper](body) - if err != nil { - return AlertV2Prometheus{}, err - } - return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (AlertV2Prometheus, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2Prometheus(ctx context.Context, alert AlertV2Prometheus) (AlertV2Prometheus, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Prometheus{}, err } @@ -148,12 +148,7 @@ func (client *Client) UpdateAlertV2Prometheus(ctx context.Context, alert AlertV2 return AlertV2Prometheus{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2Prometheus{}, err - } - - wrapper, err := Unmarshal[alertV2PrometheusWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2PrometheusWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2Prometheus{}, err } @@ -161,12 +156,8 @@ func (client *Client) UpdateAlertV2Prometheus(ctx context.Context, alert AlertV2 return wrapper.Alert, nil } -func (client *Client) GetAlertV2Prometheus(ctx context.Context, alertID int) (AlertV2Prometheus, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2Prometheus{}, err - } - wrapper, err := Unmarshal[alertV2PrometheusWrapper](body) +func (c *Client) GetAlertV2PrometheusByID(ctx context.Context, alertID int) (AlertV2Prometheus, error) { + wrapper, err := getAlertV2[alertV2PrometheusWrapper](ctx, c, alertID) if err != nil { return AlertV2Prometheus{}, err } @@ -174,17 +165,17 @@ func (client *Client) GetAlertV2Prometheus(ctx context.Context, alertID int) (Al return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2Prometheus(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2Prometheus(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Event{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Event{}, err } @@ -194,12 +185,7 @@ func (client *Client) CreateAlertV2Event(ctx context.Context, alert AlertV2Event return AlertV2Event{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2Event{}, err - } - - wrapper, err := Unmarshal[alertV2EventWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2EventWrapper](ctx, c, payload) if err != nil { return AlertV2Event{}, err } @@ -207,13 +193,13 @@ func (client *Client) CreateAlertV2Event(ctx context.Context, alert AlertV2Event return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2Event(ctx context.Context, alert AlertV2Event) (AlertV2Event, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Event{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Event{}, err } @@ -223,12 +209,7 @@ func (client *Client) UpdateAlertV2Event(ctx context.Context, alert AlertV2Event return AlertV2Event{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2Event{}, err - } - - wrapper, err := Unmarshal[alertV2EventWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2EventWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2Event{}, err } @@ -236,13 +217,8 @@ func (client *Client) UpdateAlertV2Event(ctx context.Context, alert AlertV2Event return wrapper.Alert, nil } -func (client *Client) GetAlertV2Event(ctx context.Context, alertID int) (AlertV2Event, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2Event{}, err - } - - wrapper, err := Unmarshal[alertV2EventWrapper](body) +func (c *Client) GetAlertV2EventByID(ctx context.Context, alertID int) (AlertV2Event, error) { + wrapper, err := getAlertV2[alertV2EventWrapper](ctx, c, alertID) if err != nil { return AlertV2Event{}, err } @@ -250,17 +226,17 @@ func (client *Client) GetAlertV2Event(ctx context.Context, alertID int) (AlertV2 return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2Event(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2Event(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Metric{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Metric{}, err } @@ -270,12 +246,7 @@ func (client *Client) CreateAlertV2Metric(ctx context.Context, alert AlertV2Metr return AlertV2Metric{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2Metric{}, err - } - - wrapper, err := Unmarshal[alertV2MetricWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2MetricWrapper](ctx, c, payload) if err != nil { return AlertV2Metric{}, err } @@ -283,13 +254,13 @@ func (client *Client) CreateAlertV2Metric(ctx context.Context, alert AlertV2Metr return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2Metric(ctx context.Context, alert AlertV2Metric) (AlertV2Metric, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Metric{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Metric{}, err } @@ -299,12 +270,7 @@ func (client *Client) UpdateAlertV2Metric(ctx context.Context, alert AlertV2Metr return AlertV2Metric{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2Metric{}, err - } - - wrapper, err := Unmarshal[alertV2MetricWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2MetricWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2Metric{}, err } @@ -312,13 +278,8 @@ func (client *Client) UpdateAlertV2Metric(ctx context.Context, alert AlertV2Metr return wrapper.Alert, nil } -func (client *Client) GetAlertV2Metric(ctx context.Context, alertID int) (AlertV2Metric, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2Metric{}, err - } - - wrapper, err := Unmarshal[alertV2MetricWrapper](body) +func (c *Client) GetAlertV2MetricByID(ctx context.Context, alertID int) (AlertV2Metric, error) { + wrapper, err := getAlertV2[alertV2MetricWrapper](ctx, c, alertID) if err != nil { return AlertV2Metric{}, err } @@ -326,17 +287,17 @@ func (client *Client) GetAlertV2Metric(ctx context.Context, alertID int) (AlertV return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2Metric(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2Metric(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Downtime{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Downtime{}, err } @@ -346,12 +307,7 @@ func (client *Client) CreateAlertV2Downtime(ctx context.Context, alert AlertV2Do return AlertV2Downtime{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2Downtime{}, err - } - - wrapper, err := Unmarshal[alertV2DowntimeWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2DowntimeWrapper](ctx, c, payload) if err != nil { return AlertV2Downtime{}, err } @@ -359,13 +315,13 @@ func (client *Client) CreateAlertV2Downtime(ctx context.Context, alert AlertV2Do return wrapper.Alert, err } -func (client *Client) UpdateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2Downtime(ctx context.Context, alert AlertV2Downtime) (AlertV2Downtime, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Downtime{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Downtime{}, err } @@ -375,12 +331,7 @@ func (client *Client) UpdateAlertV2Downtime(ctx context.Context, alert AlertV2Do return AlertV2Downtime{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2Downtime{}, err - } - - wrapper, err := Unmarshal[alertV2DowntimeWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2DowntimeWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2Downtime{}, err } @@ -388,13 +339,8 @@ func (client *Client) UpdateAlertV2Downtime(ctx context.Context, alert AlertV2Do return wrapper.Alert, err } -func (client *Client) GetAlertV2Downtime(ctx context.Context, alertID int) (AlertV2Downtime, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2Downtime{}, err - } - - wrapper, err := Unmarshal[alertV2DowntimeWrapper](body) +func (c *Client) GetAlertV2DowntimeByID(ctx context.Context, alertID int) (AlertV2Downtime, error) { + wrapper, err := getAlertV2[alertV2DowntimeWrapper](ctx, c, alertID) if err != nil { return AlertV2Downtime{}, err } @@ -402,17 +348,17 @@ func (client *Client) GetAlertV2Downtime(ctx context.Context, alertID int) (Aler return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2Downtime(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2Downtime(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Change{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Change{}, err } @@ -422,12 +368,7 @@ func (client *Client) CreateAlertV2Change(ctx context.Context, alert AlertV2Chan return AlertV2Change{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2Change{}, err - } - - wrapper, err := Unmarshal[alertV2ChangeWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2ChangeWrapper](ctx, c, payload) if err != nil { return AlertV2Change{}, err } @@ -435,13 +376,13 @@ func (client *Client) CreateAlertV2Change(ctx context.Context, alert AlertV2Chan return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2Change(ctx context.Context, alert AlertV2Change) (AlertV2Change, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2Change{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2Change{}, err } @@ -451,12 +392,7 @@ func (client *Client) UpdateAlertV2Change(ctx context.Context, alert AlertV2Chan return AlertV2Change{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2Change{}, err - } - - wrapper, err := Unmarshal[alertV2ChangeWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2ChangeWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2Change{}, err } @@ -464,13 +400,8 @@ func (client *Client) UpdateAlertV2Change(ctx context.Context, alert AlertV2Chan return wrapper.Alert, nil } -func (client *Client) GetAlertV2Change(ctx context.Context, alertID int) (AlertV2Change, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2Change{}, err - } - - wrapper, err := Unmarshal[alertV2ChangeWrapper](body) +func (c *Client) GetAlertV2ChangeByID(ctx context.Context, alertID int) (AlertV2Change, error) { + wrapper, err := getAlertV2[alertV2ChangeWrapper](ctx, c, alertID) if err != nil { return AlertV2Change{}, err } @@ -478,17 +409,17 @@ func (client *Client) GetAlertV2Change(ctx context.Context, alertID int) (AlertV return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2Change(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2Change(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2FormBasedPrometheus{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2FormBasedPrometheus{}, err } @@ -498,12 +429,7 @@ func (client *Client) CreateAlertV2FormBasedPrometheus(ctx context.Context, aler return AlertV2FormBasedPrometheus{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2FormBasedPrometheus{}, err - } - - wrapper, err := Unmarshal[alertV2FormBasedPrometheusWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2FormBasedPrometheusWrapper](ctx, c, payload) if err != nil { return AlertV2FormBasedPrometheus{}, err } @@ -511,13 +437,13 @@ func (client *Client) CreateAlertV2FormBasedPrometheus(ctx context.Context, aler return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2FormBasedPrometheus(ctx context.Context, alert AlertV2FormBasedPrometheus) (AlertV2FormBasedPrometheus, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2FormBasedPrometheus{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2FormBasedPrometheus{}, err } @@ -527,12 +453,7 @@ func (client *Client) UpdateAlertV2FormBasedPrometheus(ctx context.Context, aler return AlertV2FormBasedPrometheus{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2FormBasedPrometheus{}, err - } - - wrapper, err := Unmarshal[alertV2FormBasedPrometheusWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2FormBasedPrometheusWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2FormBasedPrometheus{}, err } @@ -540,13 +461,8 @@ func (client *Client) UpdateAlertV2FormBasedPrometheus(ctx context.Context, aler return wrapper.Alert, nil } -func (client *Client) GetAlertV2FormBasedPrometheus(ctx context.Context, alertID int) (AlertV2FormBasedPrometheus, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2FormBasedPrometheus{}, err - } - - wrapper, err := Unmarshal[alertV2FormBasedPrometheusWrapper](body) +func (c *Client) GetAlertV2FormBasedPrometheusByID(ctx context.Context, alertID int) (AlertV2FormBasedPrometheus, error) { + wrapper, err := getAlertV2[alertV2FormBasedPrometheusWrapper](ctx, c, alertID) if err != nil { return AlertV2FormBasedPrometheus{}, err } @@ -554,17 +470,17 @@ func (client *Client) GetAlertV2FormBasedPrometheus(ctx context.Context, alertID return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2FormBasedPrometheus(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2FormBasedPrometheus(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) CreateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) CreateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2GroupOutlier{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2GroupOutlier{}, err } @@ -574,12 +490,7 @@ func (client *Client) CreateAlertV2GroupOutlier(ctx context.Context, alert Alert return AlertV2GroupOutlier{}, err } - body, err := client.createAlertV2(ctx, payload) - if err != nil { - return AlertV2GroupOutlier{}, err - } - - wrapper, err := Unmarshal[alertV2GroupOutlierWrapper](body) + wrapper, err := createAlertV2AndUnmarshal[alertV2GroupOutlierWrapper](ctx, c, payload) if err != nil { return AlertV2GroupOutlier{}, err } @@ -587,13 +498,13 @@ func (client *Client) CreateAlertV2GroupOutlier(ctx context.Context, alert Alert return wrapper.Alert, nil } -func (client *Client) UpdateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) { - err := client.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) +func (c *Client) UpdateAlertV2GroupOutlier(ctx context.Context, alert AlertV2GroupOutlier) (AlertV2GroupOutlier, error) { + err := c.addNotificationChannelType(ctx, alert.NotificationChannelConfigList) if err != nil { return AlertV2GroupOutlier{}, err } - err = client.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) + err = c.translateScopeSegmentLabels(ctx, &alert.Config.ScopedSegmentedConfig) if err != nil { return AlertV2GroupOutlier{}, err } @@ -603,12 +514,7 @@ func (client *Client) UpdateAlertV2GroupOutlier(ctx context.Context, alert Alert return AlertV2GroupOutlier{}, err } - body, err := client.updateAlertV2(ctx, alert.ID, payload) - if err != nil { - return AlertV2GroupOutlier{}, err - } - - wrapper, err := Unmarshal[alertV2GroupOutlierWrapper](body) + wrapper, err := updateAlertV2AndUnmarshal[alertV2GroupOutlierWrapper](ctx, c, alert.ID, payload) if err != nil { return AlertV2GroupOutlier{}, err } @@ -616,13 +522,8 @@ func (client *Client) UpdateAlertV2GroupOutlier(ctx context.Context, alert Alert return wrapper.Alert, nil } -func (client *Client) GetAlertV2GroupOutlier(ctx context.Context, alertID int) (AlertV2GroupOutlier, error) { - body, err := client.getAlertV2(ctx, alertID) - if err != nil { - return AlertV2GroupOutlier{}, err - } - - wrapper, err := Unmarshal[alertV2GroupOutlierWrapper](body) +func (c *Client) GetAlertV2GroupOutlierByID(ctx context.Context, alertID int) (AlertV2GroupOutlier, error) { + wrapper, err := getAlertV2[alertV2GroupOutlierWrapper](ctx, c, alertID) if err != nil { return AlertV2GroupOutlier{}, err } @@ -630,73 +531,94 @@ func (client *Client) GetAlertV2GroupOutlier(ctx context.Context, alertID int) ( return wrapper.Alert, nil } -func (client *Client) DeleteAlertV2GroupOutlier(ctx context.Context, alertID int) error { - return client.deleteAlertV2(ctx, alertID) +func (c *Client) DeleteAlertV2GroupOutlier(ctx context.Context, alertID int) error { + return c.deleteAlertV2(ctx, alertID) } -func (client *Client) createAlertV2(ctx context.Context, alertJson io.Reader) (io.ReadCloser, error) { - response, err := client.requester.Request(ctx, http.MethodPost, client.alertsV2URL(), alertJson) +func createAlertV2AndUnmarshal[T any](ctx context.Context, c *Client, alertJSON io.Reader) (value T, err error) { + var zero T + + response, err := c.requester.Request(ctx, http.MethodPost, c.alertsV2URL(), alertJSON) if err != nil { - return nil, err + return zero, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return zero, c.ErrorFromResponse(response) } - return response.Body, nil + return Unmarshal[T](response.Body) } -func (client *Client) updateAlertV2(ctx context.Context, alertID int, alertJson io.Reader) (io.ReadCloser, error) { - response, err := client.requester.Request(ctx, http.MethodPut, client.alertV2URL(alertID), alertJson) +func updateAlertV2AndUnmarshal[T any](ctx context.Context, c *Client, alertID int, alertJSON io.Reader) (value T, err error) { + var zero T + + response, err := c.requester.Request(ctx, http.MethodPut, c.alertV2URL(alertID), alertJSON) if err != nil { - return nil, err + return zero, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return zero, c.ErrorFromResponse(response) } - return response.Body, nil + return Unmarshal[T](response.Body) } -func (client *Client) deleteAlertV2(ctx context.Context, alertID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.alertV2URL(alertID), nil) +func (c *Client) deleteAlertV2(ctx context.Context, alertID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.alertV2URL(alertID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getAlertV2(ctx context.Context, alertID int) (io.ReadCloser, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.alertV2URL(alertID), nil) +func getAlertV2[T any](ctx context.Context, c *Client, alertID int) (value T, err error) { + var zero T + response, err := c.requester.Request(ctx, http.MethodGet, c.alertV2URL(alertID), nil) if err != nil { - return nil, err + return zero, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode == http.StatusNotFound { - return nil, AlertV2NotFound + return zero, ErrAlertV2NotFound } if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return zero, c.ErrorFromResponse(response) } - return response.Body, nil + return Unmarshal[T](response.Body) } -func (client *Client) addNotificationChannelType(ctx context.Context, notificationChannelConfigList []NotificationChannelConfigV2) error { +func (c *Client) addNotificationChannelType(ctx context.Context, notificationChannelConfigList []NotificationChannelConfigV2) error { // on put/posts the api wants the type of the channel even if it can be inferred for i, n := range notificationChannelConfigList { - nc, err := client.GetNotificationChannelById(ctx, n.ChannelID) + nc, err := c.GetNotificationChannelByID(ctx, n.ChannelID) if err != nil { return fmt.Errorf("error getting info for notification channel %d: %w", n.ChannelID, err) } @@ -705,11 +627,11 @@ func (client *Client) addNotificationChannelType(ctx context.Context, notificati return nil } -func (client *Client) translateScopeSegmentLabels(ctx context.Context, scopedSegmentedConfig *ScopedSegmentedConfig) error { +func (c *Client) translateScopeSegmentLabels(ctx context.Context, scopedSegmentedConfig *ScopedSegmentedConfig) error { // the operand of the scope must be in dot notation if scopedSegmentedConfig.Scope != nil { for i, e := range scopedSegmentedConfig.Scope.Expressions { - labelDescriptorV3, err := client.getLabelDescriptor(ctx, e.Operand) + labelDescriptorV3, err := c.getLabelDescriptor(ctx, e.Operand) if err != nil { return fmt.Errorf("error getting descriptor for label %s: %w", e.Operand, err) } @@ -719,7 +641,7 @@ func (client *Client) translateScopeSegmentLabels(ctx context.Context, scopedSeg // the label descriptor id must be in dot notation for i, d := range scopedSegmentedConfig.SegmentBy { - labelDescriptorV3, err := client.getLabelDescriptor(ctx, d.ID) + labelDescriptorV3, err := c.getLabelDescriptor(ctx, d.ID) if err != nil { return fmt.Errorf("error getting descriptor for label %s: %w", d.ID, err) } @@ -729,7 +651,7 @@ func (client *Client) translateScopeSegmentLabels(ctx context.Context, scopedSeg return nil } -func (client *Client) getLabelDescriptor(ctx context.Context, label string) (LabelDescriptorV3, error) { +func (c *Client) getLabelDescriptor(ctx context.Context, label string) (LabelDescriptorV3, error) { var alertDescriptor LabelDescriptorV3 labelCache.Lock() @@ -737,7 +659,7 @@ func (client *Client) getLabelDescriptor(ctx context.Context, label string) (Lab if len(labelCache.labels) == 0 { log.Printf("[DEBUG] GetLabel for %s: fetching all labels", label) - labelDescriptors, err := client.getLabels(ctx) + labelDescriptors, err := c.getLabels(ctx) if err != nil { return alertDescriptor, err } @@ -754,40 +676,48 @@ func (client *Client) getLabelDescriptor(ctx context.Context, label string) (Lab // if the label did not exist, build the descriptor from /v3/labels/descriptor log.Printf("[DEBUG] GetLabel for %s: not found in existing customer labels", label) - return client.buildLabelDescriptor(ctx, label) + return c.buildLabelDescriptor(ctx, label) } // buildLabelDescriptor gets the descriptor of a label in public notation from the v3/labels/descriptors api // this is not a general solution to get the descriptor for a public notation label since custom labels will not be properly translated -func (client *Client) buildLabelDescriptor(ctx context.Context, label string) (LabelDescriptorV3, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.labelsDescriptorsV3URL(label), nil) +func (c *Client) buildLabelDescriptor(ctx context.Context, label string) (descriptor LabelDescriptorV3, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.labelsDescriptorsV3URL(label), nil) if err != nil { return LabelDescriptorV3{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return LabelDescriptorV3{}, err } - descriptor, err := Unmarshal[labelDescriptorV3](response.Body) + descriptorWrapper, err := Unmarshal[labelDescriptorV3](response.Body) if err != nil { return LabelDescriptorV3{}, err } - return descriptor.LabelDescriptor, nil + return descriptorWrapper.LabelDescriptor, nil } -func (client *Client) getLabels(ctx context.Context) ([]LabelDescriptorV3, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.labelsV3URL(), nil) +func (c *Client) getLabels(ctx context.Context) (labels []LabelDescriptorV3, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.labelsV3URL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } @@ -798,18 +728,18 @@ func (client *Client) getLabels(ctx context.Context) ([]LabelDescriptorV3, error return wrapper.AllLabels, nil } -func (client *Client) alertsV2URL() string { - return fmt.Sprintf(alertsV2Path, client.config.url) +func (c *Client) alertsV2URL() string { + return fmt.Sprintf(alertsV2Path, c.config.url) } -func (client *Client) alertV2URL(alertID int) string { - return fmt.Sprintf(alertV2Path, client.config.url, alertID) +func (c *Client) alertV2URL(alertID int) string { + return fmt.Sprintf(alertV2Path, c.config.url, alertID) } -func (client *Client) labelsV3URL() string { - return fmt.Sprintf(labelsV3Path, client.config.url) +func (c *Client) labelsV3URL() string { + return fmt.Sprintf(labelsV3Path, c.config.url) } -func (client *Client) labelsDescriptorsV3URL(label string) string { - return fmt.Sprintf(labelsV3DescriptorsPath, client.config.url, label) +func (c *Client) labelsDescriptorsV3URL(label string) string { + return fmt.Sprintf(labelsV3DescriptorsPath, c.config.url, label) } diff --git a/sysdig/internal/client/v2/client.go b/sysdig/internal/client/v2/client.go index 1971c37a9..7730bc943 100644 --- a/sysdig/internal/client/v2/client.go +++ b/sysdig/internal/client/v2/client.go @@ -73,8 +73,8 @@ type Client struct { requester Requester } -func (client *Client) ErrorFromResponse(response *http.Response) error { - var data interface{} +func (c *Client) ErrorFromResponse(response *http.Response) error { + var data any err := json.NewDecoder(response.Body).Decode(&data) if err != nil { return errors.New(response.Status) @@ -85,7 +85,7 @@ func (client *Client) ErrorFromResponse(response *http.Response) error { return errors.New(response.Status) } - if searchArray, ok := search.([]interface{}); ok { + if searchArray, ok := search.([]any); ok { return errors.New(strings.Join(cast.ToStringSlice(searchArray), ", ")) } @@ -97,7 +97,7 @@ func (client *Client) ErrorFromResponse(response *http.Response) error { return errors.New(response.Status) } -func Unmarshal[T any](data io.ReadCloser) (T, error) { +func Unmarshal[T any](data io.Reader) (T, error) { var result T body, err := io.ReadAll(data) @@ -143,7 +143,7 @@ func request(httpClient *http.Client, cfg *config, request *http.Request) (*http return response, err } -func getMe(ctx context.Context, cfg *config, httpClient *http.Client, headers map[string]string) (*User, error) { +func getMe(ctx context.Context, cfg *config, httpClient *http.Client, headers map[string]string) (user *User, err error) { r, err := http.NewRequest( http.MethodGet, fmt.Sprintf("%s%s", cfg.url, GetMePath), @@ -162,7 +162,11 @@ func getMe(ctx context.Context, cfg *config, httpClient *http.Client, headers ma if err != nil { return nil, err } - defer resp.Body.Close() + defer func() { + if dErr := resp.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() wrapper, err := Unmarshal[userWrapper](resp.Body) if err != nil { @@ -172,8 +176,8 @@ func getMe(ctx context.Context, cfg *config, httpClient *http.Client, headers ma return &wrapper.User, nil } -func (client *Client) CurrentTeamID(ctx context.Context) (int, error) { - return client.requester.CurrentTeamID(ctx) +func (c *Client) CurrentTeamID(ctx context.Context) (int, error) { + return c.requester.CurrentTeamID(ctx) } func newHTTPClient(cfg *config) *http.Client { diff --git a/sysdig/internal/client/v2/client_test.go b/sysdig/internal/client/v2/client_test.go index d03e09863..2f2296e5b 100644 --- a/sysdig/internal/client/v2/client_test.go +++ b/sysdig/internal/client/v2/client_test.go @@ -1,5 +1,3 @@ -//go:build unit - package v2 import ( diff --git a/sysdig/internal/client/v2/cloud_account.go b/sysdig/internal/client/v2/cloud_account.go index ebd7d30e0..63f02f238 100644 --- a/sysdig/internal/client/v2/cloud_account.go +++ b/sysdig/internal/client/v2/cloud_account.go @@ -20,7 +20,7 @@ const ( type CloudAccountSecureInterface interface { Base CreateCloudAccountSecure(ctx context.Context, cloudAccount *CloudAccountSecure) (*CloudAccountSecure, error) - GetCloudAccountSecure(ctx context.Context, accountID string) (*CloudAccountSecure, error) + GetCloudAccountSecureByID(ctx context.Context, accountID string) (*CloudAccountSecure, error) DeleteCloudAccountSecure(ctx context.Context, accountID string) error UpdateCloudAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudAccountSecure) (*CloudAccountSecure, error) } @@ -31,106 +31,112 @@ type CloudAccountMonitorInterface interface { CreateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountMonitorForCost) (*CloudAccountCreatedForCost, error) UpdateCloudAccountMonitor(ctx context.Context, id int, provider *CloudAccountMonitor) (*CloudAccountMonitor, error) UpdateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountCostProvider) (*CloudAccountCostProvider, error) - GetCloudAccountMonitor(ctx context.Context, id int) (*CloudAccountMonitor, error) - GetCloudAccountMonitorForCost(ctx context.Context, id int) (*CloudAccountCostProvider, error) + GetCloudAccountMonitorByID(ctx context.Context, id int) (*CloudAccountMonitor, error) + GetCloudAccountMonitorForCostByID(ctx context.Context, id int) (*CloudAccountCostProvider, error) DeleteCloudAccountMonitor(ctx context.Context, id int) error } -func (client *Client) CreateCloudAccountSecure(ctx context.Context, cloudAccount *CloudAccountSecure) (*CloudAccountSecure, error) { +func (c *Client) CreateCloudAccountSecure(ctx context.Context, cloudAccount *CloudAccountSecure) (createdAccount *CloudAccountSecure, err error) { payload, err := Marshal(cloudAccount) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.cloudAccountsURL(true), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.cloudAccountsURL(true), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } return Unmarshal[*CloudAccountSecure](response.Body) } -func (client *Client) GetCloudAccountSecure(ctx context.Context, accountID string) (*CloudAccountSecure, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.cloudAccountURL(accountID, true), nil) +func (c *Client) GetCloudAccountSecureByID(ctx context.Context, accountID string) (cloudAccount *CloudAccountSecure, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.cloudAccountURL(accountID, true), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*CloudAccountSecure](response.Body) } -func (client *Client) DeleteCloudAccountSecure(ctx context.Context, accountID string) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.cloudAccountURL(accountID, false), nil) +func (c *Client) DeleteCloudAccountSecure(ctx context.Context, accountID string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.cloudAccountURL(accountID, false), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) UpdateCloudAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudAccountSecure) (*CloudAccountSecure, error) { +func (c *Client) UpdateCloudAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudAccountSecure) (updatedAccount *CloudAccountSecure, err error) { payload, err := Marshal(cloudAccount) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.cloudAccountURL(accountID, true), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.cloudAccountURL(accountID, true), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } return Unmarshal[*CloudAccountSecure](response.Body) } -func (client *Client) cloudAccountsURL(includeExternalID bool) string { - if includeExternalID { - return fmt.Sprintf(cloudAccountsWithExternalIDPath, client.config.url) - } - return fmt.Sprintf(cloudAccountsPath, client.config.url) -} - -func (client *Client) cloudAccountURL(accountID string, includeExternalID bool) string { - if includeExternalID { - return fmt.Sprintf(cloudAccountWithExternalIDPath, client.config.url, accountID) - } - return fmt.Sprintf(cloudAccountPath, client.config.url, accountID) -} - -func (client *Client) CreateCloudAccountMonitor(ctx context.Context, provider *CloudAccountMonitor) (*CloudAccountMonitor, error) { +func (c *Client) CreateCloudAccountMonitor(ctx context.Context, provider *CloudAccountMonitor) (createdProvider *CloudAccountMonitor, err error) { payload, err := Marshal(provider) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getProvidersURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getProvidersURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[cloudAccountWrapperMonitor](response.Body) @@ -141,20 +147,24 @@ func (client *Client) CreateCloudAccountMonitor(ctx context.Context, provider *C return &wrapper.CloudAccount, nil } -func (client *Client) CreateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountMonitorForCost) (*CloudAccountCreatedForCost, error) { +func (c *Client) CreateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountMonitorForCost) (createdProvider *CloudAccountCreatedForCost, err error) { payload, err := Marshal(provider) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getCostProvidersURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getCostProvidersURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[CloudAccountCreatedForCost](response.Body) @@ -165,20 +175,24 @@ func (client *Client) CreateCloudAccountMonitorForCost(ctx context.Context, prov return &wrapper, nil } -func (client *Client) UpdateCloudAccountMonitor(ctx context.Context, id int, provider *CloudAccountMonitor) (*CloudAccountMonitor, error) { +func (c *Client) UpdateCloudAccountMonitor(ctx context.Context, id int, provider *CloudAccountMonitor) (updatedProvider *CloudAccountMonitor, err error) { payload, err := Marshal(provider) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getProviderURL(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getProviderURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[cloudAccountWrapperMonitor](response.Body) @@ -189,20 +203,24 @@ func (client *Client) UpdateCloudAccountMonitor(ctx context.Context, id int, pro return &wrapper.CloudAccount, nil } -func (client *Client) UpdateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountCostProvider) (*CloudAccountCostProvider, error) { +func (c *Client) UpdateCloudAccountMonitorForCost(ctx context.Context, provider *CloudAccountCostProvider) (updatedProvider *CloudAccountCostProvider, err error) { payload, err := Marshal(provider) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getUpdateCostProviderURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getUpdateCostProviderURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[CloudAccountCostProviderWrapper](response.Body) @@ -213,15 +231,19 @@ func (client *Client) UpdateCloudAccountMonitorForCost(ctx context.Context, prov return &wrapper.CloudAccountCostProvider, nil } -func (client *Client) GetCloudAccountMonitor(ctx context.Context, id int) (*CloudAccountMonitor, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getProviderURL(id), nil) +func (c *Client) GetCloudAccountMonitorByID(ctx context.Context, id int) (account *CloudAccountMonitor, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getProviderURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[cloudAccountWrapperMonitor](response.Body) @@ -232,15 +254,19 @@ func (client *Client) GetCloudAccountMonitor(ctx context.Context, id int) (*Clou return &wrapper.CloudAccount, nil } -func (client *Client) GetCloudAccountMonitorForCost(ctx context.Context, id int) (*CloudAccountCostProvider, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getCostProviderURL(id), nil) +func (c *Client) GetCloudAccountMonitorForCostByID(ctx context.Context, id int) (provider *CloudAccountCostProvider, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getCostProviderURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[CloudAccountCostProviderWrapper](response.Body) @@ -251,36 +277,54 @@ func (client *Client) GetCloudAccountMonitorForCost(ctx context.Context, id int) return &wrapper.CloudAccountCostProvider, nil } -func (client *Client) DeleteCloudAccountMonitor(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getProviderURL(id), nil) +func (c *Client) DeleteCloudAccountMonitor(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getProviderURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getProviderURL(id int) string { - return fmt.Sprintf("%v/%v", client.getProvidersURL(), id) +func (c *Client) cloudAccountsURL(includeExternalID bool) string { + if includeExternalID { + return fmt.Sprintf(cloudAccountsWithExternalIDPath, c.config.url) + } + return fmt.Sprintf(cloudAccountsPath, c.config.url) +} + +func (c *Client) cloudAccountURL(accountID string, includeExternalID bool) string { + if includeExternalID { + return fmt.Sprintf(cloudAccountWithExternalIDPath, c.config.url, accountID) + } + return fmt.Sprintf(cloudAccountPath, c.config.url, accountID) +} + +func (c *Client) getProviderURL(id int) string { + return fmt.Sprintf("%v/%v", c.getProvidersURL(), id) } -func (client *Client) getProvidersURL() string { - return fmt.Sprintf(providersPath, client.config.url) +func (c *Client) getProvidersURL() string { + return fmt.Sprintf(providersPath, c.config.url) } -func (client *Client) getCostProvidersURL() string { - return fmt.Sprintf(costCloudAccountPath, client.config.url) +func (c *Client) getCostProvidersURL() string { + return fmt.Sprintf(costCloudAccountPath, c.config.url) } -func (client *Client) getCostProviderURL(id int) string { - return fmt.Sprintf(costProviderURL, client.config.url, id) +func (c *Client) getCostProviderURL(id int) string { + return fmt.Sprintf(costProviderURL, c.config.url, id) } -func (client *Client) getUpdateCostProviderURL() string { - return fmt.Sprintf(updateCostProviderURL, client.config.url) +func (c *Client) getUpdateCostProviderURL() string { + return fmt.Sprintf(updateCostProviderURL, c.config.url) } diff --git a/sysdig/internal/client/v2/cloudauth.go b/sysdig/internal/client/v2/cloudauth.go index a2043a2c0..8214f0e19 100644 --- a/sysdig/internal/client/v2/cloudauth.go +++ b/sysdig/internal/client/v2/cloudauth.go @@ -21,115 +21,130 @@ const ( type CloudauthAccountSecureInterface interface { Base CreateCloudauthAccountSecure(ctx context.Context, cloudAccount *CloudauthAccountSecure) (*CloudauthAccountSecure, string, error) - GetCloudauthAccountSecure(ctx context.Context, accountID string) (*CloudauthAccountSecure, string, error) + GetCloudauthAccountSecureByID(ctx context.Context, accountID string) (*CloudauthAccountSecure, string, error) DeleteCloudauthAccountSecure(ctx context.Context, accountID string) (string, error) UpdateCloudauthAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudauthAccountSecure) (*CloudauthAccountSecure, string, error) } -func (client *Client) CreateCloudauthAccountSecure(ctx context.Context, cloudAccount *CloudauthAccountSecure) (*CloudauthAccountSecure, string, error) { - payload, err := client.marshalCloudauthProto(cloudAccount) +func (c *Client) CreateCloudauthAccountSecure(ctx context.Context, cloudAccount *CloudauthAccountSecure) (account *CloudauthAccountSecure, errStatus string, err error) { + payload, err := c.marshalCloudauthProto(cloudAccount) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPost, client.cloudauthAccountsURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.cloudauthAccountsURL(), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccount := &CloudauthAccountSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccount) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccount) if err != nil { return nil, "", err } return cloudauthAccount, "", nil } -func (client *Client) GetCloudauthAccountSecure(ctx context.Context, accountID string) (*CloudauthAccountSecure, string, error) { +func (c *Client) GetCloudauthAccountSecureByID(ctx context.Context, accountID string) (account *CloudauthAccountSecure, errStatus string, err error) { // get the cloud account with decrypt query param true to fetch decrypted details on the cloud account - response, err := client.requester.Request(ctx, http.MethodGet, client.getCloudauthAccountURL(accountID, "true"), nil) + response, err := c.requester.Request(ctx, http.MethodGet, c.getCloudauthAccountURL(accountID, "true"), nil) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccount := &CloudauthAccountSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccount) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccount) if err != nil { return nil, "", err } return cloudauthAccount, "", nil } -func (client *Client) DeleteCloudauthAccountSecure(ctx context.Context, accountID string) (string, error) { - response, err := client.requester.Request(ctx, http.MethodDelete, client.cloudauthAccountURL(accountID), nil) +func (c *Client) DeleteCloudauthAccountSecure(ctx context.Context, accountID string) (errStatus string, err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.cloudauthAccountURL(accountID), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorAndStatusFromResponse(response) + return c.ErrorAndStatusFromResponse(response) } return "", nil } -func (client *Client) UpdateCloudauthAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudauthAccountSecure) ( - *CloudauthAccountSecure, string, error) { - payload, err := client.marshalCloudauthProto(cloudAccount) +func (c *Client) UpdateCloudauthAccountSecure(ctx context.Context, accountID string, cloudAccount *CloudauthAccountSecure) (account *CloudauthAccountSecure, errString string, err error) { + payload, err := c.marshalCloudauthProto(cloudAccount) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPut, client.cloudauthAccountURL(accountID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.cloudauthAccountURL(accountID), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccount := &CloudauthAccountSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccount) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccount) if err != nil { return nil, "", err } return cloudauthAccount, "", nil } -func (client *Client) cloudauthAccountsURL() string { - return fmt.Sprintf(cloudauthAccountsPath, client.config.url) +func (c *Client) cloudauthAccountsURL() string { + return fmt.Sprintf(cloudauthAccountsPath, c.config.url) } -func (client *Client) cloudauthAccountURL(accountID string) string { - return fmt.Sprintf(cloudauthAccountPath, client.config.url, accountID) +func (c *Client) cloudauthAccountURL(accountID string) string { + return fmt.Sprintf(cloudauthAccountPath, c.config.url, accountID) } -func (client *Client) getCloudauthAccountURL(accountID string, decrypt string) string { - return fmt.Sprintf(getCloudauthAccountPath, client.config.url, accountID, decrypt) +func (c *Client) getCloudauthAccountURL(accountID string, decrypt string) string { + return fmt.Sprintf(getCloudauthAccountPath, c.config.url, accountID, decrypt) } // common func for protojson based marshal/unmarshal of any cloudauth proto -func (client *Client) marshalCloudauthProto(message proto.Message) (io.Reader, error) { +func (c *Client) marshalCloudauthProto(message proto.Message) (io.Reader, error) { payload, err := protojson.Marshal(message) return bytes.NewBuffer(payload), err } -func (client *Client) unmarshalCloudauthProto(data io.ReadCloser, message proto.Message) error { +func (c *Client) unmarshalCloudauthProto(data io.ReadCloser, message proto.Message) error { body, err := io.ReadAll(data) if err != nil { return err @@ -139,7 +154,7 @@ func (client *Client) unmarshalCloudauthProto(data io.ReadCloser, message proto. return err } -func (client *Client) ErrorAndStatusFromResponse(response *http.Response) (string, error) { +func (c *Client) ErrorAndStatusFromResponse(response *http.Response) (string, error) { b, err := io.ReadAll(response.Body) if err != nil { return response.Status, err diff --git a/sysdig/internal/client/v2/cloudauth/go/cloud_account.pb.go b/sysdig/internal/client/v2/cloudauth/go/cloud_account.pb.go index 18c7e119a..a29af19ab 100644 --- a/sysdig/internal/client/v2/cloudauth/go/cloud_account.pb.go +++ b/sysdig/internal/client/v2/cloudauth/go/cloud_account.pb.go @@ -5530,4 +5530,4 @@ func file_cloud_account_proto_init() { file_cloud_account_proto_rawDesc = nil file_cloud_account_proto_goTypes = nil file_cloud_account_proto_depIdxs = nil -} \ No newline at end of file +} diff --git a/sysdig/internal/client/v2/cloudauth_account_component.go b/sysdig/internal/client/v2/cloudauth_account_component.go index e34cddc19..3d59eaead 100644 --- a/sysdig/internal/client/v2/cloudauth_account_component.go +++ b/sysdig/internal/client/v2/cloudauth_account_component.go @@ -7,8 +7,8 @@ import ( ) const ( - cloudauthAccountComponentsPath = "%s/api/cloudauth/v1/accounts/%s/components" // POST - cloudauthAccountComponentPath = "%s/api/cloudauth/v1/accounts/%s/components/%s/%s" // GET, PUT, DEL + cloudauthAccountComponentsPath = "%s/api/cloudauth/v1/accounts/%s/components" + cloudauthAccountComponentPath = "%s/api/cloudauth/v1/accounts/%s/components/%s/%s" ) type CloudauthAccountComponentSecureInterface interface { @@ -19,94 +19,109 @@ type CloudauthAccountComponentSecureInterface interface { UpdateCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string, cloudAccountComponent *CloudauthAccountComponentSecure) (*CloudauthAccountComponentSecure, string, error) } -func (client *Client) CreateCloudauthAccountComponentSecure(ctx context.Context, accountID string, cloudAccountComponent *CloudauthAccountComponentSecure) (*CloudauthAccountComponentSecure, string, error) { - payload, err := client.marshalCloudauthProto(cloudAccountComponent) +func (c *Client) CreateCloudauthAccountComponentSecure(ctx context.Context, accountID string, cloudAccountComponent *CloudauthAccountComponentSecure) (component *CloudauthAccountComponentSecure, errString string, err error) { + payload, err := c.marshalCloudauthProto(cloudAccountComponent) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPost, client.cloudauthAccountComponentsURL(accountID), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.cloudauthAccountComponentsURL(accountID), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccountComponent := &CloudauthAccountComponentSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) if err != nil { return nil, "", err } return cloudauthAccountComponent, "", nil } -func (client *Client) GetCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string) (*CloudauthAccountComponentSecure, string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.cloudauthAccountComponentURL(accountID, componentType, componentInstance), nil) +func (c *Client) GetCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string) (component *CloudauthAccountComponentSecure, errString string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.cloudauthAccountComponentURL(accountID, componentType, componentInstance), nil) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccountComponent := &CloudauthAccountComponentSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) if err != nil { return nil, "", err } return cloudauthAccountComponent, "", nil } -func (client *Client) DeleteCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string) (string, error) { - response, err := client.requester.Request(ctx, http.MethodDelete, client.cloudauthAccountComponentURL(accountID, componentType, componentInstance), nil) +func (c *Client) DeleteCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string) (errString string, err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.cloudauthAccountComponentURL(accountID, componentType, componentInstance), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorAndStatusFromResponse(response) + return c.ErrorAndStatusFromResponse(response) } return "", nil } -func (client *Client) UpdateCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string, cloudAccountComponent *CloudauthAccountComponentSecure) ( - *CloudauthAccountComponentSecure, string, error) { - payload, err := client.marshalCloudauthProto(cloudAccountComponent) +func (c *Client) UpdateCloudauthAccountComponentSecure(ctx context.Context, accountID, componentType, componentInstance string, cloudAccountComponent *CloudauthAccountComponentSecure) (component *CloudauthAccountComponentSecure, errString string, err error) { + payload, err := c.marshalCloudauthProto(cloudAccountComponent) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPut, client.cloudauthAccountComponentURL(accountID, componentType, componentInstance), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.cloudauthAccountComponentURL(accountID, componentType, componentInstance), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccountComponent := &CloudauthAccountComponentSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccountComponent) if err != nil { return nil, "", err } return cloudauthAccountComponent, "", nil } -func (client *Client) cloudauthAccountComponentsURL(accountID string) string { - return fmt.Sprintf(cloudauthAccountComponentsPath, client.config.url, accountID) +func (c *Client) cloudauthAccountComponentsURL(accountID string) string { + return fmt.Sprintf(cloudauthAccountComponentsPath, c.config.url, accountID) } -func (client *Client) cloudauthAccountComponentURL(accountID string, componentType string, componentInstance string) string { - return fmt.Sprintf(cloudauthAccountComponentPath, client.config.url, accountID, componentType, componentInstance) +func (c *Client) cloudauthAccountComponentURL(accountID string, componentType string, componentInstance string) string { + return fmt.Sprintf(cloudauthAccountComponentPath, c.config.url, accountID, componentType, componentInstance) } diff --git a/sysdig/internal/client/v2/cloudauth_account_feature.go b/sysdig/internal/client/v2/cloudauth_account_feature.go index b6d00cc98..6734f41a5 100644 --- a/sysdig/internal/client/v2/cloudauth_account_feature.go +++ b/sysdig/internal/client/v2/cloudauth_account_feature.go @@ -7,7 +7,7 @@ import ( ) const ( - cloudauthAccountFeaturePath = "%s/api/cloudauth/v1/accounts/%s/feature/%s" // GET, PUT, DEL + cloudauthAccountFeaturePath = "%s/api/cloudauth/v1/accounts/%s/feature/%s" ) type CloudauthAccountFeatureSecureInterface interface { @@ -17,66 +17,76 @@ type CloudauthAccountFeatureSecureInterface interface { DeleteCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string) (string, error) } -// both create and update makes a PUT call to backend -func (client *Client) CreateOrUpdateCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string, cloudAccountFeature *CloudauthAccountFeatureSecure) ( - *CloudauthAccountFeatureSecure, string, error) { - payload, err := client.marshalCloudauthProto(cloudAccountFeature) +func (c *Client) CreateOrUpdateCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string, cloudAccountFeature *CloudauthAccountFeatureSecure) (feature *CloudauthAccountFeatureSecure, statusCode string, err error) { + payload, err := c.marshalCloudauthProto(cloudAccountFeature) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPut, client.cloudauthAccountFeatureURL(accountID, featureType), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.cloudauthAccountFeatureURL(accountID, featureType), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccountFeature := &CloudauthAccountFeatureSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccountFeature) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccountFeature) if err != nil { return nil, "", err } return cloudauthAccountFeature, "", nil } -func (client *Client) GetCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string) (*CloudauthAccountFeatureSecure, string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.cloudauthAccountFeatureURL(accountID, featureType), nil) +func (c *Client) GetCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string) (feature *CloudauthAccountFeatureSecure, statusCode string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.cloudauthAccountFeatureURL(accountID, featureType), nil) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } cloudauthAccountFeature := &CloudauthAccountFeatureSecure{} - err = client.unmarshalCloudauthProto(response.Body, cloudauthAccountFeature) + err = c.unmarshalCloudauthProto(response.Body, cloudauthAccountFeature) if err != nil { return nil, "", err } return cloudauthAccountFeature, "", nil } -func (client *Client) DeleteCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string) (string, error) { - response, err := client.requester.Request(ctx, http.MethodDelete, client.cloudauthAccountFeatureURL(accountID, featureType), nil) +func (c *Client) DeleteCloudauthAccountFeatureSecure(ctx context.Context, accountID, featureType string) (statusCode string, err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.cloudauthAccountFeatureURL(accountID, featureType), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorAndStatusFromResponse(response) + return c.ErrorAndStatusFromResponse(response) } return "", nil } -func (client *Client) cloudauthAccountFeatureURL(accountID string, featureType string) string { - return fmt.Sprintf(cloudauthAccountFeaturePath, client.config.url, accountID, featureType) +func (c *Client) cloudauthAccountFeatureURL(accountID string, featureType string) string { + return fmt.Sprintf(cloudauthAccountFeaturePath, c.config.url, accountID, featureType) } diff --git a/sysdig/internal/client/v2/cloudauth_test.go b/sysdig/internal/client/v2/cloudauth_test.go index 8ef57362b..bfa39a4d4 100644 --- a/sysdig/internal/client/v2/cloudauth_test.go +++ b/sysdig/internal/client/v2/cloudauth_test.go @@ -1,5 +1,3 @@ -//go:build unit - package v2 import ( @@ -34,7 +32,7 @@ func TestMarshalProto(t *testing.T) { } marshaled := buf.String() - if strings.Replace(marshaled, " ", "", -1) != strings.Replace(expected, " ", "", -1) { + if strings.ReplaceAll(marshaled, " ", "") != strings.ReplaceAll(expected, " ", "") { t.Errorf("expected %v, got %v", expected, marshaled) } } diff --git a/sysdig/internal/client/v2/composite_policies.go b/sysdig/internal/client/v2/composite_policies.go index 993da8b9b..a1beed354 100644 --- a/sysdig/internal/client/v2/composite_policies.go +++ b/sysdig/internal/client/v2/composite_policies.go @@ -10,16 +10,19 @@ import ( ) const ( - skipPolicyV2MsgFlag = "skipPolicyV2Msg" - CreateCompositePolicyPath = "%s/api/v2/policies/batch?%s=%t" - DeleteCompositePolicyPath = "%s/api/v2/policies/batch/%d?%s=%t" - UpdateCompositePolicyPath = "%s/api/v2/policies/batch/%d" + skipPolicyV2MsgFlag = "skipPolicyV2Msg" + getPoliciesLimit = 1000 // TODO: What is a good limit? +) + +const ( + createCompositePolicyPath = "%s/api/v2/policies/batch?%s=%t" + deleteCompositePolicyPath = "%s/api/v2/policies/batch/%d?%s=%t" + updateCompositePolicyPath = "%s/api/v2/policies/batch/%d" - GetCompositePolicyPath = "%s/api/v2/policies/%d" // TODO: Add skip query param - GetCompositePoliciesPath = "%s/api/v2/policies?%s" // TODO: Implement pagination otherwise up to getPoliciesLimit number of policies will be returned + getCompositePolicyPath = "%s/api/v2/policies/%d" // TODO: Add skip query param + getCompositePoliciesPath = "%s/api/v2/policies?%s" // TODO: Implement pagination otherwise up to getPoliciesLimit number of policies will be returned - GetCompositePolicyRulesPath = "%s/api/policies/v3/rules/groups?%s" - getPoliciesLimit = 1000 // TODO: What is a good limit? + getCompositePolicyRulesPath = "%s/api/policies/v3/rules/groups?%s" ) type CompositePolicyInterface interface { @@ -28,70 +31,86 @@ type CompositePolicyInterface interface { DeleteCompositePolicy(ctx context.Context, policyID int) error UpdateCompositePolicy(ctx context.Context, policy PolicyRulesComposite) (PolicyRulesComposite, error) GetCompositePolicyByID(ctx context.Context, policyID int) (PolicyRulesComposite, int, error) - FilterCompositePoliciesByNameAndType(ctx context.Context, policyType string, policyName string) ([]PolicyRulesComposite, int, error) + ListCompositePoliciesByNameAndType(ctx context.Context, policyType string, policyName string) ([]PolicyRulesComposite, int, error) } -func (client *Client) CreateCompositePolicy(ctx context.Context, policy PolicyRulesComposite) (PolicyRulesComposite, error) { +func (c *Client) CreateCompositePolicy(ctx context.Context, policy PolicyRulesComposite) (policyComposite PolicyRulesComposite, err error) { payload, err := Marshal(policy) if err != nil { return PolicyRulesComposite{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateCompositePolicyURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createCompositePolicyURL(), payload) if err != nil { return PolicyRulesComposite{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return PolicyRulesComposite{}, client.ErrorFromResponse(response) + return PolicyRulesComposite{}, c.ErrorFromResponse(response) } return Unmarshal[PolicyRulesComposite](response.Body) } -func (client *Client) UpdateCompositePolicy(ctx context.Context, policy PolicyRulesComposite) (PolicyRulesComposite, error) { +func (c *Client) UpdateCompositePolicy(ctx context.Context, policy PolicyRulesComposite) (policyComposite PolicyRulesComposite, err error) { payload, err := Marshal(policy) if err != nil { return PolicyRulesComposite{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateCompositePolicyURL(policy.Policy.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateCompositePolicyURL(policy.Policy.ID), payload) if err != nil { return PolicyRulesComposite{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return PolicyRulesComposite{}, client.ErrorFromResponse(response) + return PolicyRulesComposite{}, c.ErrorFromResponse(response) } return Unmarshal[PolicyRulesComposite](response.Body) } -func (client *Client) DeleteCompositePolicy(ctx context.Context, policyID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteCompositePolicyURL(policyID), nil) +func (c *Client) DeleteCompositePolicy(ctx context.Context, policyID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteCompositePolicyURL(policyID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) GetCompositePolicyByID(ctx context.Context, policyID int) (PolicyRulesComposite, int, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCompositePolicyURL(policyID), nil) +func (c *Client) GetCompositePolicyByID(ctx context.Context, policyID int) (policyComposite PolicyRulesComposite, statusCode int, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getCompositePolicyURL(policyID), nil) if err != nil { return PolicyRulesComposite{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return PolicyRulesComposite{}, response.StatusCode, client.ErrorFromResponse(response) + return PolicyRulesComposite{}, response.StatusCode, c.ErrorFromResponse(response) } policy, err := Unmarshal[Policy](response.Body) @@ -104,7 +123,7 @@ func (client *Client) GetCompositePolicyByID(ctx context.Context, policyID int) names = append(names, rule.Name) } - rules, _, err := client.GetCompositePolicyRulesByName(ctx, names) + rules, _, err := c.getCompositePolicyRulesByName(ctx, names) if err != nil { return PolicyRulesComposite{}, 0, err } @@ -115,19 +134,23 @@ func (client *Client) GetCompositePolicyByID(ctx context.Context, policyID int) }, http.StatusOK, nil } -func (client *Client) GetCompositePolicyRulesByName(ctx context.Context, names []string) ([]*RuntimePolicyRule, int, error) { +func (c *Client) getCompositePolicyRulesByName(ctx context.Context, names []string) (policies []*RuntimePolicyRule, statusCode int, err error) { if len(names) == 0 { - return nil, http.StatusOK, errors.New("Please provide at least one rule name") + return nil, http.StatusOK, errors.New("please provide at least one rule name") } - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCompositePolicyRulesURL(names), nil) + response, err := c.requester.Request(ctx, http.MethodGet, c.getCompositePolicyRulesURL(names), nil) if err != nil { return []*RuntimePolicyRule{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []*RuntimePolicyRule{}, response.StatusCode, client.ErrorFromResponse(response) + return []*RuntimePolicyRule{}, response.StatusCode, c.ErrorFromResponse(response) } unmarshalled, err := Unmarshal[[][]*RuntimePolicyRule](response.Body) @@ -141,25 +164,29 @@ func (client *Client) GetCompositePolicyRulesByName(ctx context.Context, names [ } if len(rules) == 0 { - return nil, http.StatusOK, errors.New("Rules not found") + return nil, http.StatusOK, errors.New("rules not found") } return rules, http.StatusOK, nil } -// This method is used in a data source to retrieve a policy by name and type. +// ListCompositePoliciesByNameAndType is used in a data source to retrieve a policy by name and type. // We must retrieve and iterate over all policies, as there is no endpoint to get a policy by name. -func (client *Client) FilterCompositePoliciesByNameAndType(ctx context.Context, policyType string, policyName string) ([]PolicyRulesComposite, int, error) { +func (c *Client) ListCompositePoliciesByNameAndType(ctx context.Context, policyType string, policyName string) (list []PolicyRulesComposite, statusCode int, err error) { // TODO: Implement pagination in order to get all policies? - q := GetPoliciesQueryParams{policyType, policyName, getPoliciesLimit} - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCompositePoliciesURL(q), nil) + q := getPoliciesQueryParams{policyType, policyName, getPoliciesLimit} + response, err := c.requester.Request(ctx, http.MethodGet, c.getCompositePoliciesURL(q), nil) if err != nil { return []PolicyRulesComposite{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []PolicyRulesComposite{}, response.StatusCode, client.ErrorFromResponse(response) + return []PolicyRulesComposite{}, response.StatusCode, c.ErrorFromResponse(response) } policies, err := Unmarshal[[]Policy](response.Body) // TODO @@ -187,13 +214,13 @@ func (client *Client) FilterCompositePoliciesByNameAndType(ctx context.Context, } } - rules, _, err := client.GetCompositePolicyRulesByName(ctx, names) + rules, _, err := c.getCompositePolicyRulesByName(ctx, names) if err != nil { return []PolicyRulesComposite{}, 0, err } if len(rules) != len(names) { - return []PolicyRulesComposite{}, 0, fmt.Errorf("Some rules were not found: %d != %d", len(rules), len(names)) + return []PolicyRulesComposite{}, 0, fmt.Errorf("some rules were not found: %d != %d", len(rules), len(names)) } for _, rule := range rules { @@ -211,40 +238,40 @@ func (client *Client) FilterCompositePoliciesByNameAndType(ctx context.Context, return policiesFull, http.StatusOK, nil } -func (client *Client) CreateCompositePolicyURL() string { - return fmt.Sprintf(CreateCompositePolicyPath, client.config.url, skipPolicyV2MsgFlag, client.config.secureSkipPolicyV2Msg) +func (c *Client) createCompositePolicyURL() string { + return fmt.Sprintf(createCompositePolicyPath, c.config.url, skipPolicyV2MsgFlag, c.config.secureSkipPolicyV2Msg) } -func (client *Client) DeleteCompositePolicyURL(policyID int) string { - return fmt.Sprintf(DeleteCompositePolicyPath, client.config.url, policyID, skipPolicyV2MsgFlag, client.config.secureSkipPolicyV2Msg) +func (c *Client) deleteCompositePolicyURL(policyID int) string { + return fmt.Sprintf(deleteCompositePolicyPath, c.config.url, policyID, skipPolicyV2MsgFlag, c.config.secureSkipPolicyV2Msg) } -func (client *Client) UpdateCompositePolicyURL(policyID int) string { - return fmt.Sprintf(UpdateCompositePolicyPath, client.config.url, policyID) +func (c *Client) updateCompositePolicyURL(policyID int) string { + return fmt.Sprintf(updateCompositePolicyPath, c.config.url, policyID) } -func (client *Client) GetCompositePolicyURL(policyID int) string { - return fmt.Sprintf(GetCompositePolicyPath, client.config.url, policyID) +func (c *Client) getCompositePolicyURL(policyID int) string { + return fmt.Sprintf(getCompositePolicyPath, c.config.url, policyID) } -func (client *Client) GetCompositePoliciesURL(queryParams GetPoliciesQueryParams) string { - return fmt.Sprintf(GetCompositePoliciesPath, client.config.url, queryParams.Encode()) +func (c *Client) getCompositePoliciesURL(queryParams getPoliciesQueryParams) string { + return fmt.Sprintf(getCompositePoliciesPath, c.config.url, queryParams.Encode()) } -func (client *Client) GetCompositePolicyRulesURL(names []string) string { +func (c *Client) getCompositePolicyRulesURL(names []string) string { items := []string{} for _, name := range names { items = append(items, fmt.Sprintf("names=%s", name)) } - return fmt.Sprintf(GetCompositePolicyRulesPath, client.config.url, strings.Join(items[:], "&")) + return fmt.Sprintf(getCompositePolicyRulesPath, c.config.url, strings.Join(items[:], "&")) } -type GetPoliciesQueryParams struct { +type getPoliciesQueryParams struct { PolicyType string Filter string Limit int } -func (q *GetPoliciesQueryParams) Encode() string { +func (q *getPoliciesQueryParams) Encode() string { return fmt.Sprintf("policyType=%s&filter=%s&limit=%d", q.PolicyType, url.QueryEscape(q.Filter), q.Limit) } diff --git a/sysdig/internal/client/v2/custom_role.go b/sysdig/internal/client/v2/custom_role.go index 44e96a1b0..9c0d6196f 100644 --- a/sysdig/internal/client/v2/custom_role.go +++ b/sysdig/internal/client/v2/custom_role.go @@ -7,11 +7,11 @@ import ( "net/http" ) -var CustomRoleNotFound = errors.New("custom role not found") +var ErrCustomRoleNotFound = errors.New("custom role not found") const ( - CustomRolesPath = "%s/api/roles" - CustomRolePath = "%s/api/roles/%d" + customRolesPath = "%s/api/roles" + customRolePath = "%s/api/roles/%d" ) type CustomRoleInterface interface { @@ -19,102 +19,107 @@ type CustomRoleInterface interface { CreateCustomRole(ctx context.Context, cr *CustomRole) (*CustomRole, error) UpdateCustomRole(ctx context.Context, cr *CustomRole, id int) (*CustomRole, error) DeleteCustomRole(ctx context.Context, id int) error - GetCustomRole(ctx context.Context, id int) (*CustomRole, error) + GetCustomRoleByID(ctx context.Context, id int) (*CustomRole, error) GetCustomRoleByName(ctx context.Context, name string) (*CustomRole, error) } -func (client *Client) CreateCustomRole(ctx context.Context, cr *CustomRole) (*CustomRole, error) { +func (c *Client) CreateCustomRole(ctx context.Context, cr *CustomRole) (customRole *CustomRole, err error) { payload, err := Marshal(cr) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateCustomRoleURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createCustomRoleURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - created, err := Unmarshal[CustomRole](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &created, nil + return Unmarshal[*CustomRole](response.Body) } -func (client *Client) UpdateCustomRole(ctx context.Context, cr *CustomRole, id int) (*CustomRole, error) { +func (c *Client) UpdateCustomRole(ctx context.Context, cr *CustomRole, id int) (customRole *CustomRole, err error) { payload, err := Marshal(cr) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateCustomRoleURL(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateCustomRoleURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - updated, err := Unmarshal[CustomRole](response.Body) - if err != nil { - return nil, err - } - - return &updated, nil + return Unmarshal[*CustomRole](response.Body) } -func (client *Client) DeleteCustomRole(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteCustomRoleURL(id), nil) +func (c *Client) DeleteCustomRole(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteCustomRoleURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetCustomRole(ctx context.Context, id int) (*CustomRole, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCustomRoleURL(id), nil) +func (c *Client) GetCustomRoleByID(ctx context.Context, id int) (customRole *CustomRole, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getCustomRoleURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { if response.StatusCode == http.StatusNotFound { - return nil, CustomRoleNotFound + return nil, ErrCustomRoleNotFound } - return nil, client.ErrorFromResponse(response) - } - - cr, err := Unmarshal[CustomRole](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &cr, nil + return Unmarshal[*CustomRole](response.Body) } -func (client *Client) GetCustomRoleByName(ctx context.Context, name string) (*CustomRole, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCustomRolesURL(), nil) +func (c *Client) GetCustomRoleByName(ctx context.Context, name string) (customRole *CustomRole, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getCustomRolesURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[customRoleListWrapper](response.Body) @@ -128,25 +133,25 @@ func (client *Client) GetCustomRoleByName(ctx context.Context, name string) (*Cu } } - return nil, fmt.Errorf("custom role with name: %s does not exist", name) + return nil, fmt.Errorf("custom role with name, %s does not exist: %w", name, ErrCustomRoleNotFound) } -func (client *Client) CreateCustomRoleURL() string { - return fmt.Sprintf(CustomRolesPath, client.config.url) +func (c *Client) createCustomRoleURL() string { + return fmt.Sprintf(customRolesPath, c.config.url) } -func (client *Client) UpdateCustomRoleURL(id int) string { - return fmt.Sprintf(CustomRolePath, client.config.url, id) +func (c *Client) updateCustomRoleURL(id int) string { + return fmt.Sprintf(customRolePath, c.config.url, id) } -func (client *Client) DeleteCustomRoleURL(id int) string { - return fmt.Sprintf(CustomRolePath, client.config.url, id) +func (c *Client) deleteCustomRoleURL(id int) string { + return fmt.Sprintf(customRolePath, c.config.url, id) } -func (client *Client) GetCustomRoleURL(id int) string { - return fmt.Sprintf(CustomRolePath, client.config.url, id) +func (c *Client) getCustomRoleURL(id int) string { + return fmt.Sprintf(customRolePath, c.config.url, id) } -func (client *Client) GetCustomRolesURL() string { - return fmt.Sprintf(CustomRolesPath, client.config.url) +func (c *Client) getCustomRolesURL() string { + return fmt.Sprintf(customRolesPath, c.config.url) } diff --git a/sysdig/internal/client/v2/dashboard.go b/sysdig/internal/client/v2/dashboard.go index ae6d6acbc..bb0418e4f 100644 --- a/sysdig/internal/client/v2/dashboard.go +++ b/sysdig/internal/client/v2/dashboard.go @@ -12,21 +12,25 @@ const ( ) type DashboardInterface interface { - GetDashboard(ctx context.Context, ID int) (*Dashboard, error) + GetDashboardByID(ctx context.Context, ID int) (*Dashboard, error) CreateDashboard(ctx context.Context, dashboard *Dashboard) (*Dashboard, error) UpdateDashboard(ctx context.Context, dashboard *Dashboard) (*Dashboard, error) DeleteDashboard(ctx context.Context, ID int) error } -func (client *Client) GetDashboard(ctx context.Context, ID int) (*Dashboard, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getDashboardURL(ID), nil) +func (c *Client) GetDashboardByID(ctx context.Context, ID int) (dashboard *Dashboard, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getDashboardURL(ID), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[*dashboardWrapper](response.Body) @@ -37,20 +41,24 @@ func (client *Client) GetDashboard(ctx context.Context, ID int) (*Dashboard, err return wrapper.Dashboard, nil } -func (client *Client) CreateDashboard(ctx context.Context, dashboard *Dashboard) (*Dashboard, error) { +func (c *Client) CreateDashboard(ctx context.Context, dashboard *Dashboard) (createdDashboard *Dashboard, err error) { payload, err := Marshal(dashboardWrapper{Dashboard: dashboard}) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getDashboardsURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getDashboardsURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[*dashboardWrapper](response.Body) @@ -61,20 +69,24 @@ func (client *Client) CreateDashboard(ctx context.Context, dashboard *Dashboard) return wrapper.Dashboard, nil } -func (client *Client) UpdateDashboard(ctx context.Context, dashboard *Dashboard) (*Dashboard, error) { +func (c *Client) UpdateDashboard(ctx context.Context, dashboard *Dashboard) (updatedDashboard *Dashboard, err error) { payload, err := Marshal(dashboardWrapper{Dashboard: dashboard}) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getDashboardURL(dashboard.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getDashboardURL(dashboard.ID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[*dashboardWrapper](response.Body) @@ -85,24 +97,28 @@ func (client *Client) UpdateDashboard(ctx context.Context, dashboard *Dashboard) return wrapper.Dashboard, nil } -func (client *Client) DeleteDashboard(ctx context.Context, ID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getDashboardURL(ID), nil) +func (c *Client) DeleteDashboard(ctx context.Context, ID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getDashboardURL(ID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getDashboardsURL() string { - return fmt.Sprintf(dashboardsPath, client.config.url) +func (c *Client) getDashboardsURL() string { + return fmt.Sprintf(dashboardsPath, c.config.url) } -func (client *Client) getDashboardURL(id int) string { - return fmt.Sprintf(dashboardPath, client.config.url, id) +func (c *Client) getDashboardURL(id int) string { + return fmt.Sprintf(dashboardPath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/deprecated_model.go b/sysdig/internal/client/v2/deprecated_model.go index af35a6af7..e220a626f 100644 --- a/sysdig/internal/client/v2/deprecated_model.go +++ b/sysdig/internal/client/v2/deprecated_model.go @@ -22,7 +22,7 @@ type DeprecatedScanningPolicy struct { Name string `json:"name"` Comment string `json:"comment"` IsDefault bool `json:"isDefault,omitempty"` - PolicyBundleId string `json:"policyBundleId,omitempty"` + PolicyBundleID string `json:"policyBundleId,omitempty"` Rules []DeprecatedScanningGate `json:"rules"` } @@ -41,7 +41,7 @@ type DeprecatedScanningGateParam struct { type DeprecatedScanningPolicyAssignmentList struct { Items []DeprecatedScanningPolicyAssignment `json:"items"` - PolicyBundleId string `json:"policyBundleId"` + PolicyBundleID string `json:"policyBundleId"` } type DeprecatedScanningPolicyAssignment struct { diff --git a/sysdig/internal/client/v2/deprecated_scanning_policies.go b/sysdig/internal/client/v2/deprecated_scanning_policies.go index f476f1d0b..bec56d258 100644 --- a/sysdig/internal/client/v2/deprecated_scanning_policies.go +++ b/sysdig/internal/client/v2/deprecated_scanning_policies.go @@ -16,7 +16,7 @@ type DeprecatedScanningPolicyInterface interface { Base CreateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) GetDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) (DeprecatedScanningPolicy, error) - UpdateDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) + UpdateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) DeleteDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) error } @@ -27,132 +27,160 @@ type DeprecatedScanningPolicyAssignmentInterface interface { GetDeprecatedScanningPolicyAssignmentList(ctx context.Context) (DeprecatedScanningPolicyAssignmentList, error) } -func (client *Client) CreateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) { +func (c *Client) CreateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (policy DeprecatedScanningPolicy, err error) { payload, err := Marshal(scanningPolicy) if err != nil { return DeprecatedScanningPolicy{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.deprecatedScanningPoliciesURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.deprecatedScanningPoliciesURL(), payload) if err != nil { return DeprecatedScanningPolicy{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return DeprecatedScanningPolicy{}, client.ErrorFromResponse(response) + return DeprecatedScanningPolicy{}, c.ErrorFromResponse(response) } return Unmarshal[DeprecatedScanningPolicy](response.Body) } -func (client *Client) GetDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) (DeprecatedScanningPolicy, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.deprecatedScanningPolicyURL(scanningPolicyID), nil) +func (c *Client) GetDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) (policy DeprecatedScanningPolicy, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.deprecatedScanningPolicyURL(scanningPolicyID), nil) if err != nil { return DeprecatedScanningPolicy{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return DeprecatedScanningPolicy{}, client.ErrorFromResponse(response) + return DeprecatedScanningPolicy{}, c.ErrorFromResponse(response) } return Unmarshal[DeprecatedScanningPolicy](response.Body) } -func (client *Client) UpdateDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) { +func (c *Client) UpdateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (policy DeprecatedScanningPolicy, err error) { payload, err := Marshal(scanningPolicy) if err != nil { return DeprecatedScanningPolicy{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.deprecatedScanningPolicyURL(scanningPolicy.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.deprecatedScanningPolicyURL(scanningPolicy.ID), payload) if err != nil { return DeprecatedScanningPolicy{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return DeprecatedScanningPolicy{}, client.ErrorFromResponse(response) + return DeprecatedScanningPolicy{}, c.ErrorFromResponse(response) } return Unmarshal[DeprecatedScanningPolicy](response.Body) } -func (client *Client) DeleteDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.deprecatedScanningPolicyURL(scanningPolicyID), nil) +func (c *Client) DeleteDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deprecatedScanningPolicyURL(scanningPolicyID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) CreateDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) (DeprecatedScanningPolicyAssignmentList, error) { +func (c *Client) CreateDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) (list DeprecatedScanningPolicyAssignmentList, err error) { payload, err := Marshal(scanningPolicyAssignmentList) if err != nil { return DeprecatedScanningPolicyAssignmentList{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.scanningPolicyAssignmentURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.scanningPolicyAssignmentURL(), payload) if err != nil { return DeprecatedScanningPolicyAssignmentList{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return DeprecatedScanningPolicyAssignmentList{}, client.ErrorFromResponse(response) + return DeprecatedScanningPolicyAssignmentList{}, c.ErrorFromResponse(response) } return Unmarshal[DeprecatedScanningPolicyAssignmentList](response.Body) } -func (client *Client) DeleteDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) error { +func (c *Client) DeleteDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) (err error) { payload, err := Marshal(scanningPolicyAssignmentList) if err != nil { return err } - response, err := client.requester.Request(ctx, http.MethodPut, client.scanningPolicyAssignmentURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.scanningPolicyAssignmentURL(), payload) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) GetDeprecatedScanningPolicyAssignmentList(ctx context.Context) (DeprecatedScanningPolicyAssignmentList, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.scanningPolicyAssignmentURL(), nil) +func (c *Client) GetDeprecatedScanningPolicyAssignmentList(ctx context.Context) (list DeprecatedScanningPolicyAssignmentList, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.scanningPolicyAssignmentURL(), nil) if err != nil { return DeprecatedScanningPolicyAssignmentList{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return DeprecatedScanningPolicyAssignmentList{}, client.ErrorFromResponse(response) + return DeprecatedScanningPolicyAssignmentList{}, c.ErrorFromResponse(response) } return Unmarshal[DeprecatedScanningPolicyAssignmentList](response.Body) } -func (client *Client) deprecatedScanningPoliciesURL() string { - return fmt.Sprintf(deprecatedScanningPoliciesPath, client.config.url) +func (c *Client) deprecatedScanningPoliciesURL() string { + return fmt.Sprintf(deprecatedScanningPoliciesPath, c.config.url) } -func (client *Client) deprecatedScanningPolicyURL(scanningPolicyID string) string { - return fmt.Sprintf(deprecatedScanningPolicyPath, client.config.url, scanningPolicyID) +func (c *Client) deprecatedScanningPolicyURL(scanningPolicyID string) string { + return fmt.Sprintf(deprecatedScanningPolicyPath, c.config.url, scanningPolicyID) } -func (client *Client) scanningPolicyAssignmentURL() string { - return fmt.Sprintf(deprecatedScanningPolicyAssigmentPath, client.config.url) +func (c *Client) scanningPolicyAssignmentURL() string { + return fmt.Sprintf(deprecatedScanningPolicyAssigmentPath, c.config.url) } diff --git a/sysdig/internal/client/v2/doc.go b/sysdig/internal/client/v2/doc.go new file mode 100644 index 000000000..5fac629be --- /dev/null +++ b/sysdig/internal/client/v2/doc.go @@ -0,0 +1,2 @@ +// Package v2 implements a client for Sysdig API +package v2 diff --git a/sysdig/internal/client/v2/group_mapping.go b/sysdig/internal/client/v2/group_mapping.go index 371963f65..65109cfb4 100644 --- a/sysdig/internal/client/v2/group_mapping.go +++ b/sysdig/internal/client/v2/group_mapping.go @@ -7,13 +7,13 @@ import ( "net/http" ) -var GroupMappingNotFound = errors.New("group mapping not found") +var ErrGroupMappingNotFound = errors.New("group mapping not found") const ( - CreateGroupMappingPath = "%s/api/groupmappings" - UpdateGroupMappingPath = "%s/api/groupmappings/%d" - DeleteGroupMappingPath = "%s/api/groupmappings/%d" - GetGroupMappingPath = "%s/api/groupmappings/%d" + createGroupMappingPath = "%s/api/groupmappings" + updateGroupMappingPath = "%s/api/groupmappings/%d" + deleteGroupMappingPath = "%s/api/groupmappings/%d" + getGroupMappingPath = "%s/api/groupmappings/%d" ) type GroupMappingInterface interface { @@ -24,102 +24,103 @@ type GroupMappingInterface interface { GetGroupMapping(ctx context.Context, id int) (*GroupMapping, error) } -func (client *Client) CreateGroupMapping(ctx context.Context, gm *GroupMapping) (*GroupMapping, error) { +func (c *Client) CreateGroupMapping(ctx context.Context, gm *GroupMapping) (mapping *GroupMapping, err error) { payload, err := Marshal(gm) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateGroupMappingURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createGroupMappingURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - created, err := Unmarshal[GroupMapping](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &created, nil + return Unmarshal[*GroupMapping](response.Body) } -func (client *Client) UpdateGroupMapping(ctx context.Context, gm *GroupMapping, id int) (*GroupMapping, error) { +func (c *Client) UpdateGroupMapping(ctx context.Context, gm *GroupMapping, id int) (mapping *GroupMapping, err error) { payload, err := Marshal(gm) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateGroupMappingURL(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateGroupMappingURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - updated, err := Unmarshal[GroupMapping](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updated, nil + return Unmarshal[*GroupMapping](response.Body) } -func (client *Client) DeleteGroupMapping(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteGroupMappingURL(id), nil) +func (c *Client) DeleteGroupMapping(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteGroupMappingURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetGroupMapping(ctx context.Context, id int) (*GroupMapping, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetGroupMappingURL(id), nil) +func (c *Client) GetGroupMapping(ctx context.Context, id int) (mapping *GroupMapping, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getGroupMappingURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - if response.StatusCode == http.StatusNotFound { - return nil, GroupMappingNotFound + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) } - return nil, client.ErrorFromResponse(response) - } + }() - gm, err := Unmarshal[GroupMapping](response.Body) - if err != nil { - return nil, err + if response.StatusCode == http.StatusNotFound { + return nil, ErrGroupMappingNotFound + } + if response.StatusCode != http.StatusOK { + return nil, c.ErrorFromResponse(response) } - return &gm, nil + return Unmarshal[*GroupMapping](response.Body) } -func (client *Client) CreateGroupMappingURL() string { - return fmt.Sprintf(CreateGroupMappingPath, client.config.url) +func (c *Client) createGroupMappingURL() string { + return fmt.Sprintf(createGroupMappingPath, c.config.url) } -func (client *Client) UpdateGroupMappingURL(id int) string { - return fmt.Sprintf(UpdateGroupMappingPath, client.config.url, id) +func (c *Client) updateGroupMappingURL(id int) string { + return fmt.Sprintf(updateGroupMappingPath, c.config.url, id) } -func (client *Client) DeleteGroupMappingURL(id int) string { - return fmt.Sprintf(DeleteGroupMappingPath, client.config.url, id) +func (c *Client) deleteGroupMappingURL(id int) string { + return fmt.Sprintf(deleteGroupMappingPath, c.config.url, id) } -func (client *Client) GetGroupMappingURL(id int) string { - return fmt.Sprintf(GetGroupMappingPath, client.config.url, id) +func (c *Client) getGroupMappingURL(id int) string { + return fmt.Sprintf(getGroupMappingPath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/group_mapping_config.go b/sysdig/internal/client/v2/group_mapping_config.go index f2f7ae332..0ccf9f25c 100644 --- a/sysdig/internal/client/v2/group_mapping_config.go +++ b/sysdig/internal/client/v2/group_mapping_config.go @@ -7,10 +7,10 @@ import ( "net/http" ) -var GroupMappingConfigNotFound = errors.New("group mapping configuration not found") +var ErrGroupMappingConfigNotFound = errors.New("group mapping configuration not found") const ( - GroupMappingConfigPath = "%s/api/groupmappings/settings" + groupMappingConfigPath = "%s/api/groupmappings/settings" ) type GroupMappingConfigInterface interface { @@ -19,56 +19,54 @@ type GroupMappingConfigInterface interface { GetGroupMappingConfig(ctx context.Context) (*GroupMappingConfig, error) } -func (client *Client) UpdateGroupMappingConfig(ctx context.Context, gmc *GroupMappingConfig) (*GroupMappingConfig, error) { +func (c *Client) UpdateGroupMappingConfig(ctx context.Context, gmc *GroupMappingConfig) (mapping *GroupMappingConfig, err error) { payload, err := Marshal(gmc) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateGroupMappingConfigURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateGroupMappingConfigURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - updated, err := Unmarshal[GroupMappingConfig](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updated, nil + return Unmarshal[*GroupMappingConfig](response.Body) } -func (client *Client) GetGroupMappingConfig(ctx context.Context) (*GroupMappingConfig, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetGroupMappingConfigURL(), nil) +func (c *Client) GetGroupMappingConfig(ctx context.Context) (mapping *GroupMappingConfig, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getGroupMappingConfigURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - if response.StatusCode == http.StatusNotFound { - return nil, GroupMappingConfigNotFound + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) } - return nil, client.ErrorFromResponse(response) - } + }() - gmc, err := Unmarshal[GroupMappingConfig](response.Body) - if err != nil { - return nil, err + if response.StatusCode == http.StatusNotFound { + return nil, ErrGroupMappingConfigNotFound + } + if response.StatusCode != http.StatusOK { + return nil, c.ErrorFromResponse(response) } - return &gmc, nil + return Unmarshal[*GroupMappingConfig](response.Body) } -func (client *Client) UpdateGroupMappingConfigURL() string { - return fmt.Sprintf(GroupMappingConfigPath, client.config.url) +func (c *Client) updateGroupMappingConfigURL() string { + return fmt.Sprintf(groupMappingConfigPath, c.config.url) } -func (client *Client) GetGroupMappingConfigURL() string { - return fmt.Sprintf(GroupMappingConfigPath, client.config.url) +func (c *Client) getGroupMappingConfigURL() string { + return fmt.Sprintf(groupMappingConfigPath, c.config.url) } diff --git a/sysdig/internal/client/v2/ibm.go b/sysdig/internal/client/v2/ibm.go index 40412c3b7..17e9a8c35 100644 --- a/sysdig/internal/client/v2/ibm.go +++ b/sysdig/internal/client/v2/ibm.go @@ -13,14 +13,14 @@ import ( ) const ( - IBMInstanceIDHeader = "IBMInstanceID" - IBMIAMPath = "/identity/token" - IBMGrantTypeFormValue = "grant_type" - IBMApiKeyFormValue = "apikey" - IBMAPIKeyGrantType = "urn:ibm:params:oauth:grant-type:apikey" - SysdigTeamIDHeader = "SysdigTeamID" - GetTeamByNamePath = "/api/v2/teams/light/name/" - IBMProductHeader = "SysdigProduct" + ibmInstanceIDHeader = "IBMInstanceID" + ibmIAMPath = "/identity/token" + ibmGrantTypeFormValue = "grant_type" + ibmAPIKeyFormValue = "apikey" + ibmAPIKeyGrantType = "urn:ibm:params:oauth:grant-type:apikey" + sysdigTeamIDHeader = "SysdigTeamID" + getTeamByNamePath = "/api/v2/teams/light/name/" + ibmProductHeader = "SysdigProduct" ) type IBMCommon interface { @@ -59,7 +59,7 @@ type IAMTokenResponse struct { Expiration int64 `json:"expiration"` } -func (ir *IBMRequest) getIBMIAMToken() (IBMAccessToken, error) { +func (ir *IBMRequest) getIBMIAMToken() (token IBMAccessToken, err error) { ir.tokenLock.Lock() defer ir.tokenLock.Unlock() @@ -68,9 +68,9 @@ func (ir *IBMRequest) getIBMIAMToken() (IBMAccessToken, error) { } data := url.Values{} - data.Set(IBMGrantTypeFormValue, IBMAPIKeyGrantType) - data.Set(IBMApiKeyFormValue, ir.config.ibmAPIKey) - identityURL := fmt.Sprintf("%s%s", ir.config.ibmIamURL, IBMIAMPath) + data.Set(ibmGrantTypeFormValue, ibmAPIKeyGrantType) + data.Set(ibmAPIKeyFormValue, ir.config.ibmAPIKey) + identityURL := fmt.Sprintf("%s%s", ir.config.ibmIamURL, ibmIAMPath) r, err := http.NewRequest(http.MethodPost, identityURL, strings.NewReader(data.Encode())) if err != nil { @@ -79,13 +79,17 @@ func (ir *IBMRequest) getIBMIAMToken() (IBMAccessToken, error) { r.Header.Set(ContentTypeHeader, ContentTypeFormURLEncoded) - resp, err := request(ir.httpClient, ir.config, r) + response, err := request(ir.httpClient, ir.config, r) if err != nil { return "", err } - defer resp.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() - iamToken, err := Unmarshal[IAMTokenResponse](resp.Body) + iamToken, err := Unmarshal[IAMTokenResponse](response.Body) if err != nil { return "", err } @@ -96,10 +100,10 @@ func (ir *IBMRequest) getIBMIAMToken() (IBMAccessToken, error) { return ir.token, nil } -func (ir *IBMRequest) getTeamIDByName(ctx context.Context, name string, token IBMAccessToken) (int, error) { +func (ir *IBMRequest) getTeamIDByName(ctx context.Context, name string, token IBMAccessToken) (teamID int, err error) { r, err := http.NewRequest( http.MethodGet, - fmt.Sprintf("%s%s%s", ir.config.url, GetTeamByNamePath, name), + fmt.Sprintf("%s%s%s", ir.config.url, getTeamByNamePath, name), nil, ) if err != nil { @@ -107,18 +111,22 @@ func (ir *IBMRequest) getTeamIDByName(ctx context.Context, name string, token IB } r = r.WithContext(ctx) - r.Header.Set(IBMInstanceIDHeader, ir.config.ibmInstanceID) + r.Header.Set(ibmInstanceIDHeader, ir.config.ibmInstanceID) r.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", token)) r.Header.Set(SysdigProductHeader, ir.config.product) - r.Header.Set(IBMProductHeader, ir.config.product) + r.Header.Set(ibmProductHeader, ir.config.product) - resp, err := request(ir.httpClient, ir.config, r) + response, err := request(ir.httpClient, ir.config, r) if err != nil { return -1, err } - defer resp.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() - wrapper, err := Unmarshal[teamWrapper](resp.Body) + wrapper, err := Unmarshal[teamWrapper](response.Body) if err != nil { return -1, err } @@ -151,10 +159,10 @@ func (ir *IBMRequest) CurrentTeamID(ctx context.Context) (int, error) { // use default current team user, err := getMe(ctx, ir.config, ir.httpClient, map[string]string{ - IBMInstanceIDHeader: ir.config.ibmInstanceID, + ibmInstanceIDHeader: ir.config.ibmInstanceID, AuthorizationHeader: fmt.Sprintf("Bearer %s", token), SysdigProductHeader: ir.config.product, - IBMProductHeader: ir.config.product, + ibmProductHeader: ir.config.product, }) if err != nil { return -1, err @@ -186,13 +194,13 @@ func (ir *IBMRequest) Request(ctx context.Context, method string, url string, pa } r = r.WithContext(ctx) - r.Header.Set(IBMInstanceIDHeader, ir.config.ibmInstanceID) + r.Header.Set(ibmInstanceIDHeader, ir.config.ibmInstanceID) r.Header.Set(AuthorizationHeader, fmt.Sprintf("Bearer %s", token)) - r.Header.Set(SysdigTeamIDHeader, strconv.Itoa(teamID)) + r.Header.Set(sysdigTeamIDHeader, strconv.Itoa(teamID)) r.Header.Set(ContentTypeHeader, ContentTypeJSON) r.Header.Set(SysdigProviderHeader, SysdigProviderHeaderValue) r.Header.Set(SysdigProductHeader, ir.config.product) - r.Header.Set(IBMProductHeader, ir.config.product) + r.Header.Set(ibmProductHeader, ir.config.product) return request(ir.httpClient, ir.config, r) } diff --git a/sysdig/internal/client/v2/ibm_test.go b/sysdig/internal/client/v2/ibm_test.go index 5cd62ba4a..ed876b6c0 100644 --- a/sysdig/internal/client/v2/ibm_test.go +++ b/sysdig/internal/client/v2/ibm_test.go @@ -1,5 +1,3 @@ -//go:build unit - package v2 import ( @@ -35,7 +33,7 @@ func TestIBMClient_DoIBMRequest(t *testing.T) { token := "token" iamEndpointCalled := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == IBMIAMPath { + if r.URL.Path == ibmIAMPath { iamEndpointCalled++ data, err := json.Marshal(IAMTokenResponse{ AccessToken: token, @@ -55,7 +53,7 @@ func TestIBMClient_DoIBMRequest(t *testing.T) { if value := r.Header.Get(AuthorizationHeader); value != fmt.Sprintf("Bearer %s", token) { t.Errorf("invalid authorization header, %v", value) } - if value := r.Header.Get(IBMInstanceIDHeader); value != instanceID { + if value := r.Header.Get(ibmInstanceIDHeader); value != instanceID { t.Errorf("expected instance id %v, got %v", instanceID, value) } if value := r.Header.Get(SysdigProviderHeader); value != SysdigProviderHeaderValue { @@ -138,14 +136,14 @@ func TestIBMClient_CurrentTeamID(t *testing.T) { var data []byte switch r.URL.Path { - case fmt.Sprintf("%steam", GetTeamByNamePath): + case fmt.Sprintf("%steam", getTeamByNamePath): data, err = json.Marshal(teamWrapper{Team: Team{ ID: teamID3, }}) if err != nil { t.Errorf("failed to create team response, err: %v", err) } - case IBMIAMPath: + case ibmIAMPath: data, err = json.Marshal(IAMTokenResponse{ AccessToken: token, Expiration: time.Now().Add(time.Hour).Unix(), diff --git a/sysdig/internal/client/v2/identity_context.go b/sysdig/internal/client/v2/identity_context.go index ab04b5ddb..145ef62c4 100644 --- a/sysdig/internal/client/v2/identity_context.go +++ b/sysdig/internal/client/v2/identity_context.go @@ -6,26 +6,30 @@ import ( "net/http" ) -const GetIdentityContextPath = "%s/api/identity/context" +const getIdentityContextPath = "%s/api/identity/context" type IdentityContextInterface interface { GetIdentityContext(ctx context.Context) (*IdentityContext, error) } -func (client *Client) GetIdentityContext(ctx context.Context) (*IdentityContext, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetIdentityContextURL(), nil) +func (c *Client) GetIdentityContext(ctx context.Context) (idx *IdentityContext, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getIdentityContextURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*IdentityContext](response.Body) } -func (client *Client) GetIdentityContextURL() string { - return fmt.Sprintf(GetIdentityContextPath, client.config.url) +func (c *Client) getIdentityContextURL() string { + return fmt.Sprintf(getIdentityContextPath, c.config.url) } diff --git a/sysdig/internal/client/v2/inhibition_rule.go b/sysdig/internal/client/v2/inhibition_rule.go index 346b25d1c..500a65110 100644 --- a/sysdig/internal/client/v2/inhibition_rule.go +++ b/sysdig/internal/client/v2/inhibition_rule.go @@ -16,90 +16,101 @@ var ErrInhibitionRuleNotFound = errors.New("inhibition rule not found") type InhibitionRuleInterface interface { Base - GetInhibitionRule(ctx context.Context, id int) (InhibitionRule, error) + GetInhibitionRuleByID(ctx context.Context, id int) (InhibitionRule, error) CreateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (InhibitionRule, error) UpdateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (InhibitionRule, error) DeleteInhibitionRule(ctx context.Context, id int) error } -func (client *Client) GetInhibitionRule(ctx context.Context, id int) (InhibitionRule, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getInhibitionRuleURL(id), nil) +func (c *Client) GetInhibitionRuleByID(ctx context.Context, id int) (rule InhibitionRule, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getInhibitionRuleURL(id), nil) if err != nil { return InhibitionRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode == http.StatusNotFound { return InhibitionRule{}, ErrInhibitionRuleNotFound } if response.StatusCode != http.StatusOK { - return InhibitionRule{}, client.ErrorFromResponse(response) + return InhibitionRule{}, c.ErrorFromResponse(response) } - inhibitionRule, err := Unmarshal[InhibitionRule](response.Body) - if err != nil { - return InhibitionRule{}, err - } - - return inhibitionRule, nil + return Unmarshal[InhibitionRule](response.Body) } -func (client *Client) CreateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (InhibitionRule, error) { +func (c *Client) CreateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (rule InhibitionRule, err error) { payload, err := Marshal(inhibitionRule) if err != nil { return InhibitionRule{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getInhibitionRulesURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getInhibitionRulesURL(), payload) if err != nil { return InhibitionRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return InhibitionRule{}, client.ErrorFromResponse(response) + return InhibitionRule{}, c.ErrorFromResponse(response) } return Unmarshal[InhibitionRule](response.Body) } -func (client *Client) UpdateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (InhibitionRule, error) { +func (c *Client) UpdateInhibitionRule(ctx context.Context, inhibitionRule InhibitionRule) (rule InhibitionRule, err error) { payload, err := Marshal(inhibitionRule) if err != nil { return InhibitionRule{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getInhibitionRuleURL(inhibitionRule.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getInhibitionRuleURL(inhibitionRule.ID), payload) if err != nil { return InhibitionRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return InhibitionRule{}, client.ErrorFromResponse(response) + return InhibitionRule{}, c.ErrorFromResponse(response) } return Unmarshal[InhibitionRule](response.Body) } -func (client *Client) DeleteInhibitionRule(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getInhibitionRuleURL(id), nil) +func (c *Client) DeleteInhibitionRule(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getInhibitionRuleURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getInhibitionRulesURL() string { - return fmt.Sprintf(inhibitionRulesPath, client.config.url) +func (c *Client) getInhibitionRulesURL() string { + return fmt.Sprintf(inhibitionRulesPath, c.config.url) } -func (client *Client) getInhibitionRuleURL(id int) string { - return fmt.Sprintf(inhibitionRulePath, client.config.url, id) +func (c *Client) getInhibitionRuleURL(id int) string { + return fmt.Sprintf(inhibitionRulePath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/ip_filtering_settings.go b/sysdig/internal/client/v2/ip_filtering_settings.go index 6a2aabd81..4336664fe 100644 --- a/sysdig/internal/client/v2/ip_filtering_settings.go +++ b/sysdig/internal/client/v2/ip_filtering_settings.go @@ -7,7 +7,7 @@ import ( ) const ( - IPFiltersSettingsPath = "%s/platform/v1/ip-filters-settings" + ipFiltersSettingsPath = "%s/platform/v1/ip-filters-settings" ) type IPFilteringSettingsInterface interface { @@ -16,50 +16,48 @@ type IPFilteringSettingsInterface interface { UpdateIPFilteringSettings(ctx context.Context, ipFiltersSettings *IPFiltersSettings) (*IPFiltersSettings, error) } -func (client *Client) GetIPFilteringSettings(ctx context.Context) (*IPFiltersSettings, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetIPFiltersSettingsURL(), nil) +func (c *Client) GetIPFilteringSettings(ctx context.Context) (settings *IPFiltersSettings, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.GetIPFiltersSettingsURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } - ipFiltersSettings, err := Unmarshal[IPFiltersSettings](response.Body) - if err != nil { - return nil, err - } - - return &ipFiltersSettings, nil + return Unmarshal[*IPFiltersSettings](response.Body) } -func (client *Client) UpdateIPFilteringSettings(ctx context.Context, ipFiltersSettings *IPFiltersSettings) (*IPFiltersSettings, error) { +func (c *Client) UpdateIPFilteringSettings(ctx context.Context, ipFiltersSettings *IPFiltersSettings) (settings *IPFiltersSettings, err error) { payload, err := Marshal(ipFiltersSettings) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.GetIPFiltersSettingsURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.GetIPFiltersSettingsURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - updated, err := Unmarshal[IPFiltersSettings](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updated, nil + return Unmarshal[*IPFiltersSettings](response.Body) } -func (client *Client) GetIPFiltersSettingsURL() string { - return fmt.Sprintf(IPFiltersSettingsPath, client.config.url) +func (c *Client) GetIPFiltersSettingsURL() string { + return fmt.Sprintf(ipFiltersSettingsPath, c.config.url) } diff --git a/sysdig/internal/client/v2/ip_filters.go b/sysdig/internal/client/v2/ip_filters.go index d1d207753..903af0b98 100644 --- a/sysdig/internal/client/v2/ip_filters.go +++ b/sysdig/internal/client/v2/ip_filters.go @@ -7,108 +7,108 @@ import ( "net/http" ) -var IPFilterNotFound = errors.New("IP filter not found") +var ErrIPFilterNotFound = errors.New("IP filter not found") const ( - IPFiltersPath = "%s/platform/v1/ip-filters" - IPFilterPath = "%s/platform/v1/ip-filters/%d" + ipFiltersPath = "%s/platform/v1/ip-filters" + ipFilterPath = "%s/platform/v1/ip-filters/%d" ) type IPFiltersInterface interface { Base - GetIPFilterById(ctx context.Context, id int) (*IPFilter, error) + GetIPFilterByID(ctx context.Context, id int) (*IPFilter, error) CreateIPFilter(ctx context.Context, ipFilter *IPFilter) (*IPFilter, error) UpdateIPFilter(ctx context.Context, ipFilter *IPFilter, id int) (*IPFilter, error) DeleteIPFilter(ctx context.Context, id int) error } -func (client *Client) GetIPFilterById(ctx context.Context, id int) (*IPFilter, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetIPFilterURL(id), nil) +func (c *Client) GetIPFilterByID(ctx context.Context, id int) (ipFilter *IPFilter, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getIPFilterURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } - ipFilter, err := Unmarshal[IPFilter](response.Body) - if err != nil { - return nil, err - } - - return &ipFilter, nil + return Unmarshal[*IPFilter](response.Body) } -func (client *Client) CreateIPFilter(ctx context.Context, ipFilter *IPFilter) (*IPFilter, error) { +func (c *Client) CreateIPFilter(ctx context.Context, ipFilter *IPFilter) (createdFilter *IPFilter, err error) { payload, err := Marshal(ipFilter) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.GetIPFiltersURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getIPFiltersURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - created, err := Unmarshal[IPFilter](response.Body) - if err != nil { - return nil, err - } - - return &created, nil - + return Unmarshal[*IPFilter](response.Body) } -func (client *Client) UpdateIPFilter(ctx context.Context, ipFilter *IPFilter, id int) (*IPFilter, error) { +func (c *Client) UpdateIPFilter(ctx context.Context, ipFilter *IPFilter, id int) (updatedFilter *IPFilter, err error) { payload, err := Marshal(ipFilter) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.GetIPFilterURL(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getIPFilterURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - updated, err := Unmarshal[IPFilter](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updated, nil + return Unmarshal[*IPFilter](response.Body) } -func (client *Client) DeleteIPFilter(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.GetIPFilterURL(id), nil) +func (c *Client) DeleteIPFilter(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getIPFilterURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetIPFilterURL(id int) string { - return fmt.Sprintf(IPFilterPath, client.config.url, id) +func (c *Client) getIPFilterURL(id int) string { + return fmt.Sprintf(ipFilterPath, c.config.url, id) } -func (client *Client) GetIPFiltersURL() string { - return fmt.Sprintf(IPFiltersPath, client.config.url) +func (c *Client) getIPFiltersURL() string { + return fmt.Sprintf(ipFiltersPath, c.config.url) } diff --git a/sysdig/internal/client/v2/list.go b/sysdig/internal/client/v2/list.go index ced87d3b1..e087410c4 100644 --- a/sysdig/internal/client/v2/list.go +++ b/sysdig/internal/client/v2/list.go @@ -7,10 +7,10 @@ import ( ) const ( - CreateListPath = "%s/api/secure/falco/lists?skipPolicyV2Msg=%t" - GetListPath = "%s/api/secure/falco/lists/%d" - UpdateListPath = "%s/api/secure/falco/lists/%d?skipPolicyV2Msg=%t" - DeleteListPath = "%s/api/secure/falco/lists/%d?skipPolicyV2Msg=%t" + createListPath = "%s/api/secure/falco/lists?skipPolicyV2Msg=%t" + getListPath = "%s/api/secure/falco/lists/%d" + updateListPath = "%s/api/secure/falco/lists/%d?skipPolicyV2Msg=%t" + deleteListPath = "%s/api/secure/falco/lists/%d?skipPolicyV2Msg=%t" ) type ListInterface interface { @@ -21,37 +21,45 @@ type ListInterface interface { DeleteList(ctx context.Context, id int) error } -func (client *Client) CreateList(ctx context.Context, list List) (List, error) { - payload, err := Marshal[List](list) +func (c *Client) CreateList(ctx context.Context, list List) (createdList List, err error) { + payload, err := Marshal(list) if err != nil { return List{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateListURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createListURL(), payload) if err != nil { return List{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return List{}, client.ErrorFromResponse(response) + return List{}, c.ErrorFromResponse(response) } return Unmarshal[List](response.Body) } -func (client *Client) GetListByID(ctx context.Context, id int) (List, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetListURL(id), nil) +func (c *Client) GetListByID(ctx context.Context, id int) (list List, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getListURL(id), nil) if err != nil { return List{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return List{}, client.ErrorFromResponse(response) + return List{}, c.ErrorFromResponse(response) } - list, err := Unmarshal[List](response.Body) + list, err = Unmarshal[List](response.Body) if err != nil { return List{}, err } @@ -63,51 +71,59 @@ func (client *Client) GetListByID(ctx context.Context, id int) (List, error) { return list, nil } -func (client *Client) UpdateList(ctx context.Context, list List) (List, error) { - payload, err := Marshal[List](list) +func (c *Client) UpdateList(ctx context.Context, list List) (updatedList List, err error) { + payload, err := Marshal(list) if err != nil { return List{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateListURL(list.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateListURL(list.ID), payload) if err != nil { return List{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return List{}, client.ErrorFromResponse(response) + return List{}, c.ErrorFromResponse(response) } return Unmarshal[List](response.Body) } -func (client *Client) DeleteList(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteListURL(id), nil) +func (c *Client) DeleteList(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteListURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) CreateListURL() string { - return fmt.Sprintf(CreateListPath, client.config.url, client.config.secureSkipPolicyV2Msg) +func (c *Client) createListURL() string { + return fmt.Sprintf(createListPath, c.config.url, c.config.secureSkipPolicyV2Msg) } -func (client *Client) GetListURL(id int) string { - return fmt.Sprintf(GetListPath, client.config.url, id) +func (c *Client) getListURL(id int) string { + return fmt.Sprintf(getListPath, c.config.url, id) } -func (client *Client) UpdateListURL(id int) string { - return fmt.Sprintf(UpdateListPath, client.config.url, id, client.config.secureSkipPolicyV2Msg) +func (c *Client) updateListURL(id int) string { + return fmt.Sprintf(updateListPath, c.config.url, id, c.config.secureSkipPolicyV2Msg) } -func (client *Client) DeleteListURL(id int) string { - return fmt.Sprintf(DeleteListPath, client.config.url, id, client.config.secureSkipPolicyV2Msg) +func (c *Client) deleteListURL(id int) string { + return fmt.Sprintf(deleteListPath, c.config.url, id, c.config.secureSkipPolicyV2Msg) } diff --git a/sysdig/internal/client/v2/macros.go b/sysdig/internal/client/v2/macros.go index 8283af5b6..c91309df1 100644 --- a/sysdig/internal/client/v2/macros.go +++ b/sysdig/internal/client/v2/macros.go @@ -7,10 +7,10 @@ import ( ) const ( - CreateMacroPath = "%s/api/secure/falco/macros?skipPolicyV2Msg=%t" - GetMacroByIDPath = "%s/api/secure/falco/macros/%d" - UpdateMacroPath = "%s/api/secure/falco/macros/%d?skipPolicyV2Msg=%t" - DeleteMacroPath = "%s/api/secure/falco/macros/%d?skipPolicyV2Msg=%t" + createMacroPath = "%s/api/secure/falco/macros?skipPolicyV2Msg=%t" + getMacroByIDPath = "%s/api/secure/falco/macros/%d" + updateMacroPath = "%s/api/secure/falco/macros/%d?skipPolicyV2Msg=%t" + deleteMacroPath = "%s/api/secure/falco/macros/%d?skipPolicyV2Msg=%t" ) type MacroInterface interface { @@ -21,37 +21,45 @@ type MacroInterface interface { DeleteMacro(ctx context.Context, id int) error } -func (client *Client) CreateMacro(ctx context.Context, macro Macro) (Macro, error) { +func (c *Client) CreateMacro(ctx context.Context, macro Macro) (createdMacro Macro, err error) { payload, err := Marshal(macro) if err != nil { return Macro{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateMacroURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createMacroURL(), payload) if err != nil { return Macro{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return Macro{}, client.ErrorFromResponse(response) + return Macro{}, c.ErrorFromResponse(response) } return Unmarshal[Macro](response.Body) } -func (client *Client) GetMacroByID(ctx context.Context, id int) (Macro, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetMacroByIDURL(id), nil) +func (c *Client) GetMacroByID(ctx context.Context, id int) (macro Macro, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getMacroByIDURL(id), nil) if err != nil { return Macro{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Macro{}, client.ErrorFromResponse(response) + return Macro{}, c.ErrorFromResponse(response) } - macro, err := Unmarshal[Macro](response.Body) + macro, err = Unmarshal[Macro](response.Body) if err != nil { return Macro{}, err } @@ -63,50 +71,58 @@ func (client *Client) GetMacroByID(ctx context.Context, id int) (Macro, error) { return macro, nil } -func (client *Client) UpdateMacro(ctx context.Context, macro Macro) (Macro, error) { +func (c *Client) UpdateMacro(ctx context.Context, macro Macro) (updateMacro Macro, err error) { payload, err := Marshal(macro) if err != nil { return Macro{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateMacroURL(macro.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateMacroURL(macro.ID), payload) if err != nil { return Macro{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Macro{}, client.ErrorFromResponse(response) + return Macro{}, c.ErrorFromResponse(response) } return Unmarshal[Macro](response.Body) } -func (client *Client) DeleteMacro(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteMacroURL(id), nil) +func (c *Client) DeleteMacro(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteMacroURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) CreateMacroURL() string { - return fmt.Sprintf(CreateMacroPath, client.config.url, client.config.secureSkipPolicyV2Msg) +func (c *Client) createMacroURL() string { + return fmt.Sprintf(createMacroPath, c.config.url, c.config.secureSkipPolicyV2Msg) } -func (client *Client) GetMacroByIDURL(id int) string { - return fmt.Sprintf(GetMacroByIDPath, client.config.url, id) +func (c *Client) getMacroByIDURL(id int) string { + return fmt.Sprintf(getMacroByIDPath, c.config.url, id) } -func (client *Client) UpdateMacroURL(id int) string { - return fmt.Sprintf(UpdateMacroPath, client.config.url, id, client.config.secureSkipPolicyV2Msg) +func (c *Client) updateMacroURL(id int) string { + return fmt.Sprintf(updateMacroPath, c.config.url, id, c.config.secureSkipPolicyV2Msg) } -func (client *Client) DeleteMacroURL(id int) string { - return fmt.Sprintf(DeleteMacroPath, client.config.url, id, client.config.secureSkipPolicyV2Msg) +func (c *Client) deleteMacroURL(id int) string { + return fmt.Sprintf(deleteMacroPath, c.config.url, id, c.config.secureSkipPolicyV2Msg) } diff --git a/sysdig/internal/client/v2/model.go b/sysdig/internal/client/v2/model.go index f23c4ad36..480be46de 100644 --- a/sysdig/internal/client/v2/model.go +++ b/sysdig/internal/client/v2/model.go @@ -42,7 +42,7 @@ type NamespaceFilters struct { } type UserRoles struct { - UserId int `json:"userId"` + UserID int `json:"userId"` Email string `json:"userName,omitempty"` Role string `json:"role"` Admin bool `json:"admin,omitempty"` @@ -70,11 +70,11 @@ type TeamServiceAccount struct { ID int `json:"id,omitempty"` Name string `json:"name"` SystemRole string `json:"systemRole"` - TeamId int `json:"teamId"` + TeamID int `json:"teamId"` TeamRole string `json:"teamRole"` DateCreated int64 `json:"dateCreated,omitempty"` ExpirationDate int64 `json:"expirationDate"` - ApiKey string `json:"apiKey,omitempty"` + APIKey string `json:"apiKey,omitempty"` } type EntryPoint struct { @@ -119,22 +119,22 @@ type NotificationChannelOptions struct { SnsTopicARNs []string `json:"snsTopicARNs,omitempty"` // Type: SNS APIKey string `json:"apiKey,omitempty"` // Type: VictorOps, ibm event function RoutingKey string `json:"routingKey,omitempty"` // Type: VictorOps - Url string `json:"url,omitempty"` // Type: OpsGenie, Webhook, Slack, google chat, prometheus alert manager, custom webhook, ms teams + URL string `json:"url,omitempty"` // Type: OpsGenie, Webhook, Slack, google chat, prometheus alert manager, custom webhook, ms teams Channel string `json:"channel,omitempty"` // Type: Slack PrivateChannel bool `json:"privateChannel,omitempty"` // Type: Slack - PrivateChannelUrl string `json:"privateChannelUrl,omitempty"` // Type: Slack + PrivateChannelURL string `json:"privateChannelUrl,omitempty"` // Type: Slack Account string `json:"account,omitempty"` // Type: PagerDuty ServiceKey string `json:"serviceKey,omitempty"` // Type: PagerDuty ServiceName string `json:"serviceName,omitempty"` // Type: PagerDuty - AdditionalHeaders map[string]interface{} `json:"additionalHeaders,omitempty"` // Type: Webhook, prometheus alert manager, custom webhook, ibm function + AdditionalHeaders map[string]any `json:"additionalHeaders,omitempty"` // Type: Webhook, prometheus alert manager, custom webhook, ibm function Region string `json:"region,omitempty"` // Type: OpsGenie AllowInsecureConnections *bool `json:"allowInsecureConnections,omitempty"` // Type: prometheus alert manager, custom webhook, Webhook - TeamId int `json:"teamId,omitempty"` // Type: team email - HttpMethod string `json:"httpMethod,omitempty"` // Type: custom webhook + TeamID int `json:"teamId,omitempty"` // Type: team email + HTTPMethod string `json:"httpMethod,omitempty"` // Type: custom webhook MonitorTemplate string `json:"monitorTemplate,omitempty"` // Type: custom webhook - InstanceId string `json:"instanceId,omitempty"` // Type: ibm event notification + InstanceID string `json:"instanceId,omitempty"` // Type: ibm event notification IbmFunctionType string `json:"ibmFunctionType,omitempty"` // Type: ibm event function - CustomData map[string]interface{} `json:"customData,omitempty"` // Type: ibm function, Webhook + CustomData map[string]any `json:"customData,omitempty"` // Type: ibm function, Webhook TemplateConfiguration []NotificationChannelTemplateConfiguration `json:"templateConfiguration,omitempty"` // Type: slack, ms teams NotifyOnOk bool `json:"notifyOnOk"` @@ -233,14 +233,14 @@ type CustomNotification struct { } type SysdigCapture struct { - Name string `json:"name"` - Filters string `json:"filters,omitempty"` - Duration int `json:"duration"` - Type string `json:"type,omitempty"` - BucketName string `json:"bucketName"` - Folder string `json:"folder,omitempty"` - Enabled bool `json:"enabled"` - StorageID interface{} `json:"storageId,omitempty"` + Name string `json:"name"` + Filters string `json:"filters,omitempty"` + Duration int `json:"duration"` + Type string `json:"type,omitempty"` + BucketName string `json:"bucketName"` + Folder string `json:"folder,omitempty"` + Enabled bool `json:"enabled"` + StorageID any `json:"storageId,omitempty"` } type SegmentCondition struct { @@ -273,7 +273,7 @@ type Policy struct { Type string `json:"type"` Origin string `json:"origin"` Runbook string `json:"runbook"` - TemplateId int `json:"templateId"` + TemplateID int `json:"templateId"` TemplateVersion string `json:"templateVersion"` } @@ -293,10 +293,10 @@ type RuntimePolicyRuleDetails interface { } type RuntimePolicyRule struct { - Id *FlexInt `json:"id"` + ID *FlexInt `json:"id"` Name string `json:"name"` Origin *RuntimePolicyObjectOrigin `json:"origin"` - VersionId string `json:"versionId"` + VersionID string `json:"versionId"` Filename string `json:"filename"` Description string `json:"description"` Details RuntimePolicyRuleDetails `json:"details"` @@ -306,18 +306,16 @@ type RuntimePolicyRule struct { ModifiedOn int64 `json:"modifiedOn"` } -// TODO: This should be exported into a common package -// Copied from: https://github.com/draios/secure-backend/blob/main/policies/model/model_rules.go#L676C1-L779C2 func (r *RuntimePolicyRule) UnmarshalJSON(b []byte) error { type findType struct { RuleType string `json:"ruleType"` } findDetails := struct { FindType findType `json:"details"` - Id *FlexInt `json:"id"` + ID *FlexInt `json:"id"` Name string `json:"name"` Origin *RuntimePolicyObjectOrigin `json:"origin"` - VersionId string `json:"versionId"` + VersionID string `json:"versionId"` Filename string `json:"filename"` Description string `json:"description"` Tags []string `json:"tags"` @@ -333,21 +331,6 @@ func (r *RuntimePolicyRule) UnmarshalJSON(b []byte) error { var d RuntimePolicyRuleDetails switch findDetails.FindType.RuleType { - // case "FALCO": - // d = &FalcoRuleDetails{} - // case "CONTAINER": - // d = &ContainerImageRuleDetails{} - // case "FILESYSTEM": - // d = &FilesystemRuleDetails{} - // case "NETWORK": - // d = &NetworkRuleDetails{ - // AllInbound: true, - // AllOutbound: true, - // } - // case "PROCESS": - // d = &ProcessRuleDetails{} - // case "SYSCALL": - // d = &SyscallRuleDetails{} case "DRIFT": d = &DriftRuleDetails{} case "MACHINE_LEARNING": @@ -356,8 +339,6 @@ func (r *RuntimePolicyRule) UnmarshalJSON(b []byte) error { d = &AWSMLRuleDetails{} case "MALWARE": d = &MalwareRuleDetails{} - // case "OKTA_MACHINE_LEARNING": - // d = &OktaMLRuleDetails{} default: return errors.New("The field details has an unknown ruleType: " + findDetails.FindType.RuleType) } @@ -375,16 +356,16 @@ func (r *RuntimePolicyRule) UnmarshalJSON(b []byte) error { return err } - var findDetailsIdPtr *FlexInt - if findDetails.Id != nil { - findDetailsId := FlexInt(*findDetails.Id) - findDetailsIdPtr = &findDetailsId + var findDetailsIDPtr *FlexInt + if findDetails.ID != nil { + findDetailsID := FlexInt(*findDetails.ID) + findDetailsIDPtr = &findDetailsID } - r.Id = findDetailsIdPtr + r.ID = findDetailsIDPtr r.Name = findDetails.Name r.Origin = findDetails.Origin - r.VersionId = findDetails.VersionId + r.VersionID = findDetails.VersionID r.Filename = findDetails.Filename r.Description = findDetails.Description r.Tags = findDetails.Tags @@ -460,7 +441,6 @@ type PolicyRule struct { Enabled bool `json:"enabled"` } -// Did not add support storageId because FE does not support it yet type Action struct { AfterEventNs int `json:"afterEventNs,omitempty"` BeforeEventNs int `json:"beforeEventNs,omitempty"` @@ -472,6 +452,7 @@ type Action struct { IsLimitedToContainer bool `json:"isLimitedToContainer"` Type string `json:"type"` Msg *string `json:"msg,omitempty"` + // Note: Did not add support storageId because FE does not support it yet } type List struct { @@ -587,15 +568,15 @@ type Syscalls struct { } type Condition struct { - Condition string `json:"condition"` - Components []interface{} `json:"components"` + Condition string `json:"condition"` + Components []any `json:"components"` } type Exception struct { - Name string `json:"name"` - Fields interface{} `json:"fields,omitempty"` - Comps interface{} `json:"comps,omitempty"` - Values interface{} `json:"values,omitempty"` + Name string `json:"name"` + Fields any `json:"fields,omitempty"` + Comps any `json:"comps,omitempty"` + Values any `json:"values,omitempty"` } type CloudAccountSecure struct { @@ -671,7 +652,7 @@ type AlertV2Common struct { CustomNotificationTemplate *CustomNotificationTemplateV2 `json:"customNotificationTemplate,omitempty"` CaptureConfig *CaptureConfigV2 `json:"captureConfig,omitempty"` Links []AlertLinkV2 `json:"links"` - Labels map[string]interface{} `json:"labels,omitempty"` + Labels map[string]any `json:"labels,omitempty"` } type AlertV2ConfigPrometheus struct { @@ -877,14 +858,14 @@ type alertV2ChangeWrapper struct { } type CloudAccountCredentialsMonitor struct { - AccountId string `json:"accountId"` + AccountID string `json:"accountId"` RoleName string `json:"roleName"` SecretKey string `json:"key"` - AccessKeyId string `json:"id"` + AccessKeyID string `json:"id"` } type CloudAccountMonitor struct { - Id int `json:"id"` + ID int `json:"id"` Platform string `json:"platform"` IntegrationType string `json:"integrationType"` Credentials CloudAccountCredentialsMonitor `json:"credentials"` @@ -908,15 +889,15 @@ type CloudCostConfiguration struct { } type CloudAccountCreatedForCost struct { - Id string `json:"id"` - CustomerId int `json:"customerId"` - ProviderId string `json:"providerId"` + ID string `json:"id"` + CustomerID int `json:"customerId"` + ProviderID string `json:"providerId"` Provider string `json:"provider"` SkipFetch bool `json:"skipFetch"` IntegrationType string `json:"integrationType"` CredentialsType string `json:"credentialsType"` RoleArn string `json:"roleArn"` - ExternalId string `json:"externalId"` + ExternalID string `json:"externalId"` } type cloudAccountWrapperMonitor struct { @@ -924,7 +905,7 @@ type cloudAccountWrapperMonitor struct { } type CloudConfigForCost struct { - AthenaProjectId string `json:"athenaProjectId"` + AthenaProjectID string `json:"athenaProjectId"` AthenaBucketName string `json:"athenaBucketName"` AthenaRegion string `json:"athenaRegion"` AthenaDatabaseName string `json:"athenaDatabaseName"` @@ -935,16 +916,16 @@ type CloudConfigForCost struct { } type CloudAccountCostProvider struct { - CustomerId int `json:"customerId"` - ProviderId string `json:"providerId"` + CustomerID int `json:"customerId"` + ProviderID string `json:"providerId"` Provider string `json:"provider"` - CredentialsId string `json:"credentialsId"` + CredentialsID string `json:"credentialsId"` Feature string `json:"feature"` Config CloudConfigForCost `json:"config"` Enabled bool `json:"enabled"` CredentialsType string `json:"credentialsType"` RoleArn string `json:"roleArn"` - ExternalId string `json:"externalId"` + ExternalID string `json:"externalId"` } type CloudAccountCostProviderWrapper struct { @@ -1011,7 +992,7 @@ type RequirementsGroup struct { type Requirement struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` - RequirementFolderId string `json:"requirementFolderId,omitempty"` + RequirementFolderID string `json:"requirementFolderId,omitempty"` Description string `json:"description,omitempty"` Controls []Control `json:"controls,omitempty"` Authors string `json:"authors,omitempty"` @@ -1118,7 +1099,7 @@ type IdentityContext struct { type SilenceRule struct { Name string `json:"name"` Enabled bool `json:"enabled"` - StartTs int64 `json:"startTs"` + StartTS int64 `json:"startTs"` DurationInSec int `json:"durationInSec"` Scope string `json:"scope,omitempty"` AlertIds []int `json:"alertIds,omitempty"` diff --git a/sysdig/internal/client/v2/model_dashboard.go b/sysdig/internal/client/v2/model_dashboard.go index 78f215060..a21adb23b 100644 --- a/sysdig/internal/client/v2/model_dashboard.go +++ b/sysdig/internal/client/v2/model_dashboard.go @@ -14,11 +14,11 @@ type Layout struct { } type QueryParams struct { - Severities []interface{} `json:"severities"` - AlertStatuses []interface{} `json:"alertStatuses"` - Categories []interface{} `json:"categories"` - Filter string `json:"filter"` - TeamScope bool `json:"teamScope"` + Severities []any `json:"severities"` + AlertStatuses []any `json:"alertStatuses"` + Categories []any `json:"categories"` + Filter string `json:"filter"` + TeamScope bool `json:"teamScope"` } type EventDisplaySettings struct { @@ -31,29 +31,29 @@ type Bottom struct { } type Left struct { - Enabled bool `json:"enabled"` - DisplayName interface{} `json:"displayName"` - Unit string `json:"unit"` - DisplayFormat string `json:"displayFormat"` - Decimals interface{} `json:"decimals"` - MinValue float64 `json:"minValue"` - MaxValue interface{} `json:"maxValue"` - MinInputFormat string `json:"minInputFormat"` - MaxInputFormat string `json:"maxInputFormat"` - Scale string `json:"scale"` + Enabled bool `json:"enabled"` + DisplayName any `json:"displayName"` + Unit string `json:"unit"` + DisplayFormat string `json:"displayFormat"` + Decimals any `json:"decimals"` + MinValue float64 `json:"minValue"` + MaxValue any `json:"maxValue"` + MinInputFormat string `json:"minInputFormat"` + MaxInputFormat string `json:"maxInputFormat"` + Scale string `json:"scale"` } type Right struct { - Enabled bool `json:"enabled"` - DisplayName interface{} `json:"displayName"` - Unit string `json:"unit"` - DisplayFormat string `json:"displayFormat"` - Decimals interface{} `json:"decimals"` - MinValue float64 `json:"minValue"` - MaxValue interface{} `json:"maxValue"` - MinInputFormat string `json:"minInputFormat"` - MaxInputFormat string `json:"maxInputFormat"` - Scale string `json:"scale"` + Enabled bool `json:"enabled"` + DisplayName any `json:"displayName"` + Unit string `json:"unit"` + DisplayFormat string `json:"displayFormat"` + Decimals any `json:"decimals"` + MinValue float64 `json:"minValue"` + MaxValue any `json:"maxValue"` + MinInputFormat string `json:"minInputFormat"` + MaxInputFormat string `json:"maxInputFormat"` + Scale string `json:"scale"` } type AxesConfiguration struct { @@ -63,12 +63,12 @@ type AxesConfiguration struct { } type LegendConfiguration struct { - Enabled bool `json:"enabled"` - Position string `json:"position"` - Layout string `json:"layout"` - ShowCurrent bool `json:"showCurrent"` - Width interface{} `json:"width"` - Height interface{} `json:"height"` + Enabled bool `json:"enabled"` + Position string `json:"position"` + Layout string `json:"layout"` + ShowCurrent bool `json:"showCurrent"` + Width any `json:"width"` + Height any `json:"height"` } type DisplayInfo struct { @@ -374,7 +374,7 @@ func (p *Panels) WithLayout(xPos, yPos, width, height int) (*Panels, error) { type NumberThresholds struct { Base NumberThresholdBase `json:"base"` - Values []interface{} `json:"values"` + Values []any `json:"values"` } type NumberThresholdBase struct { @@ -383,9 +383,9 @@ type NumberThresholdBase struct { } type TeamSharingOptions struct { - Type string `json:"type"` - UserTeamsRole string `json:"userTeamsRole"` - SelectedTeams []interface{} `json:"selectedTeams"` + Type string `json:"type"` + UserTeamsRole string `json:"userTeamsRole"` + SelectedTeams []any `json:"selectedTeams"` } type SharingOptions struct { @@ -399,24 +399,24 @@ type SharingMember struct { } type ScopeExpressionList struct { - Operand string `json:"operand"` - Operator string `json:"operator"` - DisplayName string `json:"displayName"` - Value []string `json:"value"` - Descriptor interface{} `json:"descriptor"` - IsVariable bool `json:"isVariable"` + Operand string `json:"operand"` + Operator string `json:"operator"` + DisplayName string `json:"displayName"` + Value []string `json:"value"` + Descriptor any `json:"descriptor"` + IsVariable bool `json:"isVariable"` } type Dashboard struct { Version int `json:"version,omitempty"` - CustomerID interface{} `json:"customerId"` + CustomerID any `json:"customerId"` TeamID int `json:"teamId"` Schema int `json:"schema"` AutoCreated bool `json:"autoCreated"` PublicToken string `json:"publicToken"` ScopeExpressionList []*ScopeExpressionList `json:"scopeExpressionList"` Layout []*Layout `json:"layout"` - TeamScope interface{} `json:"teamScope"` + TeamScope any `json:"teamScope"` EventDisplaySettings EventDisplaySettings `json:"eventDisplaySettings"` ID int `json:"id,omitempty"` Name string `json:"name"` @@ -429,7 +429,7 @@ type Dashboard struct { CreatedOn int64 `json:"createdOn"` ModifiedOn int64 `json:"modifiedOn"` Panels []*Panels `json:"panels"` - TeamScopeExpressionList []interface{} `json:"teamScopeExpressionList"` + TeamScopeExpressionList []any `json:"teamScopeExpressionList"` CreatedOnDate string `json:"createdOnDate"` ModifiedOnDate string `json:"modifiedOnDate"` TeamSharingOptions TeamSharingOptions `json:"teamSharingOptions"` diff --git a/sysdig/internal/client/v2/notification_channels.go b/sysdig/internal/client/v2/notification_channels.go index 44ee8a9c3..03448cc36 100644 --- a/sysdig/internal/client/v2/notification_channels.go +++ b/sysdig/internal/client/v2/notification_channels.go @@ -8,33 +8,37 @@ import ( ) const ( - GetNotificationChannels = "%s/api/notificationChannels" - GetNotificationChannel = "%s/api/notificationChannels/%d" + getNotificationChannels = "%s/api/notificationChannels" + getNotificationChannel = "%s/api/notificationChannels/%d" ) -var NotificationChannelNotFound = errors.New("notification channel not found") +var ErrNotificationChannelNotFound = errors.New("notification channel not found") type NotificationChannelInterface interface { Base - GetNotificationChannelById(ctx context.Context, id int) (NotificationChannel, error) + GetNotificationChannelByID(ctx context.Context, id int) (NotificationChannel, error) GetNotificationChannelByName(ctx context.Context, name string) (NotificationChannel, error) CreateNotificationChannel(ctx context.Context, channel NotificationChannel) (NotificationChannel, error) UpdateNotificationChannel(ctx context.Context, channel NotificationChannel) (NotificationChannel, error) DeleteNotificationChannel(ctx context.Context, id int) error } -func (client *Client) GetNotificationChannelById(ctx context.Context, id int) (NotificationChannel, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetNotificationChannelUrl(id), nil) +func (c *Client) GetNotificationChannelByID(ctx context.Context, id int) (nc NotificationChannel, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getNotificationChannelURL(id), nil) if err != nil { return NotificationChannel{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode == http.StatusNotFound { - return NotificationChannel{}, NotificationChannelNotFound + return NotificationChannel{}, ErrNotificationChannelNotFound } if response.StatusCode != http.StatusOK { - return NotificationChannel{}, client.ErrorFromResponse(response) + return NotificationChannel{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[notificationChannelWrapper](response.Body) @@ -43,21 +47,25 @@ func (client *Client) GetNotificationChannelById(ctx context.Context, id int) (N } if wrapper.NotificationChannel.ID == 0 { - return NotificationChannel{}, fmt.Errorf("NotificationChannel with ID: %d does not exists", id) + return NotificationChannel{}, fmt.Errorf("notificationChannel with ID: %d does not exists", id) } return wrapper.NotificationChannel, nil } -func (client *Client) GetNotificationChannelByName(ctx context.Context, name string) (NotificationChannel, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetNotificationChannelsUrl(), nil) +func (c *Client) GetNotificationChannelByName(ctx context.Context, name string) (nc NotificationChannel, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getNotificationChannelsURL(), nil) if err != nil { return NotificationChannel{}, nil } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return NotificationChannel{}, client.ErrorFromResponse(response) + return NotificationChannel{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[notificationChannelListWrapper](response.Body) @@ -74,7 +82,7 @@ func (client *Client) GetNotificationChannelByName(ctx context.Context, name str return NotificationChannel{}, fmt.Errorf("notification channel with name: %s does not exist", name) } -func (client *Client) CreateNotificationChannel(ctx context.Context, channel NotificationChannel) (NotificationChannel, error) { +func (c *Client) CreateNotificationChannel(ctx context.Context, channel NotificationChannel) (nc NotificationChannel, err error) { payload, err := Marshal(notificationChannelWrapper{ NotificationChannel: channel, }) @@ -82,14 +90,18 @@ func (client *Client) CreateNotificationChannel(ctx context.Context, channel Not return NotificationChannel{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.GetNotificationChannelsUrl(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getNotificationChannelsURL(), payload) if err != nil { return NotificationChannel{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return NotificationChannel{}, client.ErrorFromResponse(response) + return NotificationChannel{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[notificationChannelWrapper](response.Body) @@ -100,7 +112,7 @@ func (client *Client) CreateNotificationChannel(ctx context.Context, channel Not return wrapper.NotificationChannel, nil } -func (client *Client) UpdateNotificationChannel(ctx context.Context, channel NotificationChannel) (NotificationChannel, error) { +func (c *Client) UpdateNotificationChannel(ctx context.Context, channel NotificationChannel) (nc NotificationChannel, err error) { payload, err := Marshal(notificationChannelWrapper{ NotificationChannel: channel, }) @@ -108,14 +120,18 @@ func (client *Client) UpdateNotificationChannel(ctx context.Context, channel Not return NotificationChannel{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.GetNotificationChannelUrl(channel.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getNotificationChannelURL(channel.ID), payload) if err != nil { return NotificationChannel{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return NotificationChannel{}, client.ErrorFromResponse(response) + return NotificationChannel{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[notificationChannelWrapper](response.Body) @@ -126,24 +142,28 @@ func (client *Client) UpdateNotificationChannel(ctx context.Context, channel Not return wrapper.NotificationChannel, nil } -func (client *Client) DeleteNotificationChannel(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.GetNotificationChannelUrl(id), nil) +func (c *Client) DeleteNotificationChannel(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getNotificationChannelURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetNotificationChannelsUrl() string { - return fmt.Sprintf(GetNotificationChannels, client.config.url) +func (c *Client) getNotificationChannelsURL() string { + return fmt.Sprintf(getNotificationChannels, c.config.url) } -func (client *Client) GetNotificationChannelUrl(id int) string { - return fmt.Sprintf(GetNotificationChannel, client.config.url, id) +func (c *Client) getNotificationChannelURL(id int) string { + return fmt.Sprintf(getNotificationChannel, c.config.url, id) } diff --git a/sysdig/internal/client/v2/onboarding.go b/sysdig/internal/client/v2/onboarding.go index c56f39f39..bed76ed8b 100644 --- a/sysdig/internal/client/v2/onboarding.go +++ b/sysdig/internal/client/v2/onboarding.go @@ -27,99 +27,127 @@ type OnboardingSecureInterface interface { GetTrustedOracleAppSecure(ctx context.Context, app string) (map[string]string, error) } -func (client *Client) GetTrustedCloudIdentitySecure(ctx context.Context, provider string) (string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedIdentityPath, client.config.url, provider), nil) +func (c *Client) GetTrustedCloudIdentitySecure(ctx context.Context, provider string) (identity string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedIdentityPath, c.config.url, provider), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return "", client.ErrorFromResponse(response) + return "", c.ErrorFromResponse(response) } return Unmarshal[string](response.Body) } -func (client *Client) GetTrustedAzureAppSecure(ctx context.Context, app string) (map[string]string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedAzureAppPath, client.config.url, app), nil) +func (c *Client) GetTrustedAzureAppSecure(ctx context.Context, app string) (trusted map[string]string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedAzureAppPath, c.config.url, app), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[map[string]string](response.Body) } -func (client *Client) GetTenantExternalIDSecure(ctx context.Context) (string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTenantExternaIDPath, client.config.url), nil) +func (c *Client) GetTenantExternalIDSecure(ctx context.Context) (tenant string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTenantExternaIDPath, c.config.url), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return "", client.ErrorFromResponse(response) + return "", c.ErrorFromResponse(response) } return Unmarshal[string](response.Body) } -func (client *Client) GetAgentlessScanningAssetsSecure(ctx context.Context) (map[string]interface{}, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingAgentlessScanningAssetsPath, client.config.url), nil) +func (c *Client) GetAgentlessScanningAssetsSecure(ctx context.Context) (assets map[string]any, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingAgentlessScanningAssetsPath, c.config.url), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - return Unmarshal[map[string]interface{}](response.Body) + return Unmarshal[map[string]any](response.Body) } -func (client *Client) GetCloudIngestionAssetsSecure(ctx context.Context, provider, providerID, componentType string) (map[string]interface{}, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingCloudIngestionAssetsPath, client.config.url, provider, providerID, componentType), nil) +func (c *Client) GetCloudIngestionAssetsSecure(ctx context.Context, provider, providerID, componentType string) (assets map[string]any, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingCloudIngestionAssetsPath, c.config.url, provider, providerID, componentType), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - return Unmarshal[map[string]interface{}](response.Body) + return Unmarshal[map[string]any](response.Body) } -func (client *Client) GetTrustedCloudRegulationAssetsSecure(ctx context.Context, provider string) (map[string]string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedRegulationAssetsPath, client.config.url, provider), nil) +func (c *Client) GetTrustedCloudRegulationAssetsSecure(ctx context.Context, provider string) (assets map[string]string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedRegulationAssetsPath, c.config.url, provider), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[map[string]string](response.Body) } -func (client *Client) GetTrustedOracleAppSecure(ctx context.Context, app string) (map[string]string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedOracleAppPath, client.config.url, app), nil) +func (c *Client) GetTrustedOracleAppSecure(ctx context.Context, app string) (trustedApp map[string]string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(onboardingTrustedOracleAppPath, c.config.url, app), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[map[string]string](response.Body) diff --git a/sysdig/internal/client/v2/organization.go b/sysdig/internal/client/v2/organization.go index 54e8102ad..f61d9f015 100644 --- a/sysdig/internal/client/v2/organization.go +++ b/sysdig/internal/client/v2/organization.go @@ -20,100 +20,113 @@ type OrganizationSecureInterface interface { UpdateOrganizationSecure(ctx context.Context, orgID string, org *OrganizationSecure) (*OrganizationSecure, string, error) } -func (client *Client) CreateOrganizationSecure(ctx context.Context, org *OrganizationSecure) (*OrganizationSecure, string, error) { - payload, err := client.marshalCloudauthProto(org) +func (c *Client) CreateOrganizationSecure(ctx context.Context, org *OrganizationSecure) (organization *OrganizationSecure, errString string, err error) { + payload, err := c.marshalCloudauthProto(org) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPost, client.organizationsURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.organizationsURL(), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated && response.StatusCode != http.StatusAccepted { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } - organization := &OrganizationSecure{} - err = client.unmarshalCloudauthProto(response.Body, organization) + err = c.unmarshalCloudauthProto(response.Body, organization) if err != nil { return nil, "", err } return organization, "", nil } -func (client *Client) GetOrganizationSecure(ctx context.Context, orgID string) (*OrganizationSecure, string, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.organizationURL(orgID), nil) +func (c *Client) GetOrganizationSecure(ctx context.Context, orgID string) (organization *OrganizationSecure, errString string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.organizationURL(orgID), nil) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } - organization := &OrganizationSecure{} - err = client.unmarshalCloudauthProto(response.Body, organization) + err = c.unmarshalCloudauthProto(response.Body, organization) if err != nil { return nil, "", err } return organization, "", nil } -func (client *Client) DeleteOrganizationSecure(ctx context.Context, orgID string) (string, error) { - response, err := client.requester.Request(ctx, http.MethodDelete, client.organizationURL(orgID), nil) +func (c *Client) DeleteOrganizationSecure(ctx context.Context, orgID string) (errString string, err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.organizationURL(orgID), nil) if err != nil { return "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return errStatus, err } return "", nil } -func (client *Client) UpdateOrganizationSecure(ctx context.Context, orgID string, org *OrganizationSecure) (*OrganizationSecure, string, error) { +func (c *Client) UpdateOrganizationSecure(ctx context.Context, orgID string, org *OrganizationSecure) (organization *OrganizationSecure, errString string, err error) { payload, err := Marshal(org) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPut, client.organizationURL(orgID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.organizationURL(orgID), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated && response.StatusCode != http.StatusAccepted { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } - organization := &OrganizationSecure{} - err = client.unmarshalCloudauthProto(response.Body, organization) + err = c.unmarshalCloudauthProto(response.Body, organization) if err != nil { return nil, "", err } return organization, "", nil } -func (client *Client) organizationsURL() string { - url := fmt.Sprintf(organizationsPath, client.config.url) +func (c *Client) organizationsURL() string { + url := fmt.Sprintf(organizationsPath, c.config.url) if os.Getenv("SYSDIG_ORG_API_ASYNC") == "true" { url += "?async=true" } return url } -func (client *Client) organizationURL(orgId string) string { - url := fmt.Sprintf(organizationPath, client.config.url, orgId) +func (c *Client) organizationURL(orgID string) string { + url := fmt.Sprintf(organizationPath, c.config.url, orgID) if os.Getenv("SYSDIG_ORG_API_ASYNC") == "true" { url += "?async=true" } diff --git a/sysdig/internal/client/v2/organization_test.go b/sysdig/internal/client/v2/organization_test.go index afdc6e1ee..c445da428 100644 --- a/sysdig/internal/client/v2/organization_test.go +++ b/sysdig/internal/client/v2/organization_test.go @@ -1,5 +1,3 @@ -//go:build unit - package v2 import ( @@ -34,7 +32,7 @@ func TestMarshalOrg(t *testing.T) { } marshaled := buf.String() - if strings.Replace(marshaled, " ", "", -1) != strings.Replace(expected, " ", "", -1) { + if strings.ReplaceAll(marshaled, " ", "") != strings.ReplaceAll(expected, " ", "") { t.Errorf("expected %v, got %v", expected, marshaled) } } diff --git a/sysdig/internal/client/v2/permission.go b/sysdig/internal/client/v2/permission.go index 66d16c02e..34206d092 100644 --- a/sysdig/internal/client/v2/permission.go +++ b/sysdig/internal/client/v2/permission.go @@ -7,7 +7,7 @@ import ( "strings" ) -const PermissionsURL = "%s/api/permissions/%s/dependencies?requestedPermissions=%s" +const permissionsURL = "%s/api/permissions/%s/dependencies?requestedPermissions=%s" type CustomRolePermissionInterface interface { Base @@ -15,28 +15,27 @@ type CustomRolePermissionInterface interface { GetPermissionsDependencies(ctx context.Context, product Product, permissions []string) ([]Dependency, error) } -func (client *Client) GetPermissionsDependencies(ctx context.Context, product Product, permissions []string) ([]Dependency, error) { +func (c *Client) GetPermissionsDependencies(ctx context.Context, product Product, permissions []string) ([]Dependency, error) { segments := map[Product]string{MonitorProduct: "monitor", SecureProduct: "secure"} - url := fmt.Sprintf(PermissionsURL, client.config.url, segments[product], strings.Join(permissions, ",")) + url := fmt.Sprintf(permissionsURL, c.config.url, segments[product], strings.Join(permissions, ",")) - return client.getPermissionsDependencies(ctx, url) + return c.getPermissionsDependencies(ctx, url) } -func (client *Client) getPermissionsDependencies(ctx context.Context, url string) ([]Dependency, error) { - response, err := client.requester.Request(ctx, http.MethodGet, url, nil) +func (c *Client) getPermissionsDependencies(ctx context.Context, url string) (dependencies []Dependency, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, url, nil) if err != nil { - return []Dependency{}, err + return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []Dependency{}, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - dependencies, err := Unmarshal[Dependencies](response.Body) - if err != nil { - return []Dependency{}, err - } - - return dependencies, nil + return Unmarshal[Dependencies](response.Body) } diff --git a/sysdig/internal/client/v2/policies.go b/sysdig/internal/client/v2/policies.go index f0ad1fe42..5fb3d3c11 100644 --- a/sysdig/internal/client/v2/policies.go +++ b/sysdig/internal/client/v2/policies.go @@ -4,17 +4,15 @@ import ( "context" "fmt" "net/http" - - "github.com/pkg/errors" ) const ( - CreatePolicyPath = "%s/api/v2/policies?skipPolicyV2Msg=%t" - DeletePolicyPath = "%s/api/v2/policies/%d?skipPolicyV2Msg=%t" - UpdatePolicyPath = "%s/api/v2/policies/%d?skipPolicyV2Msg=%t" - GetPolicyPath = "%s/api/v2/policies/%d" - GetPoliciesPath = "%s/api/v2/policies" - SendPoliciesToAgentsPath = "%s/api/v2/policies/actions?action=forwardPolicyV2Msg" + createPolicyPath = "%s/api/v2/policies?skipPolicyV2Msg=%t" + deletePolicyPath = "%s/api/v2/policies/%d?skipPolicyV2Msg=%t" + updatePolicyPath = "%s/api/v2/policies/%d?skipPolicyV2Msg=%t" + getPolicyPath = "%s/api/v2/policies/%d" + getPoliciesPath = "%s/api/v2/policies" + sendPoliciesToAgentsPath = "%s/api/v2/policies/actions?action=forwardPolicyV2Msg" ) type PolicyInterface interface { @@ -27,70 +25,86 @@ type PolicyInterface interface { SendPoliciesToAgents(ctx context.Context) error } -func (client *Client) CreatePolicy(ctx context.Context, policy Policy) (Policy, error) { +func (c *Client) CreatePolicy(ctx context.Context, policy Policy) (createdPolicy Policy, err error) { payload, err := Marshal(policy) if err != nil { return Policy{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreatePolicyURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createPolicyURL(), payload) if err != nil { return Policy{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Policy{}, client.ErrorFromResponse(response) + return Policy{}, c.ErrorFromResponse(response) } return Unmarshal[Policy](response.Body) } -func (client *Client) DeletePolicy(ctx context.Context, policyID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeletePolicyURL(policyID), nil) +func (c *Client) DeletePolicy(ctx context.Context, policyID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deletePolicyURL(policyID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) UpdatePolicy(ctx context.Context, policy Policy) (Policy, error) { +func (c *Client) UpdatePolicy(ctx context.Context, policy Policy) (updatedPolicy Policy, err error) { payload, err := Marshal(policy) if err != nil { return Policy{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdatePolicyURL(policy.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updatePolicyURL(policy.ID), payload) if err != nil { return Policy{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Policy{}, client.ErrorFromResponse(response) + return Policy{}, c.ErrorFromResponse(response) } return Unmarshal[Policy](response.Body) } -func (client *Client) GetPolicyByID(ctx context.Context, policyID int) (Policy, int, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetPolicyURL(policyID), nil) +func (c *Client) GetPolicyByID(ctx context.Context, policyID int) (policy Policy, statusCode int, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getPolicyURL(policyID), nil) if err != nil { return Policy{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Policy{}, response.StatusCode, client.ErrorFromResponse(response) + return Policy{}, response.StatusCode, c.ErrorFromResponse(response) } - policy, err := Unmarshal[Policy](response.Body) + policy, err = Unmarshal[Policy](response.Body) if err != nil { return Policy{}, 0, err } @@ -98,18 +112,22 @@ func (client *Client) GetPolicyByID(ctx context.Context, policyID int) (Policy, return policy, http.StatusOK, nil } -func (client *Client) GetPolicies(ctx context.Context) ([]Policy, int, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetPoliciesURL(), nil) +func (c *Client) GetPolicies(ctx context.Context) (policies []Policy, statusCode int, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getPoliciesURL(), nil) if err != nil { return []Policy{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []Policy{}, response.StatusCode, client.ErrorFromResponse(response) + return []Policy{}, response.StatusCode, c.ErrorFromResponse(response) } - policies, err := Unmarshal[[]Policy](response.Body) + policies, err = Unmarshal[[]Policy](response.Body) if err != nil { return []Policy{}, 0, err } @@ -117,42 +135,46 @@ func (client *Client) GetPolicies(ctx context.Context) ([]Policy, int, error) { return policies, http.StatusOK, nil } -func (client *Client) SendPoliciesToAgents(ctx context.Context) error { - if client.config.secureSkipPolicyV2Msg { +func (c *Client) SendPoliciesToAgents(ctx context.Context) (err error) { + if c.config.secureSkipPolicyV2Msg { // We only need to send policies if we've been configured to skip sending them during updates - response, err := client.requester.Request(ctx, http.MethodPost, client.SendPoliciesToAgentsURL(), nil) + response, err := c.requester.Request(ctx, http.MethodPost, c.sendPoliciesToAgentsURL(), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return errors.Errorf("Unexpected response when sending policies to agents: %s", response.Status) + return fmt.Errorf("unexpected response when sending policies to agents: %s", response.Status) } } return nil } -func (client *Client) CreatePolicyURL() string { - return fmt.Sprintf(CreatePolicyPath, client.config.url, client.config.secureSkipPolicyV2Msg) +func (c *Client) createPolicyURL() string { + return fmt.Sprintf(createPolicyPath, c.config.url, c.config.secureSkipPolicyV2Msg) } -func (client *Client) DeletePolicyURL(policyID int) string { - return fmt.Sprintf(DeletePolicyPath, client.config.url, policyID, client.config.secureSkipPolicyV2Msg) +func (c *Client) deletePolicyURL(policyID int) string { + return fmt.Sprintf(deletePolicyPath, c.config.url, policyID, c.config.secureSkipPolicyV2Msg) } -func (client *Client) UpdatePolicyURL(policyID int) string { - return fmt.Sprintf(UpdatePolicyPath, client.config.url, policyID, client.config.secureSkipPolicyV2Msg) +func (c *Client) updatePolicyURL(policyID int) string { + return fmt.Sprintf(updatePolicyPath, c.config.url, policyID, c.config.secureSkipPolicyV2Msg) } -func (client *Client) GetPolicyURL(policyID int) string { - return fmt.Sprintf(GetPolicyPath, client.config.url, policyID) +func (c *Client) getPolicyURL(policyID int) string { + return fmt.Sprintf(getPolicyPath, c.config.url, policyID) } -func (client *Client) GetPoliciesURL() string { - return fmt.Sprintf(GetPoliciesPath, client.config.url) +func (c *Client) getPoliciesURL() string { + return fmt.Sprintf(getPoliciesPath, c.config.url) } -func (client *Client) SendPoliciesToAgentsURL() string { - return fmt.Sprintf(SendPoliciesToAgentsPath, client.config.url) +func (c *Client) sendPoliciesToAgentsURL() string { + return fmt.Sprintf(sendPoliciesToAgentsPath, c.config.url) } diff --git a/sysdig/internal/client/v2/posture_accept_risk.go b/sysdig/internal/client/v2/posture_accept_risk.go index 20b25a26d..6b61e7e36 100644 --- a/sysdig/internal/client/v2/posture_accept_risk.go +++ b/sysdig/internal/client/v2/posture_accept_risk.go @@ -7,10 +7,10 @@ import ( ) const ( - AcceptPostureRiskCreatePath = "%s/api/cspm/v1/compliance/risk-acceptances" - AcceptPostureRiskGetPath = "%s/api/cspm/v1/compliance/risk-acceptances/%s" - AcceptPostureRiskDelete = "%s/api/cspm/v1/compliance/violations/revoke" - AcceptPostureRiskUpdate = "%s/api/cspm/v1/compliance/risk-acceptances/%s" + acceptPostureRiskCreatePath = "%s/api/cspm/v1/compliance/risk-acceptances" + acceptPostureRiskGetPath = "%s/api/cspm/v1/compliance/risk-acceptances/%s" + acceptPostureRiskDelete = "%s/api/cspm/v1/compliance/violations/revoke" + acceptPostureRiskUpdate = "%s/api/cspm/v1/compliance/risk-acceptances/%s" ) type PostureAcceptRiskInterface interface { @@ -21,23 +21,26 @@ type PostureAcceptRiskInterface interface { UpdateAcceptancePostureRisk(ctx context.Context, p *UpdateAccepetPostureRiskRequest) (*AcceptPostureRisk, string, error) } -func (c *Client) SaveAcceptPostureRisk(ctx context.Context, p *AccepetPostureRiskRequest) (*AcceptPostureRiskResponse, string, error) { +func (c *Client) SaveAcceptPostureRisk(ctx context.Context, p *AccepetPostureRiskRequest) (risk *AcceptPostureRiskResponse, errString string, err error) { payload, err := Marshal(p) if err != nil { return nil, "", err } - response, err := c.requester.Request(ctx, http.MethodPost, c.getPostureControlURL(AcceptPostureRiskCreatePath), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getPostureControlURL(acceptPostureRiskCreatePath), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } resp, err := Unmarshal[AcceptPostureRiskResponse](response.Body) - if err != nil { return nil, "", err } @@ -45,12 +48,16 @@ func (c *Client) SaveAcceptPostureRisk(ctx context.Context, p *AccepetPostureRis return &resp, "", nil } -func (c *Client) GetAcceptancePostureRisk(ctx context.Context, id string) (*AcceptPostureRiskResponse, string, error) { - response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(AcceptPostureRiskGetPath, c.config.url, id), nil) +func (c *Client) GetAcceptancePostureRisk(ctx context.Context, id string) (risk *AcceptPostureRiskResponse, errString string, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(acceptPostureRiskGetPath, c.config.url, id), nil) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { errStatus, err := c.ErrorAndStatusFromResponse(response) @@ -64,17 +71,21 @@ func (c *Client) GetAcceptancePostureRisk(ctx context.Context, id string) (*Acce return &wrapper, "", nil } -func (c *Client) DeleteAcceptancePostureRisk(ctx context.Context, p *DeleteAcceptPostureRisk) error { +func (c *Client) DeleteAcceptancePostureRisk(ctx context.Context, p *DeleteAcceptPostureRisk) (err error) { payload, err := Marshal(p) if err != nil { return err } - response, err := c.requester.Request(ctx, http.MethodPost, fmt.Sprintf(AcceptPostureRiskDelete, c.config.url), payload) + response, err := c.requester.Request(ctx, http.MethodPost, fmt.Sprintf(acceptPostureRiskDelete, c.config.url), payload) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { return c.ErrorFromResponse(response) @@ -83,16 +94,20 @@ func (c *Client) DeleteAcceptancePostureRisk(ctx context.Context, p *DeleteAccep return nil } -func (c *Client) UpdateAcceptancePostureRisk(ctx context.Context, p *UpdateAccepetPostureRiskRequest) (*AcceptPostureRisk, string, error) { +func (c *Client) UpdateAcceptancePostureRisk(ctx context.Context, p *UpdateAccepetPostureRiskRequest) (risk *AcceptPostureRisk, errString string, err error) { payload, err := Marshal(p) if err != nil { return nil, "", err } - response, err := c.requester.Request(ctx, http.MethodPatch, fmt.Sprintf(AcceptPostureRiskUpdate, c.config.url, p.AcceptanceID), payload) + response, err := c.requester.Request(ctx, http.MethodPatch, fmt.Sprintf(acceptPostureRiskUpdate, c.config.url, p.AcceptanceID), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err diff --git a/sysdig/internal/client/v2/posture_controls.go b/sysdig/internal/client/v2/posture_controls.go index 2dc997697..f3af9507a 100644 --- a/sysdig/internal/client/v2/posture_controls.go +++ b/sysdig/internal/client/v2/posture_controls.go @@ -7,28 +7,32 @@ import ( ) const ( - PostureControlSavePath = "%s/api/cspm/v1/policy/controls" - PostureControlGetPath = "%s/api/cspm/v1/policy/controls/view/%d" - PostureControlDeletePath = "%s/api/cspm/v1/policy/controls/%d" + postureControlSavePath = "%s/api/cspm/v1/policy/controls" + postureControlGetPath = "%s/api/cspm/v1/policy/controls/view/%d" + postureControlDeletePath = "%s/api/cspm/v1/policy/controls/%d" ) type PostureControlInterface interface { Base CreateOrUpdatePostureControl(ctx context.Context, p *SaveControlRequest) (*PostureControl, string, error) - GetPostureControl(ctx context.Context, id int64) (*PostureControl, error) - DeletePostureControl(ctx context.Context, id int64) error + GetPostureControlByID(ctx context.Context, id int64) (*PostureControl, error) + DeletePostureControlByID(ctx context.Context, id int64) error } -func (c *Client) CreateOrUpdatePostureControl(ctx context.Context, p *SaveControlRequest) (*PostureControl, string, error) { +func (c *Client) CreateOrUpdatePostureControl(ctx context.Context, p *SaveControlRequest) (control *PostureControl, status string, err error) { payload, err := Marshal(p) if err != nil { return nil, "", err } - response, err := c.requester.Request(ctx, http.MethodPost, c.getPostureControlURL(PostureControlSavePath), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getPostureControlURL(postureControlSavePath), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err @@ -38,15 +42,18 @@ func (c *Client) CreateOrUpdatePostureControl(ctx context.Context, p *SaveContro return nil, "", err } return &resp.Data, "", nil - } -func (c *Client) GetPostureControl(ctx context.Context, id int64) (*PostureControl, error) { - response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(PostureControlGetPath, c.config.url, id), nil) +func (c *Client) GetPostureControlByID(ctx context.Context, id int64) (control *PostureControl, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(postureControlGetPath, c.config.url, id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { return nil, c.ErrorFromResponse(response) @@ -58,12 +65,16 @@ func (c *Client) GetPostureControl(ctx context.Context, id int64) (*PostureContr return &wrapper.Data, nil } -func (c *Client) DeletePostureControl(ctx context.Context, id int64) error { - response, err := c.requester.Request(ctx, http.MethodDelete, fmt.Sprintf(PostureControlDeletePath, c.config.url, id), nil) +func (c *Client) DeletePostureControlByID(ctx context.Context, id int64) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, fmt.Sprintf(postureControlDeletePath, c.config.url, id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { return c.ErrorFromResponse(response) @@ -71,6 +82,7 @@ func (c *Client) DeletePostureControl(ctx context.Context, id int64) error { return nil } + func (c *Client) getPostureControlURL(path string) string { return fmt.Sprintf(path, c.config.url) } diff --git a/sysdig/internal/client/v2/posture_policies.go b/sysdig/internal/client/v2/posture_policies.go index e1f4a375b..3f4f5229a 100644 --- a/sysdig/internal/client/v2/posture_policies.go +++ b/sysdig/internal/client/v2/posture_policies.go @@ -7,29 +7,33 @@ import ( ) const ( - PosturePolicyListPath = "%s/api/cspm/v1/policy/policies/list" - PosturePolicyCreatePath = "%s/api/cspm/v1/policy" - PosturePolicyGetPath = "%s/api/cspm/v1/policy/posture/policies/%d?include_controls=true" - PosturePolicyDeletePath = "%s/api/cspm/v1/policy/policies/%d" + posturePolicyListPath = "%s/api/cspm/v1/policy/policies/list" + posturePolicyCreatePath = "%s/api/cspm/v1/policy" + posturePolicyGetPath = "%s/api/cspm/v1/policy/posture/policies/%d?include_controls=true" + posturePolicyDeletePath = "%s/api/cspm/v1/policy/policies/%d" ) type PosturePolicyInterface interface { Base ListPosturePolicies(ctx context.Context) ([]PosturePolicy, error) CreateOrUpdatePosturePolicy(ctx context.Context, p *CreatePosturePolicy) (*FullPosturePolicy, string, error) - GetPosturePolicy(ctx context.Context, id int64) (*FullPosturePolicy, error) + GetPosturePolicyByID(ctx context.Context, id int64) (*FullPosturePolicy, error) DeletePosturePolicy(ctx context.Context, id int64) error } -func (client *Client) ListPosturePolicies(ctx context.Context) ([]PosturePolicy, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getPosturePolicyURL(PosturePolicyListPath), nil) +func (c *Client) ListPosturePolicies(ctx context.Context) (policies []PosturePolicy, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getPosturePolicyURL(posturePolicyListPath), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } resp, err := Unmarshal[PostureZonePolicyListResponse](response.Body) @@ -40,18 +44,22 @@ func (client *Client) ListPosturePolicies(ctx context.Context) ([]PosturePolicy, return resp.Data, nil } -func (client *Client) CreateOrUpdatePosturePolicy(ctx context.Context, p *CreatePosturePolicy) (*FullPosturePolicy, string, error) { +func (c *Client) CreateOrUpdatePosturePolicy(ctx context.Context, p *CreatePosturePolicy) (policy *FullPosturePolicy, errString string, err error) { payload, err := Marshal(p) if err != nil { return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getPosturePolicyURL(PosturePolicyCreatePath), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getPosturePolicyURL(posturePolicyCreatePath), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } resp, err := Unmarshal[FullPosturePolicyResponse](response.Body) @@ -61,12 +69,16 @@ func (client *Client) CreateOrUpdatePosturePolicy(ctx context.Context, p *Create return &resp.Data, "", nil } -func (client *Client) GetPosturePolicy(ctx context.Context, id int64) (*FullPosturePolicy, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getPolicyUrl(id), nil) +func (c *Client) GetPosturePolicyByID(ctx context.Context, id int64) (policy *FullPosturePolicy, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getPosturePolicyURLForID(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() wrapper, err := Unmarshal[FullPosturePolicyResponse](response.Body) if err != nil { @@ -75,28 +87,32 @@ func (client *Client) GetPosturePolicy(ctx context.Context, id int64) (*FullPost return &wrapper.Data, nil } -func (client *Client) DeletePosturePolicy(ctx context.Context, id int64) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.deletePolicyUrl(id), nil) +func (c *Client) DeletePosturePolicy(ctx context.Context, id int64) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deletePosturePolicyURLForID(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getPolicyUrl(id int64) string { - return fmt.Sprintf(PosturePolicyGetPath, client.config.url, id) +func (c *Client) getPosturePolicyURLForID(id int64) string { + return fmt.Sprintf(posturePolicyGetPath, c.config.url, id) } -func (client *Client) deletePolicyUrl(id int64) string { - return fmt.Sprintf(PosturePolicyDeletePath, client.config.url, id) +func (c *Client) deletePosturePolicyURLForID(id int64) string { + return fmt.Sprintf(posturePolicyDeletePath, c.config.url, id) } -func (client *Client) getPosturePolicyURL(path string) string { - return fmt.Sprintf(path, client.config.url) +func (c *Client) getPosturePolicyURL(path string) string { + return fmt.Sprintf(path, c.config.url) } diff --git a/sysdig/internal/client/v2/posture_zones.go b/sysdig/internal/client/v2/posture_zones.go index 7a6fd245c..9828e7037 100644 --- a/sysdig/internal/client/v2/posture_zones.go +++ b/sysdig/internal/client/v2/posture_zones.go @@ -7,18 +7,18 @@ import ( ) const ( - PostureZonesPath = "%s/api/cspm/v1/policy/zones" - PostureZonePath = "%s/api/cspm/v1/policy/zones/%d" + postureZonesPath = "%s/api/cspm/v1/policy/zones" + postureZonePath = "%s/api/cspm/v1/policy/zones/%d" ) type PostureZoneInterface interface { Base CreateOrUpdatePostureZone(ctx context.Context, z *PostureZoneRequest) (*PostureZone, string, error) - GetPostureZone(ctx context.Context, id int) (*PostureZone, error) + GetPostureZoneByID(ctx context.Context, id int) (*PostureZone, error) DeletePostureZone(ctx context.Context, id int) error } -func (client *Client) CreateOrUpdatePostureZone(ctx context.Context, r *PostureZoneRequest) (*PostureZone, string, error) { +func (c *Client) CreateOrUpdatePostureZone(ctx context.Context, r *PostureZoneRequest) (zone *PostureZone, errStatus string, err error) { if r.ID == "" { r.ID = "0" } @@ -28,14 +28,18 @@ func (client *Client) CreateOrUpdatePostureZone(ctx context.Context, r *PostureZ return nil, "", err } - response, err := client.requester.Request(ctx, http.MethodPost, client.createPostureZoneURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createPostureZoneURL(), payload) if err != nil { return nil, "", err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated && response.StatusCode != http.StatusAccepted { - errStatus, err := client.ErrorAndStatusFromResponse(response) + errStatus, err := c.ErrorAndStatusFromResponse(response) return nil, errStatus, err } @@ -47,15 +51,19 @@ func (client *Client) CreateOrUpdatePostureZone(ctx context.Context, r *PostureZ return &wrapper.Data, "", nil } -func (client *Client) GetPostureZone(ctx context.Context, id int) (*PostureZone, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getPostureZoneURL(id), nil) +func (c *Client) GetPostureZoneByID(ctx context.Context, id int) (zone *PostureZone, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getPostureZoneURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[PostureZoneResponse](response.Body) if err != nil { @@ -65,24 +73,28 @@ func (client *Client) GetPostureZone(ctx context.Context, id int) (*PostureZone, return &wrapper.Data, nil } -func (client *Client) DeletePostureZone(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getPostureZoneURL(id), nil) +func (c *Client) DeletePostureZone(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getPostureZoneURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) createPostureZoneURL() string { - return fmt.Sprintf(PostureZonesPath, client.config.url) +func (c *Client) createPostureZoneURL() string { + return fmt.Sprintf(postureZonesPath, c.config.url) } -func (client *Client) getPostureZoneURL(id int) string { - return fmt.Sprintf(PostureZonePath, client.config.url, id) +func (c *Client) getPostureZoneURL(id int) string { + return fmt.Sprintf(postureZonePath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/rules.go b/sysdig/internal/client/v2/rules.go index b14070de5..e53c2c00a 100644 --- a/sysdig/internal/client/v2/rules.go +++ b/sysdig/internal/client/v2/rules.go @@ -8,15 +8,15 @@ import ( ) const ( - CreateRulePath = "%s/api/secure/rules?skipPolicyV2Msg=%t" - GetRuleByIDPath = "%s/api/secure/rules/%d" - UpdateRulePath = "%s/api/secure/rules/%d?skipPolicyV2Msg=%t" - DeleteURLPath = "%s/api/secure/rules/%d?skipPolicyV2Msg=%t" - GetRuleGroupPath = "%s/api/secure/rules/groups?name=%s&type=%s" - CreateStatefulRulePath = "%s/api/policies/v3/statefulRules" - UpdateStatefulRulePath = "%s/api/policies/v3/statefulRules/%d" - DeleteStatefulRulePath = "%s/api/policies/v3/statefulRules/%d" - GetStatefulRuleGroupPath = "%s/api/policies/v3/statefulRules/groups?name=%s&type=%s" + createRulePath = "%s/api/secure/rules?skipPolicyV2Msg=%t" + getRuleByIDPath = "%s/api/secure/rules/%d" + updateRulePath = "%s/api/secure/rules/%d?skipPolicyV2Msg=%t" + deleteURLPath = "%s/api/secure/rules/%d?skipPolicyV2Msg=%t" + getRuleGroupPath = "%s/api/secure/rules/groups?name=%s&type=%s" + createStatefulRulePath = "%s/api/policies/v3/statefulRules" + updateStatefulRulePath = "%s/api/policies/v3/statefulRules/%d" + deleteStatefulRulePath = "%s/api/policies/v3/statefulRules/%d" + getStatefulRuleGroupPath = "%s/api/policies/v3/statefulRules/groups?name=%s&type=%s" ) type RuleInterface interface { @@ -32,186 +32,222 @@ type RuleInterface interface { GetStatefulRuleGroup(ctx context.Context, ruleName string, ruleType string) ([]Rule, error) } -func (client *Client) CreateRule(ctx context.Context, rule Rule) (Rule, error) { +func (c *Client) CreateRule(ctx context.Context, rule Rule) (createdRule Rule, err error) { payload, err := Marshal(rule) if err != nil { return Rule{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateRuleURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createRuleURL(), payload) if err != nil { return Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Rule{}, client.ErrorFromResponse(response) + return Rule{}, c.ErrorFromResponse(response) } return Unmarshal[Rule](response.Body) } -func (client *Client) GetRuleByID(ctx context.Context, ruleID int) (Rule, int, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetRuleByIDURL(ruleID), nil) +func (c *Client) GetRuleByID(ctx context.Context, ruleID int) (rule Rule, statusCode int, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getRuleByIDURL(ruleID), nil) if err != nil { return Rule{}, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Rule{}, response.StatusCode, client.ErrorFromResponse(response) + return Rule{}, response.StatusCode, c.ErrorFromResponse(response) } - rule, err := Unmarshal[Rule](response.Body) + rule, err = Unmarshal[Rule](response.Body) return rule, 0, err } -func (client *Client) UpdateRule(ctx context.Context, rule Rule) (Rule, error) { +func (c *Client) UpdateRule(ctx context.Context, rule Rule) (updatedRule Rule, err error) { payload, err := Marshal(rule) if err != nil { return Rule{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateRuleURL(rule.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateRuleURL(rule.ID), payload) if err != nil { return Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Rule{}, client.ErrorFromResponse(response) + return Rule{}, c.ErrorFromResponse(response) } return Unmarshal[Rule](response.Body) } -func (client *Client) DeleteRule(ctx context.Context, ruleID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteRuleURL(ruleID), nil) +func (c *Client) DeleteRule(ctx context.Context, ruleID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteRuleURL(ruleID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) GetRuleGroup(ctx context.Context, ruleName string, ruleType string) ([]Rule, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetRuleGroupURL(ruleName, ruleType), nil) +func (c *Client) GetRuleGroup(ctx context.Context, ruleName string, ruleType string) (rules []Rule, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getRuleGroupURL(ruleName, ruleType), nil) if err != nil { return []Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []Rule{}, client.ErrorFromResponse(response) + return []Rule{}, c.ErrorFromResponse(response) } return Unmarshal[[]Rule](response.Body) } -func (client *Client) CreateRuleURL() string { - return fmt.Sprintf(CreateRulePath, client.config.url, client.config.secureSkipPolicyV2Msg) -} - -func (client *Client) GetRuleByIDURL(ruleID int) string { - return fmt.Sprintf(GetRuleByIDPath, client.config.url, ruleID) -} - -func (client *Client) UpdateRuleURL(ruleID int) string { - return fmt.Sprintf(UpdateRulePath, client.config.url, ruleID, client.config.secureSkipPolicyV2Msg) -} - -func (client *Client) DeleteRuleURL(ruleID int) string { - return fmt.Sprintf(DeleteURLPath, client.config.url, ruleID, client.config.secureSkipPolicyV2Msg) -} - -func (client *Client) GetRuleGroupURL(ruleName string, ruleType string) string { - return fmt.Sprintf(GetRuleGroupPath, client.config.url, url.QueryEscape(ruleName), url.QueryEscape(ruleType)) -} - -func (client *Client) CreateStatefulRuleURL() string { - return fmt.Sprintf(CreateStatefulRulePath, client.config.url) -} - -func (client *Client) UpdateStatefulRuleURL(ruleID int) string { - return fmt.Sprintf(UpdateStatefulRulePath, client.config.url, ruleID) -} - -func (client *Client) DeleteStatefulRuleURL(ruleID int) string { - return fmt.Sprintf(DeleteStatefulRulePath, client.config.url, ruleID) -} - -func (client *Client) GetStatefulRuleGroupURL(ruleName string, ruleType string) string { - return fmt.Sprintf(GetStatefulRuleGroupPath, client.config.url, url.QueryEscape(ruleName), url.QueryEscape(ruleType)) -} - -func (client *Client) CreateStatefulRule(ctx context.Context, rule Rule) (Rule, error) { +func (c *Client) CreateStatefulRule(ctx context.Context, rule Rule) (createdRule Rule, err error) { payload, err := Marshal(rule) if err != nil { return Rule{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateStatefulRuleURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createStatefulRuleURL(), payload) if err != nil { return Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Rule{}, client.ErrorFromResponse(response) + return Rule{}, c.ErrorFromResponse(response) } return Unmarshal[Rule](response.Body) } -func (client *Client) UpdateStatefulRule(ctx context.Context, rule Rule) (Rule, error) { +func (c *Client) UpdateStatefulRule(ctx context.Context, rule Rule) (updatedRule Rule, err error) { payload, err := Marshal(rule) if err != nil { return Rule{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateStatefulRuleURL(rule.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateStatefulRuleURL(rule.ID), payload) if err != nil { return Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Rule{}, client.ErrorFromResponse(response) + return Rule{}, c.ErrorFromResponse(response) } return Unmarshal[Rule](response.Body) } -func (client *Client) DeleteStatefulRule(ctx context.Context, ruleID int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteStatefulRuleURL(ruleID), nil) +func (c *Client) DeleteStatefulRule(ctx context.Context, ruleID int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteStatefulRuleURL(ruleID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return err } -func (client *Client) GetStatefulRuleGroup(ctx context.Context, ruleName string, ruleType string) ([]Rule, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetStatefulRuleGroupURL(ruleName, ruleType), nil) +func (c *Client) GetStatefulRuleGroup(ctx context.Context, ruleName string, ruleType string) (rules []Rule, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getStatefulRuleGroupURL(ruleName, ruleType), nil) if err != nil { return []Rule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return []Rule{}, client.ErrorFromResponse(response) + return []Rule{}, c.ErrorFromResponse(response) } return Unmarshal[[]Rule](response.Body) } + +func (c *Client) createRuleURL() string { + return fmt.Sprintf(createRulePath, c.config.url, c.config.secureSkipPolicyV2Msg) +} + +func (c *Client) getRuleByIDURL(ruleID int) string { + return fmt.Sprintf(getRuleByIDPath, c.config.url, ruleID) +} + +func (c *Client) updateRuleURL(ruleID int) string { + return fmt.Sprintf(updateRulePath, c.config.url, ruleID, c.config.secureSkipPolicyV2Msg) +} + +func (c *Client) deleteRuleURL(ruleID int) string { + return fmt.Sprintf(deleteURLPath, c.config.url, ruleID, c.config.secureSkipPolicyV2Msg) +} + +func (c *Client) getRuleGroupURL(ruleName string, ruleType string) string { + return fmt.Sprintf(getRuleGroupPath, c.config.url, url.QueryEscape(ruleName), url.QueryEscape(ruleType)) +} + +func (c *Client) createStatefulRuleURL() string { + return fmt.Sprintf(createStatefulRulePath, c.config.url) +} + +func (c *Client) updateStatefulRuleURL(ruleID int) string { + return fmt.Sprintf(updateStatefulRulePath, c.config.url, ruleID) +} + +func (c *Client) deleteStatefulRuleURL(ruleID int) string { + return fmt.Sprintf(deleteStatefulRulePath, c.config.url, ruleID) +} + +func (c *Client) getStatefulRuleGroupURL(ruleName string, ruleType string) string { + return fmt.Sprintf(getStatefulRuleGroupPath, c.config.url, url.QueryEscape(ruleName), url.QueryEscape(ruleType)) +} diff --git a/sysdig/internal/client/v2/silence_rule.go b/sysdig/internal/client/v2/silence_rule.go index 51f259322..70b3e658c 100644 --- a/sysdig/internal/client/v2/silence_rule.go +++ b/sysdig/internal/client/v2/silence_rule.go @@ -12,7 +12,7 @@ const ( silenceRulePath = "%s/api/v1/silencingRules/%d" ) -var SilenceRuleNotFound = errors.New("silence rule not found") +var ErrSilenceRuleNotFound = errors.New("silence rule not found") type SilenceRuleInterface interface { Base @@ -22,84 +22,95 @@ type SilenceRuleInterface interface { DeleteSilenceRule(ctx context.Context, id int) error } -func (client *Client) GetSilenceRule(ctx context.Context, id int) (SilenceRule, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getSilenceRuleURL(id), nil) +func (c *Client) GetSilenceRule(ctx context.Context, id int) (rule SilenceRule, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getSilenceRuleURL(id), nil) if err != nil { return SilenceRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode == http.StatusNotFound { - return SilenceRule{}, SilenceRuleNotFound + return SilenceRule{}, ErrSilenceRuleNotFound } if response.StatusCode != http.StatusOK { - return SilenceRule{}, client.ErrorFromResponse(response) + return SilenceRule{}, c.ErrorFromResponse(response) } - silenceRule, err := Unmarshal[SilenceRule](response.Body) - if err != nil { - return SilenceRule{}, err - } - - return silenceRule, nil + return Unmarshal[SilenceRule](response.Body) } -func (client *Client) CreateSilenceRule(ctx context.Context, silenceRule SilenceRule) (SilenceRule, error) { +func (c *Client) CreateSilenceRule(ctx context.Context, silenceRule SilenceRule) (rule SilenceRule, err error) { payload, err := Marshal(silenceRule) if err != nil { return SilenceRule{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getSilenceRulesURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getSilenceRulesURL(), payload) if err != nil { return SilenceRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return SilenceRule{}, client.ErrorFromResponse(response) + return SilenceRule{}, c.ErrorFromResponse(response) } return Unmarshal[SilenceRule](response.Body) } -func (client *Client) UpdateSilenceRule(ctx context.Context, silenceRule SilenceRule) (SilenceRule, error) { +func (c *Client) UpdateSilenceRule(ctx context.Context, silenceRule SilenceRule) (rule SilenceRule, err error) { payload, err := Marshal(silenceRule) if err != nil { return SilenceRule{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getSilenceRuleURL(silenceRule.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getSilenceRuleURL(silenceRule.ID), payload) if err != nil { return SilenceRule{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return SilenceRule{}, client.ErrorFromResponse(response) + return SilenceRule{}, c.ErrorFromResponse(response) } return Unmarshal[SilenceRule](response.Body) } -func (client *Client) DeleteSilenceRule(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getSilenceRuleURL(id), nil) +func (c *Client) DeleteSilenceRule(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getSilenceRuleURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getSilenceRulesURL() string { - return fmt.Sprintf(silenceRulesPath, client.config.url) +func (c *Client) getSilenceRulesURL() string { + return fmt.Sprintf(silenceRulesPath, c.config.url) } -func (client *Client) getSilenceRuleURL(id int) string { - return fmt.Sprintf(silenceRulePath, client.config.url, id) +func (c *Client) getSilenceRuleURL(id int) string { + return fmt.Sprintf(silenceRulePath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/sysdig_test.go b/sysdig/internal/client/v2/sysdig_test.go index 6ad70b2f0..323c2e539 100644 --- a/sysdig/internal/client/v2/sysdig_test.go +++ b/sysdig/internal/client/v2/sysdig_test.go @@ -1,5 +1,3 @@ -//go:build unit - package v2 import ( diff --git a/sysdig/internal/client/v2/team_service_account.go b/sysdig/internal/client/v2/team_service_account.go index e7f9a8327..a6e221270 100644 --- a/sysdig/internal/client/v2/team_service_account.go +++ b/sysdig/internal/client/v2/team_service_account.go @@ -7,12 +7,12 @@ import ( "net/http" ) -var TeamServiceAccountNotFound = errors.New("team service account not found") +var ErrTeamServiceAccountNotFound = errors.New("team service account not found") const ( - ServiceAccountsPath = "%s/api/serviceaccounts/team" - ServiceAccountPath = "%s/api/serviceaccounts/team/%d" - ServiceAccountDeletePath = "%s/api/serviceaccounts/team/%d/delete" + serviceAccountsPath = "%s/api/serviceaccounts/team" + serviceAccountPath = "%s/api/serviceaccounts/team/%d" + serviceAccountDeletePath = "%s/api/serviceaccounts/team/%d/delete" ) type TeamServiceAccountInterface interface { @@ -23,101 +23,103 @@ type TeamServiceAccountInterface interface { DeleteTeamServiceAccount(ctx context.Context, id int) error } -func (client *Client) GetTeamServiceAccountByID(ctx context.Context, id int) (*TeamServiceAccount, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetTeamServiceAccountURL(id), nil) +func (c *Client) GetTeamServiceAccountByID(ctx context.Context, id int) (team *TeamServiceAccount, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getTeamServiceAccountURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() + if response.StatusCode == http.StatusNotFound { + return nil, ErrTeamServiceAccountNotFound + } if response.StatusCode != http.StatusOK { - if response.StatusCode == http.StatusNotFound { - return nil, TeamServiceAccountNotFound - } - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - teamServiceAccount, err := Unmarshal[TeamServiceAccount](response.Body) - if err != nil { - return nil, err - } - return &teamServiceAccount, nil + return Unmarshal[*TeamServiceAccount](response.Body) } -func (client *Client) CreateTeamServiceAccount(ctx context.Context, account *TeamServiceAccount) (*TeamServiceAccount, error) { +func (c *Client) CreateTeamServiceAccount(ctx context.Context, account *TeamServiceAccount) (teamAccount *TeamServiceAccount, err error) { payload, err := Marshal(account) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateTeamServiceAccountURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createTeamServiceAccountURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - created, err := Unmarshal[TeamServiceAccount](response.Body) - if err != nil { - return nil, err - } - - return &created, nil + return Unmarshal[*TeamServiceAccount](response.Body) } -func (client *Client) UpdateTeamServiceAccount(ctx context.Context, account *TeamServiceAccount, id int) (*TeamServiceAccount, error) { +func (c *Client) UpdateTeamServiceAccount(ctx context.Context, account *TeamServiceAccount, id int) (serviceAccount *TeamServiceAccount, err error) { payload, err := Marshal(account) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateTeamServiceAccountURL(id), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateTeamServiceAccountURL(id), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - - updated, err := Unmarshal[TeamServiceAccount](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updated, nil + return Unmarshal[*TeamServiceAccount](response.Body) } -func (client *Client) DeleteTeamServiceAccount(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteTeamServiceAccountURL(id), nil) +func (c *Client) DeleteTeamServiceAccount(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteTeamServiceAccountURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetTeamServiceAccountURL(id int) string { - return fmt.Sprintf(ServiceAccountPath, client.config.url, id) +func (c *Client) getTeamServiceAccountURL(id int) string { + return fmt.Sprintf(serviceAccountPath, c.config.url, id) } -func (client *Client) CreateTeamServiceAccountURL() string { - return fmt.Sprintf(ServiceAccountsPath, client.config.url) +func (c *Client) createTeamServiceAccountURL() string { + return fmt.Sprintf(serviceAccountsPath, c.config.url) } -func (client *Client) UpdateTeamServiceAccountURL(id int) string { - return fmt.Sprintf(ServiceAccountPath, client.config.url, id) +func (c *Client) updateTeamServiceAccountURL(id int) string { + return fmt.Sprintf(serviceAccountPath, c.config.url, id) } -func (client *Client) DeleteTeamServiceAccountURL(id int) string { - return fmt.Sprintf(ServiceAccountDeletePath, client.config.url, id) +func (c *Client) deleteTeamServiceAccountURL(id int) string { + return fmt.Sprintf(serviceAccountDeletePath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/teams.go b/sysdig/internal/client/v2/teams.go index 8688a8669..4783dc4f9 100644 --- a/sysdig/internal/client/v2/teams.go +++ b/sysdig/internal/client/v2/teams.go @@ -7,15 +7,15 @@ import ( ) const ( - GetUsersLightPath = "%s/api/users/light" - GetTeamsPath = "%s/api/teams" - GetTeamPath = "%s/api/teams/%d" + getUsersLightPath = "%s/api/users/light" + getTeamsPath = "%s/api/teams" + getTeamPath = "%s/api/teams/%d" ) type TeamInterface interface { Base GetUserIDByEmail(ctx context.Context, userRoles []UserRoles) ([]UserRoles, error) - GetTeamById(ctx context.Context, id int) (t Team, err error) + GetTeamByID(ctx context.Context, id int) (t Team, err error) CreateTeam(ctx context.Context, tRequest Team) (t Team, err error) UpdateTeam(ctx context.Context, tRequest Team) (t Team, err error) DeleteTeam(ctx context.Context, id int) error @@ -26,15 +26,19 @@ type teamsWrapper struct { Teams []Team `json:"teams"` } -func (client *Client) GetUserIDByEmail(ctx context.Context, userRoles []UserRoles) ([]UserRoles, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetUsersLightURL(), nil) +func (c *Client) GetUserIDByEmail(ctx context.Context, userRoles []UserRoles) (modifiedUserRoles []UserRoles, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getUsersLightURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return nil, err } @@ -48,43 +52,45 @@ func (client *Client) GetUserIDByEmail(ctx context.Context, userRoles []UserRole usersMap[u.Email] = u.ID } - modifiedUserRoles := make([]UserRoles, 0) + modifiedUserRoles = make([]UserRoles, 0) for _, userRole := range userRoles { ur := userRole id, ok := usersMap[ur.Email] if !ok { return nil, fmt.Errorf("email %s doesn't exist", ur.Email) } - ur.UserId = id + ur.UserID = id modifiedUserRoles = append(modifiedUserRoles, ur) } return modifiedUserRoles, nil } -func (client *Client) GetTeamById(ctx context.Context, id int) (Team, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetTeamURL(id), nil) +func (c *Client) GetTeamByID(ctx context.Context, id int) (team Team, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getTeamURL(id), nil) if err != nil { return Team{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Team{}, client.ErrorFromResponse(response) + return Team{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[teamWrapper](response.Body) if err != nil { - return Team{}, client.ErrorFromResponse(response) + return Team{}, c.ErrorFromResponse(response) } return wrapper.Team, err } -func (client *Client) CreateTeam(ctx context.Context, team Team) (Team, error) { - var err error - - team.UserRoles, err = client.GetUserIDByEmail(ctx, team.UserRoles) +func (c *Client) CreateTeam(ctx context.Context, team Team) (createdTeam Team, err error) { + team.UserRoles, err = c.GetUserIDByEmail(ctx, team.UserRoles) if err != nil { return Team{}, err } @@ -96,14 +102,18 @@ func (client *Client) CreateTeam(ctx context.Context, team Team) (Team, error) { return Team{}, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.GetTeamsURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getTeamsURL(), payload) if err != nil { return Team{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return Team{}, client.ErrorFromResponse(response) + return Team{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[teamWrapper](response.Body) @@ -114,10 +124,8 @@ func (client *Client) CreateTeam(ctx context.Context, team Team) (Team, error) { return wrapper.Team, nil } -func (client *Client) UpdateTeam(ctx context.Context, team Team) (Team, error) { - var err error - - team.UserRoles, err = client.GetUserIDByEmail(ctx, team.UserRoles) +func (c *Client) UpdateTeam(ctx context.Context, team Team) (updatedTeam Team, err error) { + team.UserRoles, err = c.GetUserIDByEmail(ctx, team.UserRoles) if err != nil { return Team{}, err } @@ -127,14 +135,18 @@ func (client *Client) UpdateTeam(ctx context.Context, team Team) (Team, error) { return Team{}, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.GetTeamURL(team.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getTeamURL(team.ID), payload) if err != nil { return Team{}, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return Team{}, client.ErrorFromResponse(response) + return Team{}, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[teamWrapper](response.Body) @@ -145,29 +157,37 @@ func (client *Client) UpdateTeam(ctx context.Context, team Team) (Team, error) { return wrapper.Team, nil } -func (client *Client) DeleteTeam(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.GetTeamURL(id), nil) +func (c *Client) DeleteTeam(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getTeamURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) ListTeams(ctx context.Context) ([]Team, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetTeamsURL(), nil) +func (c *Client) ListTeams(ctx context.Context) (teams []Team, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getTeamsURL(), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[teamsWrapper](response.Body) @@ -178,14 +198,14 @@ func (client *Client) ListTeams(ctx context.Context) ([]Team, error) { return wrapper.Teams, nil } -func (client *Client) GetUsersLightURL() string { - return fmt.Sprintf(GetUsersLightPath, client.config.url) +func (c *Client) getUsersLightURL() string { + return fmt.Sprintf(getUsersLightPath, c.config.url) } -func (client *Client) GetTeamsURL() string { - return fmt.Sprintf(GetTeamsPath, client.config.url) +func (c *Client) getTeamsURL() string { + return fmt.Sprintf(getTeamsPath, c.config.url) } -func (client *Client) GetTeamURL(id int) string { - return fmt.Sprintf(GetTeamPath, client.config.url, id) +func (c *Client) getTeamURL(id int) string { + return fmt.Sprintf(getTeamPath, c.config.url, id) } diff --git a/sysdig/internal/client/v2/users.go b/sysdig/internal/client/v2/users.go index dd5d77777..1c3131de6 100644 --- a/sysdig/internal/client/v2/users.go +++ b/sysdig/internal/client/v2/users.go @@ -7,18 +7,17 @@ import ( ) const ( - GetUserByUsernamePath = "%s/api/users/%s" - GetUserPath = "%s/api/users/%d" - GetUsersPath = "%s/api/users" - CreateUserPath = "%s/api/user/provisioning/" - UpdateUserPath = "%s/api/users/%d" - DeleteUserPath = "%s/api/users/%d" - GetCurrentUserPath = "%s/api/users/me" + getUserByUsernamePath = "%s/api/users/%s" + getUserPath = "%s/api/users/%d" + createUserPath = "%s/api/user/provisioning/" + updateUserPath = "%s/api/users/%d" + deleteUserPath = "%s/api/users/%d" + getCurrentUserPath = "%s/api/users/me" ) type UserInterface interface { Base - GetUserById(ctx context.Context, id int) (*User, error) + GetUserByID(ctx context.Context, id int) (*User, error) GetUserByUsername(ctx context.Context, username string) (*User, error) GetUserByEmail(ctx context.Context, email string) (*User, error) CreateUser(ctx context.Context, user *User) (*User, error) @@ -27,16 +26,19 @@ type UserInterface interface { GetCurrentUser(ctx context.Context) (u *User, err error) } -func (client *Client) GetUserById(ctx context.Context, id int) (*User, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetUserUrl(id), nil) +func (c *Client) GetUserByID(ctx context.Context, id int) (user *User, error error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getUserURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) - return nil, err + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[userWrapper](response.Body) @@ -47,16 +49,19 @@ func (client *Client) GetUserById(ctx context.Context, id int) (*User, error) { return &wrapper.User, nil } -func (client *Client) GetUserByUsername(ctx context.Context, username string) (*User, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetUserByUsernameURL(username), nil) +func (c *Client) GetUserByUsername(ctx context.Context, username string) (user *User, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getUserByUsernameURL(username), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) - return nil, err + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[userWrapper](response.Body) @@ -67,24 +72,27 @@ func (client *Client) GetUserByUsername(ctx context.Context, username string) (* return &wrapper.User, nil } -func (client *Client) GetUserByEmail(ctx context.Context, email string) (*User, error) { - return client.GetUserByUsername(ctx, email) +func (c *Client) GetUserByEmail(ctx context.Context, email string) (*User, error) { + return c.GetUserByUsername(ctx, email) } -func (client *Client) CreateUser(ctx context.Context, user *User) (*User, error) { +func (c *Client) CreateUser(ctx context.Context, user *User) (createdUser *User, err error) { payload, err := Marshal(user) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.CreateUsersURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createUsersURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - err = client.ErrorFromResponse(response) - return nil, err + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[userWrapper](response.Body) @@ -95,21 +103,24 @@ func (client *Client) CreateUser(ctx context.Context, user *User) (*User, error) return &wrapper.User, nil } -func (client *Client) UpdateUser(ctx context.Context, user *User) (*User, error) { +func (c *Client) UpdateUser(ctx context.Context, user *User) (updated *User, err error) { payload, err := Marshal(user) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.UpdateUserURL(user.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateUserURL(user.ID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) - return nil, err + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[userWrapper](response.Body) @@ -120,29 +131,37 @@ func (client *Client) UpdateUser(ctx context.Context, user *User) (*User, error) return &wrapper.User, nil } -func (client *Client) DeleteUser(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.DeleteUserURL(id), nil) +func (c *Client) DeleteUser(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteUserURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) GetCurrentUser(ctx context.Context) (u *User, err error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.GetCurrentUserURL(), nil) +func (c *Client) GetCurrentUser(ctx context.Context) (u *User, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getCurrentUserURL(), nil) if err != nil { return } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - err = client.ErrorFromResponse(response) + err = c.ErrorFromResponse(response) return } @@ -154,30 +173,26 @@ func (client *Client) GetCurrentUser(ctx context.Context) (u *User, err error) { return &wrapper.User, nil } -func (client *Client) GetUserUrl(id int) string { - return fmt.Sprintf(GetUserPath, client.config.url, id) -} - -func (client *Client) GetUsersUrl() string { - return fmt.Sprintf(GetUsersPath, client.config.url) +func (c *Client) getUserURL(id int) string { + return fmt.Sprintf(getUserPath, c.config.url, id) } -func (client *Client) GetUserByUsernameURL(username string) string { - return fmt.Sprintf(GetUserByUsernamePath, client.config.url, username) +func (c *Client) getUserByUsernameURL(username string) string { + return fmt.Sprintf(getUserByUsernamePath, c.config.url, username) } -func (client *Client) CreateUsersURL() string { - return fmt.Sprintf(CreateUserPath, client.config.url) +func (c *Client) createUsersURL() string { + return fmt.Sprintf(createUserPath, c.config.url) } -func (client *Client) UpdateUserURL(id int) string { - return fmt.Sprintf(UpdateUserPath, client.config.url, id) +func (c *Client) updateUserURL(id int) string { + return fmt.Sprintf(updateUserPath, c.config.url, id) } -func (client *Client) DeleteUserURL(id int) string { - return fmt.Sprintf(DeleteUserPath, client.config.url, id) +func (c *Client) deleteUserURL(id int) string { + return fmt.Sprintf(deleteUserPath, c.config.url, id) } -func (client *Client) GetCurrentUserURL() string { - return fmt.Sprintf(GetCurrentUserPath, client.config.url) +func (c *Client) getCurrentUserURL() string { + return fmt.Sprintf(getCurrentUserPath, c.config.url) } diff --git a/sysdig/internal/client/v2/vulnerability_accept_risk.go b/sysdig/internal/client/v2/vulnerability_accept_risk.go index d7cceecd9..c2b5022c4 100644 --- a/sysdig/internal/client/v2/vulnerability_accept_risk.go +++ b/sysdig/internal/client/v2/vulnerability_accept_risk.go @@ -6,33 +6,37 @@ import ( "net/http" ) +const ( + acceptVulnerabilityRiskCreatePath = "%s/secure/vulnerability/v1beta1/accepted-risks" + acceptVulnerabilityRiskGetPath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" + acceptVulnerabilityRiskDeletePath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" + acceptVulnerabilityRiskUpdatePath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" +) + type PostureVulnerabilityAcceptRiskInterface interface { Base SaveAcceptVulnerabilityRisk(ctx context.Context, p *AcceptVulnerabilityRiskRequest) (*AcceptVulnerabilityRisk, int, error) - GetAcceptanceVulnerabilityRisk(ctx context.Context, id string) (*AcceptVulnerabilityRisk, int, error) + GetAcceptanceVulnerabilityRiskByID(ctx context.Context, id string) (*AcceptVulnerabilityRisk, int, error) DeleteAcceptanceVulnerabilityRisk(ctx context.Context, id string) error UpdateAcceptanceVulnerabilityRisk(ctx context.Context, p *UpdateAcceptVulnerabilityRiskRequest) (*AcceptVulnerabilityRisk, int, error) } -const ( - AcceptVulnerabilityRiskCreatePath = "%s/secure/vulnerability/v1beta1/accepted-risks" - AcceptVulnerabilityRiskGetPath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" - AcceptVulnerabilityRiskDeletePath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" - AcceptVulnerabilityRiskUpdatePath = "%s/secure/vulnerability/v1beta1/accepted-risks/%s" -) - -func (c *Client) SaveAcceptVulnerabilityRisk(ctx context.Context, p *AcceptVulnerabilityRiskRequest) (*AcceptVulnerabilityRisk, int, error) { +func (c *Client) SaveAcceptVulnerabilityRisk(ctx context.Context, p *AcceptVulnerabilityRiskRequest) (risk *AcceptVulnerabilityRisk, statusCode int, err error) { payload, err := Marshal(p) if err != nil { return nil, 0, err } - response, err := c.requester.Request(ctx, http.MethodPost, fmt.Sprintf(AcceptVulnerabilityRiskCreatePath, c.config.url), payload) + response, err := c.requester.Request(ctx, http.MethodPost, fmt.Sprintf(acceptVulnerabilityRiskCreatePath, c.config.url), payload) if err != nil { return nil, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusCreated { return nil, response.StatusCode, c.ErrorFromResponse(response) @@ -46,12 +50,16 @@ func (c *Client) SaveAcceptVulnerabilityRisk(ctx context.Context, p *AcceptVulne return &resp, 0, nil } -func (c *Client) GetAcceptanceVulnerabilityRisk(ctx context.Context, id string) (*AcceptVulnerabilityRisk, int, error) { - response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(AcceptVulnerabilityRiskGetPath, c.config.url, id), nil) +func (c *Client) GetAcceptanceVulnerabilityRiskByID(ctx context.Context, id string) (risk *AcceptVulnerabilityRisk, statusCode int, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, fmt.Sprintf(acceptVulnerabilityRiskGetPath, c.config.url, id), nil) if err != nil { return nil, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { return nil, response.StatusCode, c.ErrorFromResponse(response) @@ -65,12 +73,16 @@ func (c *Client) GetAcceptanceVulnerabilityRisk(ctx context.Context, id string) return &resp, 0, nil } -func (c *Client) DeleteAcceptanceVulnerabilityRisk(ctx context.Context, id string) error { - response, err := c.requester.Request(ctx, http.MethodDelete, fmt.Sprintf(AcceptVulnerabilityRiskDeletePath, c.config.url, id), nil) +func (c *Client) DeleteAcceptanceVulnerabilityRisk(ctx context.Context, id string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, fmt.Sprintf(acceptVulnerabilityRiskDeletePath, c.config.url, id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent { return c.ErrorFromResponse(response) @@ -79,17 +91,21 @@ func (c *Client) DeleteAcceptanceVulnerabilityRisk(ctx context.Context, id strin return nil } -func (c *Client) UpdateAcceptanceVulnerabilityRisk(ctx context.Context, p *UpdateAcceptVulnerabilityRiskRequest) (*AcceptVulnerabilityRisk, int, error) { +func (c *Client) UpdateAcceptanceVulnerabilityRisk(ctx context.Context, p *UpdateAcceptVulnerabilityRiskRequest) (risk *AcceptVulnerabilityRisk, statusCode int, err error) { payload, err := Marshal(p) if err != nil { return nil, 0, err } - response, err := c.requester.Request(ctx, http.MethodPut, fmt.Sprintf(AcceptVulnerabilityRiskUpdatePath, c.config.url, p.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, fmt.Sprintf(acceptVulnerabilityRiskUpdatePath, c.config.url, p.ID), payload) if err != nil { return nil, 0, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { return nil, response.StatusCode, c.ErrorFromResponse(response) diff --git a/sysdig/internal/client/v2/vulnerability_exception.go b/sysdig/internal/client/v2/vulnerability_exception.go index d142a3f07..857df9296 100644 --- a/sysdig/internal/client/v2/vulnerability_exception.go +++ b/sysdig/internal/client/v2/vulnerability_exception.go @@ -34,168 +34,200 @@ type DeprecatedVulnerabilityExceptionInterface interface { UpdateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (*DeprecatedVulnerabilityException, error) } -func (client *Client) CreateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (*DeprecatedVulnerabilityExceptionList, error) { +func (c *Client) CreateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (createdList *DeprecatedVulnerabilityExceptionList, err error) { payload, err := Marshal(list) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.createDeprecatedVulnerabilityExceptionListURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createDeprecatedVulnerabilityExceptionListURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) } -func (client *Client) GetDeprectedVulnerabilityExceptionListByID(ctx context.Context, id string) (*DeprecatedVulnerabilityExceptionList, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getDeprecatedVulnerabilityExceptionListURL(id), nil) +func (c *Client) GetDeprectedVulnerabilityExceptionListByID(ctx context.Context, id string) (list *DeprecatedVulnerabilityExceptionList, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getDeprecatedVulnerabilityExceptionListURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) } -func (client *Client) DeleteDeprecatedVulnerabilityExceptionList(ctx context.Context, id string) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.deleteDeprecatedVulnerabilityExceptionListURL(id), nil) +func (c *Client) DeleteDeprecatedVulnerabilityExceptionList(ctx context.Context, id string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteDeprecatedVulnerabilityExceptionListURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) UpdateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (*DeprecatedVulnerabilityExceptionList, error) { +func (c *Client) UpdateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (updatedList *DeprecatedVulnerabilityExceptionList, err error) { payload, err := Marshal(list) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.updateDeprecatedVulnerabilityExceptionListURL(list.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateDeprecatedVulnerabilityExceptionListURL(list.ID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) } -func (client *Client) CreateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (*DeprecatedVulnerabilityException, error) { +func (c *Client) CreateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (createdException *DeprecatedVulnerabilityException, err error) { payload, err := Marshal(exception) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.createDeprecatedVulnerabilityExceptionURL(listID), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.createDeprecatedVulnerabilityExceptionURL(listID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityException](response.Body) } -func (client *Client) GetDeprecatedVulnerabilityExceptionByID(ctx context.Context, listID string, exceptionID string) (*DeprecatedVulnerabilityException, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getDeprecatedVulnerabilityExceptionURL(listID, exceptionID), nil) +func (c *Client) GetDeprecatedVulnerabilityExceptionByID(ctx context.Context, listID string, exceptionID string) (exception *DeprecatedVulnerabilityException, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getDeprecatedVulnerabilityExceptionURL(listID, exceptionID), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityException](response.Body) } -func (client *Client) DeleteDeprecatedVulnerabilityException(ctx context.Context, listID string, exceptionID string) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.deleteDeprecatedVulnerabilityExceptionURL(listID, exceptionID), nil) +func (c *Client) DeleteDeprecatedVulnerabilityException(ctx context.Context, listID string, exceptionID string) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.deleteDeprecatedVulnerabilityExceptionURL(listID, exceptionID), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() // We will ignore the 404 error, because the exception may have been removed if the exception list has been // removed as well. This should not affect the user, because removing a non existing exception has no effect. if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) UpdateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (*DeprecatedVulnerabilityException, error) { +func (c *Client) UpdateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (updatedException *DeprecatedVulnerabilityException, err error) { payload, err := Marshal(exception) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.updateDeprecatedVulnerabilityExceptionURL(listID, exception.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.updateDeprecatedVulnerabilityExceptionURL(listID, exception.ID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } return Unmarshal[*DeprecatedVulnerabilityException](response.Body) } -func (client *Client) createDeprecatedVulnerabilityExceptionListURL() string { - return fmt.Sprintf(createDeprecatedVulnerabilityExceptionListPath, client.config.url) +func (c *Client) createDeprecatedVulnerabilityExceptionListURL() string { + return fmt.Sprintf(createDeprecatedVulnerabilityExceptionListPath, c.config.url) } -func (client *Client) getDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(getDeprecatedVulnerabilityExceptionListPath, client.config.url, id) +func (c *Client) getDeprecatedVulnerabilityExceptionListURL(id string) string { + return fmt.Sprintf(getDeprecatedVulnerabilityExceptionListPath, c.config.url, id) } -func (client *Client) deleteDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionListPath, client.config.url, id) +func (c *Client) deleteDeprecatedVulnerabilityExceptionListURL(id string) string { + return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionListPath, c.config.url, id) } -func (client *Client) updateDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionListPath, client.config.url, id) +func (c *Client) updateDeprecatedVulnerabilityExceptionListURL(id string) string { + return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionListPath, c.config.url, id) } -func (client *Client) createDeprecatedVulnerabilityExceptionURL(listID string) string { - return fmt.Sprintf(createDeprecatedVulnerabilityExceptionPath, client.config.url, listID) +func (c *Client) createDeprecatedVulnerabilityExceptionURL(listID string) string { + return fmt.Sprintf(createDeprecatedVulnerabilityExceptionPath, c.config.url, listID) } -func (client *Client) getDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(getDeprecatedVulnerabilityExceptionPath, client.config.url, listID, ID) +func (c *Client) getDeprecatedVulnerabilityExceptionURL(listID, ID string) string { + return fmt.Sprintf(getDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) } -func (client *Client) deleteDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionPath, client.config.url, listID, ID) +func (c *Client) deleteDeprecatedVulnerabilityExceptionURL(listID, ID string) string { + return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) } -func (client *Client) updateDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionPath, client.config.url, listID, ID) +func (c *Client) updateDeprecatedVulnerabilityExceptionURL(listID, ID string) string { + return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) } diff --git a/sysdig/internal/client/v2/zones.go b/sysdig/internal/client/v2/zones.go index eafd15d87..994ae98d2 100644 --- a/sysdig/internal/client/v2/zones.go +++ b/sysdig/internal/client/v2/zones.go @@ -8,31 +8,35 @@ import ( ) const ( - PlatformZonesPath = "%s/platform/v1/zones" - PlatformZonePath = "%s/platform/v1/zones/%d" + platformZonesPath = "%s/platform/v1/zones" + platformZonePath = "%s/platform/v1/zones/%d" ) type ZoneInterface interface { Base GetZones(ctx context.Context, name string) ([]Zone, error) - GetZoneById(ctx context.Context, id int) (*Zone, error) + GetZoneByID(ctx context.Context, id int) (*Zone, error) CreateZone(ctx context.Context, zone *ZoneRequest) (*Zone, error) UpdateZone(ctx context.Context, zone *ZoneRequest) (*Zone, error) DeleteZone(ctx context.Context, id int) error } -func (client *Client) GetZones(ctx context.Context, name string) ([]Zone, error) { - zonesURL := client.getZonesURL() +func (c *Client) GetZones(ctx context.Context, name string) (zones []Zone, err error) { + zonesURL := c.getZonesURL() zonesURL = fmt.Sprintf("%s?filter=name:%s", zonesURL, url.QueryEscape(name)) - response, err := client.requester.Request(ctx, http.MethodGet, zonesURL, nil) + response, err := c.requester.Request(ctx, http.MethodGet, zonesURL, nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } wrapper, err := Unmarshal[ZonesWrapper](response.Body) if err != nil { @@ -42,90 +46,92 @@ func (client *Client) GetZones(ctx context.Context, name string) ([]Zone, error) return wrapper.Zones, nil } -func (client *Client) GetZoneById(ctx context.Context, id int) (*Zone, error) { - response, err := client.requester.Request(ctx, http.MethodGet, client.getZoneURL(id), nil) +func (c *Client) GetZoneByID(ctx context.Context, id int) (zone *Zone, err error) { + response, err := c.requester.Request(ctx, http.MethodGet, c.getZoneURL(id), nil) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK { - return nil, client.ErrorFromResponse(response) - } - zone, err := Unmarshal[Zone](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &zone, nil + return Unmarshal[*Zone](response.Body) } -func (client *Client) CreateZone(ctx context.Context, zone *ZoneRequest) (*Zone, error) { +func (c *Client) CreateZone(ctx context.Context, zone *ZoneRequest) (createdZone *Zone, err error) { payload, err := Marshal(zone) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPost, client.getZonesURL(), payload) + response, err := c.requester.Request(ctx, http.MethodPost, c.getZonesURL(), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) + return nil, c.ErrorFromResponse(response) } - createdZone, err := Unmarshal[Zone](response.Body) - if err != nil { - return nil, err - } - - return &createdZone, nil + return Unmarshal[*Zone](response.Body) } -func (client *Client) UpdateZone(ctx context.Context, zone *ZoneRequest) (*Zone, error) { +func (c *Client) UpdateZone(ctx context.Context, zone *ZoneRequest) (updatedZone *Zone, err error) { payload, err := Marshal(zone) if err != nil { return nil, err } - response, err := client.requester.Request(ctx, http.MethodPut, client.getZoneURL(zone.ID), payload) + response, err := c.requester.Request(ctx, http.MethodPut, c.getZoneURL(zone.ID), payload) if err != nil { return nil, err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { - return nil, client.ErrorFromResponse(response) - } - - updatedZone, err := Unmarshal[Zone](response.Body) - if err != nil { - return nil, err + return nil, c.ErrorFromResponse(response) } - return &updatedZone, nil + return Unmarshal[*Zone](response.Body) } -func (client *Client) DeleteZone(ctx context.Context, id int) error { - response, err := client.requester.Request(ctx, http.MethodDelete, client.getZoneURL(id), nil) +func (c *Client) DeleteZone(ctx context.Context, id int) (err error) { + response, err := c.requester.Request(ctx, http.MethodDelete, c.getZoneURL(id), nil) if err != nil { return err } - defer response.Body.Close() + defer func() { + if dErr := response.Body.Close(); dErr != nil { + err = fmt.Errorf("unable to close response body: %w", dErr) + } + }() if response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotFound { - return client.ErrorFromResponse(response) + return c.ErrorFromResponse(response) } return nil } -func (client *Client) getZonesURL() string { - return fmt.Sprintf(PlatformZonesPath, client.config.url) +func (c *Client) getZonesURL() string { + return fmt.Sprintf(platformZonesPath, c.config.url) } -func (client *Client) getZoneURL(id int) string { - return fmt.Sprintf(PlatformZonePath, client.config.url, id) +func (c *Client) getZoneURL(id int) string { + return fmt.Sprintf(platformZonePath, c.config.url, id) } diff --git a/sysdig/provider.go b/sysdig/provider.go index 50e0d4ff9..a99b42cb3 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -11,7 +11,7 @@ type SysdigProvider struct { SysdigClient SysdigClients } -// Used by tests to get the provider +// Provider is used by tests to get the provider func Provider() *schema.Provider { sysdigClient := NewSysdigClients() provider := &SysdigProvider{SysdigClient: sysdigClient} @@ -269,7 +269,7 @@ func (p *SysdigProvider) Provider() *schema.Provider { } } -func (p *SysdigProvider) providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { +func (p *SysdigProvider) providerConfigure(ctx context.Context, d *schema.ResourceData) (any, diag.Diagnostics) { p.SysdigClient.Configure(ctx, d) return p.SysdigClient, nil } diff --git a/sysdig/provider_test.go b/sysdig/provider_test.go index e0fb16c35..ed3badc74 100644 --- a/sysdig/provider_test.go +++ b/sysdig/provider_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_ibm_monitor || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_agent_access_key.go b/sysdig/resource_sysdig_agent_access_key.go index 5e6aab938..b21d39479 100644 --- a/sysdig/resource_sysdig_agent_access_key.go +++ b/sysdig/resource_sysdig_agent_access_key.go @@ -67,7 +67,7 @@ func resourceSysdigAgentAccessKey() *schema.Resource { } } -func resourceSysdigAgentAccessKeyDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAgentAccessKeyDelete(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) @@ -81,7 +81,7 @@ func resourceSysdigAgentAccessKeyDelete(ctx context.Context, data *schema.Resour return nil } -func resourceSysdigAgentAccessKeyCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAgentAccessKeyCreate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) @@ -101,7 +101,7 @@ func resourceSysdigAgentAccessKeyCreate(ctx context.Context, data *schema.Resour return nil } -func resourceSysdigAgentAccessKeyUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAgentAccessKeyUpdate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) @@ -124,7 +124,7 @@ func resourceSysdigAgentAccessKeyUpdate(ctx context.Context, data *schema.Resour } func agentAccessKeyFromResourceData(data *schema.ResourceData) (*v2.AgentAccessKey, error) { - metadataFromResourceData := data.Get("metadata").(map[string]interface{}) + metadataFromResourceData := data.Get("metadata").(map[string]any) metadata := make(map[string]string) for key, val := range metadataFromResourceData { @@ -149,15 +149,15 @@ func agentAccessKeyFromResourceData(data *schema.ResourceData) (*v2.AgentAccessK }, nil } -func resourceSysdigAgentAccessKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAgentAccessKeyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).commonClientV2() if err != nil { return diag.FromErr(err) } - agentKeyId := d.Id() + agentKeyID := d.Id() - agentAccessKey, err := client.GetAgentAccessKeyByID(ctx, agentKeyId) + agentAccessKey, err := client.GetAgentAccessKeyByID(ctx, agentKeyID) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/resource_sysdig_agent_access_key_test.go b/sysdig/resource_sysdig_agent_access_key_test.go index e91f222a9..367eaa458 100644 --- a/sysdig/resource_sysdig_agent_access_key_test.go +++ b/sysdig/resource_sysdig_agent_access_key_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_custom_role.go b/sysdig/resource_sysdig_custom_role.go index 4a38ad573..7e8a9f480 100644 --- a/sysdig/resource_sysdig_custom_role.go +++ b/sysdig/resource_sysdig_custom_role.go @@ -64,7 +64,7 @@ func resourceSysdigCustomRole() *schema.Resource { } } -func resourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -75,9 +75,9 @@ func resourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m return diag.FromErr(err) } - customRole, err := client.GetCustomRole(ctx, id) + customRole, err := client.GetCustomRoleByID(ctx, id) if err != nil { - if err == v2.CustomRoleNotFound { + if err == v2.ErrCustomRoleNotFound { d.SetId("") return nil } @@ -92,7 +92,7 @@ func resourceSysdigCustomRoleRead(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigCustomRoleCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigCustomRoleCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -116,7 +116,7 @@ func resourceSysdigCustomRoleCreate(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigCustomRoleUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigCustomRoleUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -144,7 +144,7 @@ func resourceSysdigCustomRoleUpdate(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigCustomRoleDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigCustomRoleDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -184,7 +184,7 @@ type permission struct { } func (p *permission) readPermissions(product string) []string { - permissionsMap := p.s.List()[0].(map[string]interface{}) + permissionsMap := p.s.List()[0].(map[string]any) permissionsInterface := permissionsMap[product].(*schema.Set).List() permissions := make([]string, len(permissionsInterface)) for i, permission := range permissionsInterface { @@ -210,7 +210,7 @@ func customRoleToResourceData(customRole *v2.CustomRole, d *schema.ResourceData) if err != nil { return err } - err = d.Set(SchemaPermissionsKey, []map[string]interface{}{ + err = d.Set(SchemaPermissionsKey, []map[string]any{ permissionsToResourceData(customRole.MonitorPermissions, customRole.SecurePermissions), }) if err != nil { @@ -219,8 +219,8 @@ func customRoleToResourceData(customRole *v2.CustomRole, d *schema.ResourceData) return nil } -func permissionsToResourceData(monitorPermissions []string, securePermissions []string) map[string]interface{} { - return map[string]interface{}{ +func permissionsToResourceData(monitorPermissions []string, securePermissions []string) map[string]any { + return map[string]any{ SchemaMonitorPermKey: monitorPermissions, SchemaSecurePermKey: securePermissions, } diff --git a/sysdig/resource_sysdig_custom_role_test.go b/sysdig/resource_sysdig_custom_role_test.go index e16d3fcd8..137722d5a 100644 --- a/sysdig/resource_sysdig_custom_role_test.go +++ b/sysdig/resource_sysdig_custom_role_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_group_mapping.go b/sysdig/resource_sysdig_group_mapping.go index 1ae491bac..9168466f0 100644 --- a/sysdig/resource_sysdig_group_mapping.go +++ b/sysdig/resource_sysdig_group_mapping.go @@ -70,7 +70,7 @@ func resourceSysdigGroupMapping() *schema.Resource { } } -func resourceSysdigGroupMappingRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -83,7 +83,7 @@ func resourceSysdigGroupMappingRead(ctx context.Context, d *schema.ResourceData, groupMapping, err := client.GetGroupMapping(ctx, id) if err != nil { - if err == v2.GroupMappingNotFound { + if err == v2.ErrGroupMappingNotFound { d.SetId("") return nil } @@ -98,7 +98,7 @@ func resourceSysdigGroupMappingRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigGroupMappingCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -119,7 +119,7 @@ func resourceSysdigGroupMappingCreate(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigGroupMappingUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -144,7 +144,7 @@ func resourceSysdigGroupMappingUpdate(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigGroupMappingDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -174,8 +174,8 @@ func groupMappingFromResourceData(d *schema.ResourceData) *v2.GroupMapping { } func teamMapFromResourceData(d *schema.ResourceData) *v2.TeamMap { - teamMap := d.Get("team_map").(*schema.Set).List()[0].(map[string]interface{}) - teamIDsInterface := teamMap["team_ids"].([]interface{}) + teamMap := d.Get("team_map").(*schema.Set).List()[0].(map[string]any) + teamIDsInterface := teamMap["team_ids"].([]any) teamIDs := make([]int, len(teamIDsInterface)) for i, teamID := range teamIDsInterface { teamIDs[i] = teamID.(int) @@ -187,8 +187,8 @@ func teamMapFromResourceData(d *schema.ResourceData) *v2.TeamMap { } } -func teamMapToResourceData(teamMap *v2.TeamMap) map[string]interface{} { - return map[string]interface{}{ +func teamMapToResourceData(teamMap *v2.TeamMap) map[string]any { + return map[string]any{ "all_teams": teamMap.AllTeams, "team_ids": teamMap.TeamIDs, } @@ -207,7 +207,7 @@ func groupMappingToResourceData(groupMapping *v2.GroupMapping, d *schema.Resourc if err != nil { return err } - err = d.Set("team_map", []map[string]interface{}{teamMapToResourceData(groupMapping.TeamMap)}) + err = d.Set("team_map", []map[string]any{teamMapToResourceData(groupMapping.TeamMap)}) if err != nil { return err } diff --git a/sysdig/resource_sysdig_group_mapping_config.go b/sysdig/resource_sysdig_group_mapping_config.go index 4bc0f6130..7538c1c9f 100644 --- a/sysdig/resource_sysdig_group_mapping_config.go +++ b/sysdig/resource_sysdig_group_mapping_config.go @@ -38,7 +38,7 @@ func resourceSysdigGroupMappingConfig() *schema.Resource { } } -func resourceSysdigGroupMappingConfigRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingConfigRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -46,7 +46,7 @@ func resourceSysdigGroupMappingConfigRead(ctx context.Context, d *schema.Resourc groupMappingConfig, err := client.GetGroupMappingConfig(ctx) if err != nil { - if err == v2.GroupMappingConfigNotFound { + if err == v2.ErrGroupMappingConfigNotFound { return nil } return diag.FromErr(err) @@ -60,7 +60,7 @@ func resourceSysdigGroupMappingConfigRead(ctx context.Context, d *schema.Resourc return nil } -func resourceSysdigGroupMappingConfigCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingConfigCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -79,7 +79,7 @@ func resourceSysdigGroupMappingConfigCreate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigGroupMappingConfigUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingConfigUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -96,7 +96,7 @@ func resourceSysdigGroupMappingConfigUpdate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigGroupMappingConfigDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigGroupMappingConfigDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { return nil } diff --git a/sysdig/resource_sysdig_group_mapping_config_test.go b/sysdig/resource_sysdig_group_mapping_config_test.go index 54226eeed..0f5d0daa5 100644 --- a/sysdig/resource_sysdig_group_mapping_config_test.go +++ b/sysdig/resource_sysdig_group_mapping_config_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_group_mapping_test.go b/sysdig/resource_sysdig_group_mapping_test.go index 98bf0e7a0..3e7705f9d 100644 --- a/sysdig/resource_sysdig_group_mapping_test.go +++ b/sysdig/resource_sysdig_group_mapping_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_ip_filter.go b/sysdig/resource_sysdig_ip_filter.go index 4a9cd9105..27c3e4f27 100644 --- a/sysdig/resource_sysdig_ip_filter.go +++ b/sysdig/resource_sysdig_ip_filter.go @@ -2,10 +2,11 @@ package sysdig import ( "context" + "strconv" + v2 "github.com/draios/terraform-provider-sysdig/sysdig/internal/client/v2" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "strconv" ) func resourceSysdigIPFilter() *schema.Resource { @@ -31,7 +32,7 @@ func resourceSysdigIPFilter() *schema.Resource { } } -func resourceSysdigIPFilterRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilterRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -42,9 +43,9 @@ func resourceSysdigIPFilterRead(ctx context.Context, d *schema.ResourceData, m i return diag.FromErr(err) } - ipFilter, err := client.GetIPFilterById(ctx, id) + ipFilter, err := client.GetIPFilterByID(ctx, id) if err != nil { - if err == v2.IPFilterNotFound { + if err == v2.ErrIPFilterNotFound { d.SetId("") return nil } @@ -59,7 +60,7 @@ func resourceSysdigIPFilterRead(ctx context.Context, d *schema.ResourceData, m i return nil } -func resourceSysdigIPFilterCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilterCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -82,7 +83,7 @@ func resourceSysdigIPFilterCreate(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigIPFilterUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilterUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -96,7 +97,6 @@ func resourceSysdigIPFilterUpdate(ctx context.Context, d *schema.ResourceData, m id, err := strconv.Atoi(d.Id()) if err != nil { return diag.FromErr(err) - } ipFilter.ID = id @@ -110,7 +110,7 @@ func resourceSysdigIPFilterUpdate(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigIPFilterDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilterDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_ip_filter_test.go b/sysdig/resource_sysdig_ip_filter_test.go index 86146e72e..1205e1aab 100644 --- a/sysdig/resource_sysdig_ip_filter_test.go +++ b/sysdig/resource_sysdig_ip_filter_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_ip_filtering_settings.go b/sysdig/resource_sysdig_ip_filtering_settings.go index 2ae25037d..b999e1cfe 100644 --- a/sysdig/resource_sysdig_ip_filtering_settings.go +++ b/sysdig/resource_sysdig_ip_filtering_settings.go @@ -2,6 +2,7 @@ package sysdig import ( "context" + v2 "github.com/draios/terraform-provider-sysdig/sysdig/internal/client/v2" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -22,7 +23,7 @@ func resourceSysdigIPFilteringSettings() *schema.Resource { } } -func resourceSysdigIPFilteringSettingsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilteringSettingsRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -41,22 +42,21 @@ func resourceSysdigIPFilteringSettingsRead(ctx context.Context, d *schema.Resour return nil } -func resourceSysdigIPFilteringSettingsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - +func resourceSysdigIPFilteringSettingsCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { d.SetId("ip_filtering_settings_id") // It's singleton resource so we use a fixed ID return updateIPFilteringSettings(ctx, d, m) } -func resourceSysdigIPFilteringSettingsUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilteringSettingsUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { return updateIPFilteringSettings(ctx, d, m) } -func resourceSysdigIPFilteringSettingsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigIPFilteringSettingsDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { return nil } -func updateIPFilteringSettings(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func updateIPFilteringSettings(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_ip_filtering_settings_test.go b/sysdig/resource_sysdig_ip_filtering_settings_test.go index f2f52a0e6..1ffae9378 100644 --- a/sysdig/resource_sysdig_ip_filtering_settings_test.go +++ b/sysdig/resource_sysdig_ip_filtering_settings_test.go @@ -1,12 +1,11 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( "fmt" - "github.com/draios/terraform-provider-sysdig/sysdig" "testing" + "github.com/draios/terraform-provider-sysdig/sysdig" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) diff --git a/sysdig/resource_sysdig_monitor_alert_anomaly.go b/sysdig/resource_sysdig_monitor_alert_anomaly.go index 85c787395..cccee538e 100644 --- a/sysdig/resource_sysdig_monitor_alert_anomaly.go +++ b/sysdig/resource_sysdig_monitor_alert_anomaly.go @@ -46,7 +46,7 @@ func resourceSysdigMonitorAlertAnomaly() *schema.Resource { } } -func resourceSysdigAlertAnomalyCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertAnomalyCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -67,7 +67,7 @@ func resourceSysdigAlertAnomalyCreate(ctx context.Context, data *schema.Resource return nil } -func resourceSysdigAlertAnomalyUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertAnomalyUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -88,7 +88,7 @@ func resourceSysdigAlertAnomalyUpdate(ctx context.Context, data *schema.Resource return nil } -func resourceSysdigAlertAnomalyRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertAnomalyRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -113,7 +113,7 @@ func resourceSysdigAlertAnomalyRead(ctx context.Context, data *schema.ResourceDa return nil } -func resourceSysdigAlertAnomalyDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertAnomalyDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -124,7 +124,7 @@ func resourceSysdigAlertAnomalyDelete(ctx context.Context, data *schema.Resource return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -140,16 +140,16 @@ func anomalyAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, e alert.Type = "BASELINE" - for _, metric := range data.Get("monitor").([]interface{}) { + for _, metric := range data.Get("monitor").([]any) { alert.Monitor = append(alert.Monitor, &v2.Monitor{ Metric: metric.(string), StdDevFactor: 2, }) } - if alerts_by, ok := data.GetOk("multiple_alerts_by"); ok { + if alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alerts_by.([]interface{}) { + for _, v := range alertsBy.([]any) { alert.SegmentBy = append(alert.SegmentBy, v.(string)) } } @@ -165,10 +165,10 @@ func anomalyAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err _ = data.Set("multiple_alerts_by", alert.SegmentBy) - monitor_metrics := []string{} + monitorMetrics := []string{} for _, v := range alert.Monitor { - monitor_metrics = append(monitor_metrics, v.Metric) + monitorMetrics = append(monitorMetrics, v.Metric) } - _ = data.Set("monitor", monitor_metrics) + _ = data.Set("monitor", monitorMetrics) return } diff --git a/sysdig/resource_sysdig_monitor_alert_anomaly_test.go b/sysdig/resource_sysdig_monitor_alert_anomaly_test.go index 74cb1057b..7e65d867b 100644 --- a/sysdig/resource_sysdig_monitor_alert_anomaly_test.go +++ b/sysdig/resource_sysdig_monitor_alert_anomaly_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_common.go b/sysdig/resource_sysdig_monitor_alert_common.go index 77da0efd5..ba7c14797 100644 --- a/sysdig/resource_sysdig_monitor_alert_common.go +++ b/sysdig/resource_sysdig_monitor_alert_common.go @@ -2,6 +2,7 @@ package sysdig import ( "errors" + "maps" "regexp" "strings" "time" @@ -116,16 +117,14 @@ func createAlertSchema(original map[string]*schema.Schema) map[string]*schema.Sc }, } - for k, v := range original { - alertSchema[k] = v - } + maps.Copy(alertSchema, original) return alertSchema } func alertFromResourceData(d *schema.ResourceData) (alert *v2.Alert, err error) { - trigger_after_minutes := time.Duration(d.Get("trigger_after_minutes").(int)) * time.Minute - timespan := int(trigger_after_minutes.Microseconds()) + triggerAfterMinutes := time.Duration(d.Get("trigger_after_minutes").(int)) * time.Minute + timespan := int(triggerAfterMinutes.Microseconds()) alert = &v2.Alert{ Name: d.Get("name").(string), Type: "MANUAL", @@ -203,16 +202,16 @@ func alertFromResourceData(d *schema.ResourceData) (alert *v2.Alert, err error) } func alertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - var trigger_after_minutes int + var triggerAfterMinutes int if alert.Timespan != nil { - trigger_after_minutes = int((time.Duration(*alert.Timespan) * time.Microsecond).Minutes()) + triggerAfterMinutes = int((time.Duration(*alert.Timespan) * time.Microsecond).Minutes()) } _ = data.Set("version", alert.Version) _ = data.Set("name", alert.Name) _ = data.Set("description", alert.Description) _ = data.Set("scope", alert.Filter) - _ = data.Set("trigger_after_minutes", trigger_after_minutes) + _ = data.Set("trigger_after_minutes", triggerAfterMinutes) _ = data.Set("group_name", alert.GroupName) _ = data.Set("team", alert.TeamID) _ = data.Set("enabled", alert.Enabled) @@ -228,7 +227,7 @@ func alertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) if alert.CustomNotification != nil && (alert.CustomNotification.TitleTemplate != defaultAlertTitle || alert.CustomNotification.AppendText != "" || alert.CustomNotification.PrependText != "") { - customNotification := map[string]interface{}{ + customNotification := map[string]any{ "title": alert.CustomNotification.TitleTemplate, } @@ -240,18 +239,18 @@ func alertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) customNotification["prepend"] = alert.CustomNotification.PrependText } - _ = data.Set("custom_notification", []interface{}{customNotification}) + _ = data.Set("custom_notification", []any{customNotification}) } if alert.SysdigCapture != nil && alert.SysdigCapture.Enabled { - capture := map[string]interface{}{ + capture := map[string]any{ "filename": alert.SysdigCapture.Name, "duration": alert.SysdigCapture.Duration, } if alert.SysdigCapture.Filters != "" { capture["filters"] = alert.SysdigCapture.Filters } - _ = data.Set("capture", []interface{}{capture}) + _ = data.Set("capture", []any{capture}) } return @@ -259,7 +258,7 @@ func alertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) func sysdigCaptureFromSet(d *schema.Set) (captures []*v2.SysdigCapture, err error) { for _, v := range d.List() { - m := v.(map[string]interface{}) + m := v.(map[string]any) capture := &v2.SysdigCapture{ Name: m["filename"].(string), Duration: m["duration"].(int), diff --git a/sysdig/resource_sysdig_monitor_alert_downtime.go b/sysdig/resource_sysdig_monitor_alert_downtime.go index 9f803e88e..7c0d21f95 100644 --- a/sysdig/resource_sysdig_monitor_alert_downtime.go +++ b/sysdig/resource_sysdig_monitor_alert_downtime.go @@ -48,7 +48,7 @@ func resourceSysdigMonitorAlertDowntime() *schema.Resource { } } -func resourceSysdigAlertDowntimeCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertDowntimeCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -70,7 +70,7 @@ func resourceSysdigAlertDowntimeCreate(ctx context.Context, data *schema.Resourc return nil } -func resourceSysdigAlertDowntimeUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertDowntimeUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -91,7 +91,7 @@ func resourceSysdigAlertDowntimeUpdate(ctx context.Context, data *schema.Resourc return nil } -func resourceSysdigAlertDowntimeRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertDowntimeRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -116,7 +116,7 @@ func resourceSysdigAlertDowntimeRead(ctx context.Context, data *schema.ResourceD return nil } -func resourceSysdigAlertDowntimeDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertDowntimeDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -127,7 +127,7 @@ func resourceSysdigAlertDowntimeDelete(ctx context.Context, data *schema.Resourc return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -144,7 +144,7 @@ func downtimeAlertFromResourceData(d *schema.ResourceData) (alert *v2.Alert, err alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} alert.Condition = fmt.Sprintf("avg(timeAvg(uptime)) <= %.2f", 1.0-(cast.ToFloat64(d.Get("trigger_after_pct"))/100.0)) - entitiesRaw := d.Get("entities_to_monitor").([]interface{}) + entitiesRaw := d.Get("entities_to_monitor").([]any) for _, entityRaw := range entitiesRaw { alert.SegmentBy = append(alert.SegmentBy, entityRaw.(string)) } @@ -158,11 +158,11 @@ func downtimeAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (er return } - var trigger_after_pct float64 - _, _ = fmt.Sscanf(alert.Condition, "avg(timeAvg(uptime)) <= %f", &trigger_after_pct) - trigger_after_pct = (1 - trigger_after_pct) * 100 + var triggerAfterPct float64 + _, _ = fmt.Sscanf(alert.Condition, "avg(timeAvg(uptime)) <= %f", &triggerAfterPct) + triggerAfterPct = (1 - triggerAfterPct) * 100 - _ = data.Set("trigger_after_pct", int(trigger_after_pct)) + _ = data.Set("trigger_after_pct", int(triggerAfterPct)) _ = data.Set("entities_to_monitor", alert.SegmentBy) return diff --git a/sysdig/resource_sysdig_monitor_alert_downtime_test.go b/sysdig/resource_sysdig_monitor_alert_downtime_test.go index 57184f90e..da860703c 100644 --- a/sysdig/resource_sysdig_monitor_alert_downtime_test.go +++ b/sysdig/resource_sysdig_monitor_alert_downtime_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_event.go b/sysdig/resource_sysdig_monitor_alert_event.go index cd245a616..6a9d0818b 100644 --- a/sysdig/resource_sysdig_monitor_alert_event.go +++ b/sysdig/resource_sysdig_monitor_alert_event.go @@ -59,7 +59,7 @@ func resourceSysdigMonitorAlertEvent() *schema.Resource { } } -func resourceSysdigAlertEventCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertEventCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -81,7 +81,7 @@ func resourceSysdigAlertEventCreate(ctx context.Context, data *schema.ResourceDa return nil } -func resourceSysdigAlertEventUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertEventUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -102,7 +102,7 @@ func resourceSysdigAlertEventUpdate(ctx context.Context, data *schema.ResourceDa return nil } -func resourceSysdigAlertEventRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertEventRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -127,7 +127,7 @@ func resourceSysdigAlertEventRead(ctx context.Context, data *schema.ResourceData return nil } -func resourceSysdigAlertEventDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertEventDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -138,7 +138,7 @@ func resourceSysdigAlertEventDelete(ctx context.Context, data *schema.ResourceDa return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -152,18 +152,18 @@ func eventAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err return } - event_rel := data.Get("event_rel").(string) - event_count := data.Get("event_count").(int) - alert.Condition = fmt.Sprintf("count(customEvent) %s %d", event_rel, event_count) + eventRel := data.Get("event_rel").(string) + eventCount := data.Get("event_count").(int) + alert.Condition = fmt.Sprintf("count(customEvent) %s %d", eventRel, eventCount) alert.Type = "EVENT" alert.Criteria = &v2.Criteria{ Text: data.Get("event_name").(string), Source: data.Get("source").(string), } - if alerts_by, ok := data.GetOk("multiple_alerts_by"); ok { + if alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alerts_by.([]interface{}) { + for _, v := range alertsBy.([]any) { alert.SegmentBy = append(alert.SegmentBy, v.(string)) } } @@ -187,14 +187,14 @@ func eventAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err e return fmt.Errorf("alert condition %s does not match expected expression %s", alert.Condition, alertConditionRegex.String()) } - event_rel := matches[relIndex] - event_count, err := strconv.Atoi(matches[countIndex]) + eventRel := matches[relIndex] + eventCount, err := strconv.Atoi(matches[countIndex]) if err != nil { return } - _ = data.Set("event_rel", event_rel) - _ = data.Set("event_count", event_count) + _ = data.Set("event_rel", eventRel) + _ = data.Set("event_count", eventCount) _ = data.Set("event_name", alert.Criteria.Text) _ = data.Set("source", alert.Criteria.Source) _ = data.Set("multiple_alerts_by", alert.SegmentBy) diff --git a/sysdig/resource_sysdig_monitor_alert_event_test.go b/sysdig/resource_sysdig_monitor_alert_event_test.go index a9e715a88..50e9bcfab 100644 --- a/sysdig/resource_sysdig_monitor_alert_event_test.go +++ b/sysdig/resource_sysdig_monitor_alert_event_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_group_outlier.go b/sysdig/resource_sysdig_monitor_alert_group_outlier.go index d116d987d..a181c3492 100644 --- a/sysdig/resource_sysdig_monitor_alert_group_outlier.go +++ b/sysdig/resource_sysdig_monitor_alert_group_outlier.go @@ -41,7 +41,7 @@ func resourceSysdigMonitorAlertGroupOutlier() *schema.Resource { } } -func resourceSysdigAlertGroupOutlierCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertGroupOutlierCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -63,7 +63,7 @@ func resourceSysdigAlertGroupOutlierCreate(ctx context.Context, data *schema.Res return nil } -func resourceSysdigAlertGroupOutlierUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertGroupOutlierUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -84,7 +84,7 @@ func resourceSysdigAlertGroupOutlierUpdate(ctx context.Context, data *schema.Res return nil } -func resourceSysdigAlertGroupOutlierRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertGroupOutlierRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -109,7 +109,7 @@ func resourceSysdigAlertGroupOutlierRead(ctx context.Context, data *schema.Resou return nil } -func resourceSysdigAlertGroupOutlierDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertGroupOutlierDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -120,7 +120,7 @@ func resourceSysdigAlertGroupOutlierDelete(ctx context.Context, data *schema.Res return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -136,7 +136,7 @@ func groupOutlierAlertFromResourceData(data *schema.ResourceData) (alert *v2.Ale alert.Type = "HOST_COMPARISON" - for _, metric := range data.Get("monitor").([]interface{}) { + for _, metric := range data.Get("monitor").([]any) { alert.Monitor = append(alert.Monitor, &v2.Monitor{ Metric: metric.(string), StdDevFactor: 2, @@ -155,11 +155,11 @@ func groupOutlierAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) return } - monitor_metrics := []string{} + monitorMetrics := []string{} for _, v := range alert.Monitor { - monitor_metrics = append(monitor_metrics, v.Metric) + monitorMetrics = append(monitorMetrics, v.Metric) } - _ = data.Set("monitor", monitor_metrics) + _ = data.Set("monitor", monitorMetrics) return } diff --git a/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go b/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go index a942142c5..8641566b8 100644 --- a/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go +++ b/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_metric.go b/sysdig/resource_sysdig_monitor_alert_metric.go index 6e90f0d85..aa38b269a 100644 --- a/sysdig/resource_sysdig_monitor_alert_metric.go +++ b/sysdig/resource_sysdig_monitor_alert_metric.go @@ -45,7 +45,7 @@ func resourceSysdigMonitorAlertMetric() *schema.Resource { } } -func resourceSysdigAlertMetricCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertMetricCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -67,7 +67,7 @@ func resourceSysdigAlertMetricCreate(ctx context.Context, data *schema.ResourceD return nil } -func resourceSysdigAlertMetricUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertMetricUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -88,7 +88,7 @@ func resourceSysdigAlertMetricUpdate(ctx context.Context, data *schema.ResourceD return nil } -func resourceSysdigAlertMetricRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertMetricRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -113,7 +113,7 @@ func resourceSysdigAlertMetricRead(ctx context.Context, data *schema.ResourceDat return nil } -func resourceSysdigAlertMetricDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertMetricDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -124,7 +124,7 @@ func resourceSysdigAlertMetricDelete(ctx context.Context, data *schema.ResourceD return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -139,9 +139,9 @@ func metricAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, er } alert.Condition = data.Get("metric").(string) - if alerts_by, ok := data.GetOk("multiple_alerts_by"); ok { + if alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alerts_by.([]interface{}) { + for _, v := range alertsBy.([]any) { alert.SegmentBy = append(alert.SegmentBy, v.(string)) } } diff --git a/sysdig/resource_sysdig_monitor_alert_metric_test.go b/sysdig/resource_sysdig_monitor_alert_metric_test.go index dc5292c6b..7c440d201 100644 --- a/sysdig/resource_sysdig_monitor_alert_metric_test.go +++ b/sysdig/resource_sysdig_monitor_alert_metric_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_promql.go b/sysdig/resource_sysdig_monitor_alert_promql.go index 356f4e679..efefda37d 100644 --- a/sysdig/resource_sysdig_monitor_alert_promql.go +++ b/sysdig/resource_sysdig_monitor_alert_promql.go @@ -40,7 +40,7 @@ func resourceSysdigMonitorAlertPromql() *schema.Resource { } } -func resourceSysdigAlertPromqlCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertPromqlCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -62,7 +62,7 @@ func resourceSysdigAlertPromqlCreate(ctx context.Context, data *schema.ResourceD return nil } -func resourceSysdigAlertPromqlUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertPromqlUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -83,7 +83,7 @@ func resourceSysdigAlertPromqlUpdate(ctx context.Context, data *schema.ResourceD return nil } -func resourceSysdigAlertPromqlRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertPromqlRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -108,7 +108,7 @@ func resourceSysdigAlertPromqlRead(ctx context.Context, data *schema.ResourceDat return nil } -func resourceSysdigAlertPromqlDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigAlertPromqlDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorAlertClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -119,7 +119,7 @@ func resourceSysdigAlertPromqlDelete(ctx context.Context, data *schema.ResourceD return diag.FromErr(err) } - err = client.DeleteAlert(ctx, id) + err = client.DeleteAlertByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -150,8 +150,8 @@ func promqlAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err } if alert.Duration != nil { - trigger_after_minutes := int((time.Duration(*alert.Duration) * time.Second).Minutes()) - _ = data.Set("trigger_after_minutes", trigger_after_minutes) + triggerAfterMinutes := int((time.Duration(*alert.Duration) * time.Second).Minutes()) + _ = data.Set("trigger_after_minutes", triggerAfterMinutes) } _ = data.Set("promql", alert.Condition) diff --git a/sysdig/resource_sysdig_monitor_alert_promql_test.go b/sysdig/resource_sysdig_monitor_alert_promql_test.go index eb14c54d5..215440b87 100644 --- a/sysdig/resource_sysdig_monitor_alert_promql_test.go +++ b/sysdig/resource_sysdig_monitor_alert_promql_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_change.go b/sysdig/resource_sysdig_monitor_alert_v2_change.go index ea28b57d5..dce111c40 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_change.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_change.go @@ -134,7 +134,7 @@ func resourceSysdigMonitorAlertV2Change() *schema.Resource { }, })), - CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error { + CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i any) error { shorterTimeRangeSeconds := diff.Get("shorter_time_range_seconds").(int) longerTimeRangeSeconds := diff.Get("longer_time_range_seconds").(int) @@ -165,7 +165,7 @@ func getAlertV2ChangeClient(c SysdigClients) (v2.AlertV2ChangeInterface, error) return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2ChangeCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2ChangeCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2ChangeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -191,7 +191,7 @@ func resourceSysdigMonitorAlertV2ChangeCreate(ctx context.Context, d *schema.Res return nil } -func resourceSysdigMonitorAlertV2ChangeRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2ChangeRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2ChangeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -202,9 +202,9 @@ func resourceSysdigMonitorAlertV2ChangeRead(ctx context.Context, d *schema.Resou return diag.FromErr(err) } - a, err := client.GetAlertV2Change(ctx, id) + a, err := client.GetAlertV2ChangeByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -219,7 +219,7 @@ func resourceSysdigMonitorAlertV2ChangeRead(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigMonitorAlertV2ChangeUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2ChangeUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2ChangeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -245,7 +245,7 @@ func resourceSysdigMonitorAlertV2ChangeUpdate(ctx context.Context, d *schema.Res return nil } -func resourceSysdigMonitorAlertV2ChangeDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2ChangeDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2ChangeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_change_test.go b/sysdig/resource_sysdig_monitor_alert_v2_change_test.go index 140c5a6cf..0c8f333bf 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_change_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_change_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_common.go b/sysdig/resource_sysdig_monitor_alert_v2_common.go index ae7b82f97..5ef605c4f 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_common.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_common.go @@ -1,6 +1,7 @@ package sysdig import ( + "maps" "regexp" "strings" "time" @@ -183,9 +184,7 @@ func createAlertV2Schema(original map[string]*schema.Schema) map[string]*schema. }, } - for k, v := range original { - alertSchema[k] = v - } + maps.Copy(alertSchema, original) return alertSchema } @@ -238,7 +237,7 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { channels := []v2.NotificationChannelConfigV2{} for _, channel := range attr.(*schema.Set).List() { - channelMap := channel.(map[string]interface{}) + channelMap := channel.(map[string]any) newChannel := v2.NotificationChannelConfigV2{ ChannelID: channelMap["id"].(int), // Type: will be added by the sysdig client before the put/post @@ -255,12 +254,12 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { newChannel.OverrideOptions.NotifyOnResolve = channelMap["notify_on_resolve"].(bool) newChannel.OverrideOptions.Thresholds = []string{} - main_threshold := channelMap["main_threshold"].(bool) - if main_threshold { + mainThreshold := channelMap["main_threshold"].(bool) + if mainThreshold { newChannel.OverrideOptions.Thresholds = append(newChannel.OverrideOptions.Thresholds, "MAIN") } - warning_threshold := channelMap["warning_threshold"].(bool) - if warning_threshold { + warningThreshold := channelMap["warning_threshold"].(bool) + if warningThreshold { newChannel.OverrideOptions.Thresholds = append(newChannel.OverrideOptions.Thresholds, "WARNING") } @@ -271,8 +270,8 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { customNotification := v2.CustomNotificationTemplateV2{} if attr, ok := d.GetOk("custom_notification"); ok && attr != nil { - if len(attr.([]interface{})) > 0 { - m := attr.([]interface{})[0].(map[string]interface{}) + if len(attr.([]any)) > 0 { + m := attr.([]any)[0].(map[string]any) customNotification.Subject = m["subject"].(string) customNotification.AppendText = m["append"].(string) @@ -284,8 +283,8 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { if attr, ok := d.GetOk("capture"); ok && attr != nil { capture := v2.CaptureConfigV2{} - if len(attr.([]interface{})) > 0 { - m := attr.([]interface{})[0].(map[string]interface{}) + if len(attr.([]any)) > 0 { + m := attr.([]any)[0].(map[string]any) capture.DurationSec = m["duration_seconds"].(int) capture.FileName = m["filename"].(string) @@ -302,7 +301,7 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { alert.Links = []v2.AlertLinkV2{} if attr, ok := d.GetOk("link"); ok && attr != nil { for _, link := range attr.(*schema.Set).List() { - linkMap := link.(map[string]interface{}) + linkMap := link.(map[string]any) alert.Links = append(alert.Links, v2.AlertLinkV2{ Type: linkMap["type"].(string), Href: linkMap["href"].(string), @@ -311,7 +310,7 @@ func buildAlertV2CommonStruct(d *schema.ResourceData) *v2.AlertV2Common { } } - alert.Labels = d.Get("labels").(map[string]interface{}) + alert.Labels = d.Get("labels").(map[string]any) return alert } @@ -332,9 +331,9 @@ func updateAlertV2CommonState(d *schema.ResourceData, alert *v2.AlertV2Common) ( _ = d.Set("team", alert.TeamID) _ = d.Set("version", alert.Version) - var notificationChannels []interface{} + var notificationChannels []any for _, ncc := range alert.NotificationChannelConfigList { - config := map[string]interface{}{ + config := map[string]any{ "id": ncc.ChannelID, "notify_on_resolve": ncc.OverrideOptions.NotifyOnResolve, } @@ -366,19 +365,19 @@ func updateAlertV2CommonState(d *schema.ResourceData, alert *v2.AlertV2Common) ( } _ = d.Set("notification_channels", notificationChannels) - if alert.CustomNotificationTemplate != nil && !(alert.CustomNotificationTemplate.Subject == "" && - alert.CustomNotificationTemplate.AppendText == "" && - alert.CustomNotificationTemplate.PrependText == "") { - customNotification := map[string]interface{}{} + if alert.CustomNotificationTemplate != nil && (alert.CustomNotificationTemplate.Subject != "" || + alert.CustomNotificationTemplate.AppendText != "" || + alert.CustomNotificationTemplate.PrependText != "") { + customNotification := map[string]any{} customNotification["subject"] = alert.CustomNotificationTemplate.Subject customNotification["append"] = alert.CustomNotificationTemplate.AppendText customNotification["prepend"] = alert.CustomNotificationTemplate.PrependText - _ = d.Set("custom_notification", []interface{}{customNotification}) + _ = d.Set("custom_notification", []any{customNotification}) } if alert.CaptureConfig != nil { - capture := map[string]interface{}{ + capture := map[string]any{ "duration_seconds": alert.CaptureConfig.DurationSec, "storage": alert.CaptureConfig.Storage, "filename": alert.CaptureConfig.FileName, @@ -386,13 +385,13 @@ func updateAlertV2CommonState(d *schema.ResourceData, alert *v2.AlertV2Common) ( "filter": alert.CaptureConfig.Filter, } - _ = d.Set("capture", []interface{}{capture}) + _ = d.Set("capture", []any{capture}) } if alert.Links != nil { - var links []interface{} + var links []any for _, link := range alert.Links { - links = append(links, map[string]interface{}{ + links = append(links, map[string]any{ "type": link.Type, "href": link.Href, "id": link.ID, @@ -438,9 +437,7 @@ func createScopedSegmentedAlertV2Schema(original map[string]*schema.Schema) map[ }, } - for k, v := range original { - sysdigAlertSchema[k] = v - } + maps.Copy(sysdigAlertSchema, original) return sysdigAlertSchema } @@ -449,11 +446,11 @@ func buildScopedSegmentedConfigStruct(d *schema.ResourceData, config *v2.ScopedS // scope expressions := make([]v2.ScopeExpressionV2, 0) for _, scope := range d.Get("scope").(*schema.Set).List() { - scopeMap := scope.(map[string]interface{}) + scopeMap := scope.(map[string]any) operator := scopeMap["operator"].(string) operand := scopeMap["label"].(string) value := make([]string, 0) - for _, v := range scopeMap["values"].([]interface{}) { + for _, v := range scopeMap["values"].([]any) { value = append(value, v.(string)) } expressions = append(expressions, v2.ScopeExpressionV2{ @@ -472,7 +469,7 @@ func buildScopedSegmentedConfigStruct(d *schema.ResourceData, config *v2.ScopedS config.SegmentBy = make([]v2.AlertLabelDescriptorV2, 0) labels, ok := d.GetOk("group_by") if ok { - for _, l := range labels.([]interface{}) { + for _, l := range labels.([]any) { config.SegmentBy = append(config.SegmentBy, v2.AlertLabelDescriptorV2{ ID: l.(string), // the sysdig client will rewrite this to be in dot notation }) @@ -482,7 +479,7 @@ func buildScopedSegmentedConfigStruct(d *schema.ResourceData, config *v2.ScopedS func updateScopedSegmentedConfigState(d *schema.ResourceData, config *v2.ScopedSegmentedConfig) error { if config.Scope != nil && len(config.Scope.Expressions) > 0 { - var scope []interface{} + var scope []any for _, e := range config.Scope.Expressions { // operand possibly holds the old dot notation, we want "label" to be in public notation // if the label does not yet exist the descriptor will be empty, use what's in the operand @@ -490,7 +487,7 @@ func updateScopedSegmentedConfigState(d *schema.ResourceData, config *v2.ScopedS if e.Descriptor != nil && e.Descriptor.PublicID != "" { label = e.Descriptor.PublicID } - config := map[string]interface{}{ + config := map[string]any{ "label": label, "operator": e.Operator, "values": e.Value, diff --git a/sysdig/resource_sysdig_monitor_alert_v2_downtime.go b/sysdig/resource_sysdig_monitor_alert_v2_downtime.go index ed92c543b..f353b8453 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_downtime.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_downtime.go @@ -69,7 +69,7 @@ func getAlertV2DowntimeClient(c SysdigClients) (v2.AlertV2DowntimeInterface, err return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2DowntimeCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2DowntimeCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2DowntimeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -92,7 +92,7 @@ func resourceSysdigMonitorAlertV2DowntimeCreate(ctx context.Context, d *schema.R return nil } -func resourceSysdigMonitorAlertV2DowntimeRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2DowntimeRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2DowntimeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -103,9 +103,9 @@ func resourceSysdigMonitorAlertV2DowntimeRead(ctx context.Context, d *schema.Res return diag.FromErr(err) } - a, err := client.GetAlertV2Downtime(ctx, id) + a, err := client.GetAlertV2DowntimeByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -120,7 +120,7 @@ func resourceSysdigMonitorAlertV2DowntimeRead(ctx context.Context, d *schema.Res return nil } -func resourceSysdigMonitorAlertV2DowntimeUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2DowntimeUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2DowntimeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -143,7 +143,7 @@ func resourceSysdigMonitorAlertV2DowntimeUpdate(ctx context.Context, d *schema.R return nil } -func resourceSysdigMonitorAlertV2DowntimeDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2DowntimeDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2DowntimeClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go b/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go index 960319e66..497c4e135 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_event.go b/sysdig/resource_sysdig_monitor_alert_v2_event.go index 82c47f8f4..a9899416f 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_event.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_event.go @@ -78,7 +78,7 @@ func getAlertV2EventClient(c SysdigClients) (v2.AlertV2EventInterface, error) { return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2EventCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2EventCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2EventClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -104,7 +104,7 @@ func resourceSysdigMonitorAlertV2EventCreate(ctx context.Context, d *schema.Reso return nil } -func resourceSysdigMonitorAlertV2EventRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2EventRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2EventClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -115,9 +115,9 @@ func resourceSysdigMonitorAlertV2EventRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - a, err := client.GetAlertV2Event(ctx, id) + a, err := client.GetAlertV2EventByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -131,7 +131,7 @@ func resourceSysdigMonitorAlertV2EventRead(ctx context.Context, d *schema.Resour return nil } -func resourceSysdigMonitorAlertV2EventUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2EventUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2EventClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -157,7 +157,7 @@ func resourceSysdigMonitorAlertV2EventUpdate(ctx context.Context, d *schema.Reso return nil } -func resourceSysdigMonitorAlertV2EventDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2EventDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2EventClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_event_test.go b/sysdig/resource_sysdig_monitor_alert_v2_event_test.go index 4cc9562ec..bbc2a6d34 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_event_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_event_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus.go b/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus.go index 07e46c611..ed1bc5331 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus.go @@ -75,7 +75,7 @@ func getAlertV2FormBasedPrometheusClient(c SysdigClients) (v2.AlertV2FormBasedPr return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2FormBasedPrometheusCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2FormBasedPrometheusCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2FormBasedPrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -101,7 +101,7 @@ func resourceSysdigMonitorAlertV2FormBasedPrometheusCreate(ctx context.Context, return nil } -func resourceSysdigMonitorAlertV2FormBasedPrometheusRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2FormBasedPrometheusRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2FormBasedPrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -112,9 +112,9 @@ func resourceSysdigMonitorAlertV2FormBasedPrometheusRead(ctx context.Context, d return diag.FromErr(err) } - a, err := client.GetAlertV2FormBasedPrometheus(ctx, id) + a, err := client.GetAlertV2FormBasedPrometheusByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -129,7 +129,7 @@ func resourceSysdigMonitorAlertV2FormBasedPrometheusRead(ctx context.Context, d return nil } -func resourceSysdigMonitorAlertV2FormBasedPrometheusUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2FormBasedPrometheusUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2FormBasedPrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -155,7 +155,7 @@ func resourceSysdigMonitorAlertV2FormBasedPrometheusUpdate(ctx context.Context, return nil } -func resourceSysdigMonitorAlertV2FormBasedPrometheusDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2FormBasedPrometheusDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2FormBasedPrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus_test.go b/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus_test.go index c7fe1dfca..cc90bbf83 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_form_based_prometheus_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_group_outlier.go b/sysdig/resource_sysdig_monitor_alert_v2_group_outlier.go index 631da2705..463cd0e96 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_group_outlier.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_group_outlier.go @@ -85,7 +85,7 @@ func resourceSysdigMonitorAlertV2GroupOutlier() *schema.Resource { }, })), - CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error { + CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i any) error { algorithm := diff.Get("algorithm").(string) madThreshold := diff.Get("mad_threshold").(float64) madTolerance := diff.Get("mad_tolerance").(float64) @@ -111,7 +111,7 @@ func getAlertV2GroupOutlierClient(c SysdigClients) (v2.AlertV2GroupOutlierInterf return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2GroupOutlierCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2GroupOutlierCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2GroupOutlierClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -137,7 +137,7 @@ func resourceSysdigMonitorAlertV2GroupOutlierCreate(ctx context.Context, d *sche return nil } -func resourceSysdigMonitorAlertV2GroupOutlierRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2GroupOutlierRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2GroupOutlierClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,9 +148,9 @@ func resourceSysdigMonitorAlertV2GroupOutlierRead(ctx context.Context, d *schema return diag.FromErr(err) } - a, err := client.GetAlertV2GroupOutlier(ctx, id) + a, err := client.GetAlertV2GroupOutlierByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -165,7 +165,7 @@ func resourceSysdigMonitorAlertV2GroupOutlierRead(ctx context.Context, d *schema return nil } -func resourceSysdigMonitorAlertV2GroupOutlierUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2GroupOutlierUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2GroupOutlierClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -191,7 +191,7 @@ func resourceSysdigMonitorAlertV2GroupOutlierUpdate(ctx context.Context, d *sche return nil } -func resourceSysdigMonitorAlertV2GroupOutlierDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2GroupOutlierDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2GroupOutlierClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_group_outlier_test.go b/sysdig/resource_sysdig_monitor_alert_v2_group_outlier_test.go index 6becff498..4c996fcc9 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_group_outlier_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_group_outlier_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_metric.go b/sysdig/resource_sysdig_monitor_alert_v2_metric.go index 1d5466cc3..ac7ef72fb 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_metric.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_metric.go @@ -99,7 +99,7 @@ func getAlertV2MetricClient(c SysdigClients) (v2.AlertV2MetricInterface, error) return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2MetricCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2MetricCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2MetricClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -125,7 +125,7 @@ func resourceSysdigMonitorAlertV2MetricCreate(ctx context.Context, d *schema.Res return nil } -func resourceSysdigMonitorAlertV2MetricRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2MetricRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2MetricClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -136,9 +136,9 @@ func resourceSysdigMonitorAlertV2MetricRead(ctx context.Context, d *schema.Resou return diag.FromErr(err) } - a, err := client.GetAlertV2Metric(ctx, id) + a, err := client.GetAlertV2MetricByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -153,7 +153,7 @@ func resourceSysdigMonitorAlertV2MetricRead(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigMonitorAlertV2MetricUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2MetricUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2MetricClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -179,7 +179,7 @@ func resourceSysdigMonitorAlertV2MetricUpdate(ctx context.Context, d *schema.Res return nil } -func resourceSysdigMonitorAlertV2MetricDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2MetricDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2MetricClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go b/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go index 58c9f4788..77562a662 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go index e36482277..b11518a8b 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go @@ -63,7 +63,7 @@ func getAlertV2PrometheusClient(c SysdigClients) (v2.AlertV2PrometheusInterface, return getAlertV2Client(c) } -func resourceSysdigMonitorAlertV2PrometheusCreate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2PrometheusCreate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2PrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -86,7 +86,7 @@ func resourceSysdigMonitorAlertV2PrometheusCreate(ctx context.Context, d *schema return nil } -func resourceSysdigMonitorAlertV2PrometheusRead(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2PrometheusRead(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2PrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -97,9 +97,9 @@ func resourceSysdigMonitorAlertV2PrometheusRead(ctx context.Context, d *schema.R return diag.FromErr(err) } - a, err := client.GetAlertV2Prometheus(ctx, id) + a, err := client.GetAlertV2PrometheusByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -114,7 +114,7 @@ func resourceSysdigMonitorAlertV2PrometheusRead(ctx context.Context, d *schema.R return nil } -func resourceSysdigMonitorAlertV2PrometheusUpdate(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2PrometheusUpdate(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2PrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -137,7 +137,7 @@ func resourceSysdigMonitorAlertV2PrometheusUpdate(ctx context.Context, d *schema return nil } -func resourceSysdigMonitorAlertV2PrometheusDelete(ctx context.Context, d *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorAlertV2PrometheusDelete(ctx context.Context, d *schema.ResourceData, i any) diag.Diagnostics { client, err := getAlertV2PrometheusClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go b/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go index 9b1019423..64c58fa34 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_cloud_account.go b/sysdig/resource_sysdig_monitor_cloud_account.go index 3dbf80bdd..56440d5fb 100644 --- a/sysdig/resource_sysdig_monitor_cloud_account.go +++ b/sysdig/resource_sysdig_monitor_cloud_account.go @@ -76,7 +76,7 @@ func getMonitorCloudAccountClient(c SysdigClients) (v2.CloudAccountMonitorInterf return c.sysdigMonitorClientV2() } -func resourceSysdigMonitorCloudAccountCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorCloudAccountCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorCloudAccountClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -85,27 +85,25 @@ func resourceSysdigMonitorCloudAccountCreate(ctx context.Context, data *schema.R if data.Get("integration_type").(string) == "Cost" { cloudAccount := monitorCloudAccountForCostFromResourceData(data) cloudAccountCreated, err := client.CreateCloudAccountMonitorForCost(ctx, &cloudAccount) - if err != nil { return diag.FromErr(err) } - data.SetId(cloudAccountCreated.Id) + data.SetId(cloudAccountCreated.ID) } else { cloudAccount := monitorCloudAccountFromResourceData(data) cloudAccountCreated, err := client.CreateCloudAccountMonitor(ctx, &cloudAccount) - if err != nil { return diag.FromErr(err) } - data.SetId(strconv.Itoa(cloudAccountCreated.Id)) + data.SetId(strconv.Itoa(cloudAccountCreated.ID)) } return nil } -func resourceSysdigMonitorCloudAccountDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorCloudAccountDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorCloudAccountClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -124,7 +122,7 @@ func resourceSysdigMonitorCloudAccountDelete(ctx context.Context, data *schema.R return nil } -func resourceSysdigMonitorCloudAccountRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorCloudAccountRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorCloudAccountClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -136,7 +134,7 @@ func resourceSysdigMonitorCloudAccountRead(ctx context.Context, data *schema.Res } if data.Get("integration_type").(string) == "Cost" { - cloudAccount, err := client.GetCloudAccountMonitorForCost(ctx, id) + cloudAccount, err := client.GetCloudAccountMonitorForCostByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -146,7 +144,7 @@ func resourceSysdigMonitorCloudAccountRead(ctx context.Context, data *schema.Res return diag.FromErr(err) } } else { - cloudAccount, err := client.GetCloudAccountMonitor(ctx, id) + cloudAccount, err := client.GetCloudAccountMonitorByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -160,7 +158,7 @@ func resourceSysdigMonitorCloudAccountRead(ctx context.Context, data *schema.Res return nil } -func resourceSysdigMonitorCloudAccountUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigMonitorCloudAccountUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorCloudAccountClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -174,7 +172,7 @@ func resourceSysdigMonitorCloudAccountUpdate(ctx context.Context, data *schema.R if data.Get("integration_type").(string) == "Cost" { putObjectAccount := monitorCloudAccountForCostFromResourceDataPutMethod(data) - cloudAccount, err := client.GetCloudAccountMonitorForCost(ctx, id) + cloudAccount, err := client.GetCloudAccountMonitorForCostByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -208,19 +206,18 @@ func monitorCloudAccountFromResourceData(data *schema.ResourceData) v2.CloudAcco IntegrationType: data.Get("integration_type").(string), AdditionalOptions: data.Get("additional_options").(string), Credentials: v2.CloudAccountCredentialsMonitor{ - AccountId: data.Get("account_id").(string), + AccountID: data.Get("account_id").(string), RoleName: data.Get("role_name").(string), SecretKey: data.Get("secret_key").(string), - AccessKeyId: data.Get("access_key_id").(string), + AccessKeyID: data.Get("access_key_id").(string), }, } } func monitorCloudAccountForCostFromResourceData(data *schema.ResourceData) v2.CloudAccountMonitorForCost { - configuration := v2.CloudCostConfiguration{} - if config, ok := data.Get("config").(map[string]interface{}); ok { + if config, ok := data.Get("config").(map[string]any); ok { if val, exists := config["athena_bucket_name"]; exists { configuration.AthenaBucketName = val.(string) } @@ -246,7 +243,7 @@ func monitorCloudAccountForCostFromResourceData(data *schema.ResourceData) v2.Cl Platform: data.Get("cloud_provider").(string), Configuration: configuration, Credentials: v2.CloudAccountCredentialsMonitor{ - AccountId: data.Get("account_id").(string), + AccountID: data.Get("account_id").(string), RoleName: data.Get("role_name").(string), }, } @@ -257,12 +254,12 @@ func monitorCloudAccountForCostFromResourceDataPutMethod(data *schema.ResourceDa Provider: data.Get("cloud_provider").(string), RoleArn: "arn:aws:iam::" + data.Get("account_id").(string) + ":role/" + data.Get("role_name").(string), Config: v2.CloudConfigForCost{ - AthenaBucketName: data.Get("config").(map[string]interface{})["athena_bucket_name"].(string), - AthenaDatabaseName: data.Get("config").(map[string]interface{})["athena_database_name"].(string), - AthenaRegion: data.Get("config").(map[string]interface{})["athena_region"].(string), - AthenaWorkgroup: data.Get("config").(map[string]interface{})["athena_workgroup"].(string), - AthenaTableName: data.Get("config").(map[string]interface{})["athena_table_name"].(string), - SpotPricesBucketName: data.Get("config").(map[string]interface{})["spot_prices_bucket_name"].(string), + AthenaBucketName: data.Get("config").(map[string]any)["athena_bucket_name"].(string), + AthenaDatabaseName: data.Get("config").(map[string]any)["athena_database_name"].(string), + AthenaRegion: data.Get("config").(map[string]any)["athena_region"].(string), + AthenaWorkgroup: data.Get("config").(map[string]any)["athena_workgroup"].(string), + AthenaTableName: data.Get("config").(map[string]any)["athena_table_name"].(string), + SpotPricesBucketName: data.Get("config").(map[string]any)["spot_prices_bucket_name"].(string), IntegrationType: data.Get("integration_type").(string), }, } @@ -284,7 +281,7 @@ func monitorCloudAccountToResourceData(data *schema.ResourceData, cloudAccount * return err } - err = data.Set("account_id", cloudAccount.Credentials.AccountId) + err = data.Set("account_id", cloudAccount.Credentials.AccountID) if err != nil { return err } @@ -299,7 +296,7 @@ func monitorCloudAccountToResourceData(data *schema.ResourceData, cloudAccount * return err } - err = data.Set("access_key_id", cloudAccount.Credentials.AccessKeyId) + err = data.Set("access_key_id", cloudAccount.Credentials.AccessKeyID) if err != nil { return err } @@ -313,7 +310,7 @@ func monitorCloudAccountForCostToResourceData(data *schema.ResourceData, cloudAc return err } - err = data.Set("config", map[string]interface{}{ + err = data.Set("config", map[string]any{ "athena_bucket_name": cloudAccount.Config.AthenaBucketName, "athena_database_name": cloudAccount.Config.AthenaDatabaseName, "athena_region": cloudAccount.Config.AthenaRegion, @@ -330,7 +327,7 @@ func monitorCloudAccountForCostToResourceData(data *schema.ResourceData, cloudAc return err } - err = data.Set("account_id", cloudAccount.ProviderId) + err = data.Set("account_id", cloudAccount.ProviderID) if err != nil { return err } @@ -344,11 +341,11 @@ func monitorCloudAccountForCostToResourceData(data *schema.ResourceData, cloudAc } func completeEmptyFieldsForUpdateRequest(putObject *v2.CloudAccountCostProvider, currentStatusObject *v2.CloudAccountCostProvider) { - putObject.ExternalId = currentStatusObject.ExternalId + putObject.ExternalID = currentStatusObject.ExternalID putObject.CredentialsType = currentStatusObject.CredentialsType - putObject.CustomerId = currentStatusObject.CustomerId - putObject.ProviderId = currentStatusObject.ProviderId - putObject.CredentialsId = currentStatusObject.CredentialsId + putObject.CustomerID = currentStatusObject.CustomerID + putObject.ProviderID = currentStatusObject.ProviderID + putObject.CredentialsID = currentStatusObject.CredentialsID putObject.Feature = currentStatusObject.Feature putObject.Enabled = currentStatusObject.Enabled } diff --git a/sysdig/resource_sysdig_monitor_cloud_account_test.go b/sysdig/resource_sysdig_monitor_cloud_account_test.go index fea6f54f5..f86b582f1 100644 --- a/sysdig/resource_sysdig_monitor_cloud_account_test.go +++ b/sysdig/resource_sysdig_monitor_cloud_account_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_dashboard.go b/sysdig/resource_sysdig_monitor_dashboard.go index 3c906775c..bd939c899 100644 --- a/sysdig/resource_sysdig_monitor_dashboard.go +++ b/sysdig/resource_sysdig_monitor_dashboard.go @@ -301,7 +301,7 @@ func getMonitorDashboardClient(c SysdigClients) (v2.DashboardInterface, error) { return client, nil } -func resourceSysdigDashboardCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigDashboardCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorDashboardClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -323,7 +323,7 @@ func resourceSysdigDashboardCreate(ctx context.Context, data *schema.ResourceDat return nil } -func resourceSysdigDashboardUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigDashboardUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorDashboardClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -344,7 +344,7 @@ func resourceSysdigDashboardUpdate(ctx context.Context, data *schema.ResourceDat return nil } -func resourceSysdigDashboardRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigDashboardRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorDashboardClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -355,7 +355,7 @@ func resourceSysdigDashboardRead(ctx context.Context, data *schema.ResourceData, return diag.FromErr(err) } - dashboard, err := client.GetDashboard(ctx, id) + dashboard, err := client.GetDashboardByID(ctx, id) if err != nil { data.SetId("") return nil @@ -369,7 +369,7 @@ func resourceSysdigDashboardRead(ctx context.Context, data *schema.ResourceData, return nil } -func resourceSysdigDashboardDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigDashboardDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getMonitorDashboardClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -417,8 +417,8 @@ func dashboardFromResourceData(data *schema.ResourceData) (dashboard *v2.Dashboa func sharingFromResourceData(data *schema.ResourceData) (sharingSettings []*v2.SharingOptions, err error) { for _, share := range data.Get("share").(*schema.Set).List() { - shareInfo := share.(map[string]interface{}) - memberInfo := shareInfo["member"].(*schema.Set).List()[0].(map[string]interface{}) + shareInfo := share.(map[string]any) + memberInfo := shareInfo["member"].(*schema.Set).List()[0].(map[string]any) sharingSettings = append(sharingSettings, &v2.SharingOptions{ Member: v2.SharingMember{ @@ -433,7 +433,7 @@ func sharingFromResourceData(data *schema.ResourceData) (sharingSettings []*v2.S func panelsFromResourceData(data *schema.ResourceData) (panels []*v2.Panels, err error) { for _, panelItr := range data.Get("panel").(*schema.Set).List() { - panelInfo := panelItr.(map[string]interface{}) + panelInfo := panelItr.(map[string]any) var panel *v2.Panels switch panelInfo["type"].(string) { @@ -464,7 +464,7 @@ func defaultLegendConfiguration() *v2.LegendConfiguration { } } -func legendFromResourceData(data interface{}) *v2.LegendConfiguration { +func legendFromResourceData(data any) *v2.LegendConfiguration { if data == nil { return defaultLegendConfiguration() } @@ -475,7 +475,7 @@ func legendFromResourceData(data interface{}) *v2.LegendConfiguration { return defaultLegendConfiguration() } - legend := legendList[0].(map[string]interface{}) + legend := legendList[0].(map[string]any) return &v2.LegendConfiguration{ Enabled: legend["enabled"].(bool), Position: legend["position"].(string), @@ -484,7 +484,7 @@ func legendFromResourceData(data interface{}) *v2.LegendConfiguration { } } -func timechartPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, error) { +func timechartPanelFromResourceData(panelInfo map[string]any) (*v2.Panels, error) { panel := &v2.Panels{ ID: 0, Name: panelInfo["name"].(string), @@ -547,7 +547,7 @@ func timechartPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panel return panel, nil } -func numberPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, error) { +func numberPanelFromResourceData(panelInfo map[string]any) (*v2.Panels, error) { panel := &v2.Panels{ ID: 0, Name: panelInfo["name"].(string), @@ -595,7 +595,7 @@ func numberPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, TextAutosized: false, TransparentBackground: false, NumberThresholds: &v2.NumberThresholds{ - Values: []interface{}{}, // These values must be not nil in case of type number + Values: []any{}, // These values must be not nil in case of type number Base: v2.NumberThresholdBase{ Severity: "none", }, @@ -623,7 +623,7 @@ func numberPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, return panel, nil } -func textPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, error) { +func textPanelFromResourceData(panelInfo map[string]any) (*v2.Panels, error) { content := panelInfo["content"].(string) panel := &v2.Panels{ ID: 0, @@ -643,7 +643,7 @@ func textPanelFromResourceData(panelInfo map[string]interface{}) (*v2.Panels, er return panel, nil } -func formatFromResourceData(queryInfo map[string]interface{}) *v2.Format { +func formatFromResourceData(queryInfo map[string]any) *v2.Format { formatData, ok := queryInfo["format"] if !ok { return nil @@ -655,7 +655,7 @@ func formatFromResourceData(queryInfo map[string]interface{}) *v2.Format { return nil } - fields := formatSet[0].(map[string]interface{}) + fields := formatSet[0].(map[string]any) format := &v2.Format{} if inputFormat, ok := fields["input_format"].(string); ok { @@ -685,15 +685,15 @@ func formatFromResourceData(queryInfo map[string]interface{}) *v2.Format { return format } -func queriesFromResourceData(panelInfo map[string]interface{}, panel *v2.Panels) (newQueries []*v2.AdvancedQueries, err error) { +func queriesFromResourceData(panelInfo map[string]any, panel *v2.Panels) (newQueries []*v2.AdvancedQueries, err error) { var display v2.DisplayInfo for _, queryItr := range panelInfo["query"].(*schema.Set).List() { - queryInfo := queryItr.(map[string]interface{}) + queryInfo := queryItr.(map[string]any) displayInfo := queryInfo["display_info"].(*schema.Set).List() if len(displayInfo) > 0 { - dip := displayInfo[0].(map[string]interface{}) + dip := displayInfo[0].(map[string]any) display.DisplayName = dip["display_name"].(string) display.TimeSeriesDisplayNameTemplate = dip["time_series_display_name_template"].(string) display.Type = dip["type"].(string) @@ -736,12 +736,12 @@ func dashboardToResourceData(dashboard *v2.Dashboard, data *schema.ResourceData) _ = data.Set("public_token", dashboard.PublicToken) _ = data.Set("min_interval", dashboard.MinInterval) - var panels []map[string]interface{} + var panels []map[string]any for i, panel := range dashboard.Panels { panelsData := data.Get("panel").(*schema.Set).List() - panelData := map[string]interface{}{} + panelData := map[string]any{} if len(panelsData) > i { - panelData = panelsData[i].(map[string]interface{}) + panelData = panelsData[i].(map[string]any) } dPanel, err := panelToResourceData(panel, dashboard.Layout, panelData) @@ -752,7 +752,7 @@ func dashboardToResourceData(dashboard *v2.Dashboard, data *schema.ResourceData) } _ = data.Set("panel", panels) - var scopes []map[string]interface{} + var scopes []map[string]any for _, scope := range dashboard.ScopeExpressionList { dScope, err := scopeToResourceData(scope) if err != nil { @@ -763,7 +763,7 @@ func dashboardToResourceData(dashboard *v2.Dashboard, data *schema.ResourceData) _ = data.Set("scope", scopes) _ = data.Set("version", dashboard.Version) - var shares []map[string]interface{} + var shares []map[string]any for _, share := range dashboard.SharingSettings { dShare, err := shareToResourceData(share) if err != nil { @@ -776,10 +776,10 @@ func dashboardToResourceData(dashboard *v2.Dashboard, data *schema.ResourceData) return nil } -func shareToResourceData(share *v2.SharingOptions) (map[string]interface{}, error) { - res := map[string]interface{}{ +func shareToResourceData(share *v2.SharingOptions) (map[string]any, error) { + res := map[string]any{ "role": share.Role, - "member": []map[string]interface{}{{ + "member": []map[string]any{{ "type": share.Member.Type, "id": share.Member.ID, }}, @@ -787,8 +787,8 @@ func shareToResourceData(share *v2.SharingOptions) (map[string]interface{}, erro return res, nil } -func scopeToResourceData(scope *v2.ScopeExpressionList) (map[string]interface{}, error) { - res := map[string]interface{}{ +func scopeToResourceData(scope *v2.ScopeExpressionList) (map[string]any, error) { + res := map[string]any{ "metric": scope.Operand, } @@ -807,7 +807,7 @@ func scopeToResourceData(scope *v2.ScopeExpressionList) (map[string]interface{}, func scopeFromResourceData(data *schema.ResourceData) ([]*v2.ScopeExpressionList, error) { scopes := []*v2.ScopeExpressionList{} for _, scopeItr := range data.Get("scope").(*schema.Set).List() { - scopeInfo := (scopeItr).(map[string]interface{}) + scopeInfo := (scopeItr).(map[string]any) scope := &v2.ScopeExpressionList{} scope.Operand = cast.ToString(scopeInfo["metric"]) @@ -840,7 +840,7 @@ func scopeFromResourceData(data *schema.ResourceData) ([]*v2.ScopeExpressionList return scopes, nil } -func panelToResourceData(panel *v2.Panels, layout []*v2.Layout, panelData map[string]interface{}) (map[string]interface{}, error) { +func panelToResourceData(panel *v2.Panels, layout []*v2.Layout, panelData map[string]any) (map[string]any, error) { var panelLayout *v2.Layout for _, l := range layout { @@ -864,13 +864,13 @@ func panelToResourceData(panel *v2.Panels, layout []*v2.Layout, panelData map[st } } -func timechartPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, panelData map[string]interface{}) (map[string]interface{}, error) { +func timechartPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, panelData map[string]any) (map[string]any, error) { queries, err := queriesToResourceData(panel.AdvancedQueries, panelData) if err != nil { return nil, err } - return map[string]interface{}{ + return map[string]any{ "pos_x": panelLayout.X, "pos_y": panelLayout.Y, "width": panelLayout.W, @@ -883,8 +883,7 @@ func timechartPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, pane }, nil } -func legendConfigurationToResourceData(legend *v2.LegendConfiguration, panelData map[string]interface{}) []map[string]interface{} { - +func legendConfigurationToResourceData(legend *v2.LegendConfiguration, panelData map[string]any) []map[string]any { legendData := panelData["legend"] // If legend is not defined in the user configuration and the dashboard legend is the same as the default one // we don't set the legend in the resource data to avoid drifts @@ -894,7 +893,7 @@ func legendConfigurationToResourceData(legend *v2.LegendConfiguration, panelData } } - return []map[string]interface{}{{ + return []map[string]any{{ "enabled": legend.Enabled, "show_current": legend.ShowCurrent, "position": legend.Position, @@ -902,13 +901,13 @@ func legendConfigurationToResourceData(legend *v2.LegendConfiguration, panelData }} } -func numberPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, panelData map[string]interface{}) (map[string]interface{}, error) { +func numberPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, panelData map[string]any) (map[string]any, error) { queries, err := queriesToResourceData(panel.AdvancedQueries, panelData) if err != nil { return nil, err } - return map[string]interface{}{ + return map[string]any{ "pos_x": panelLayout.X, "pos_y": panelLayout.Y, "width": panelLayout.W, @@ -920,8 +919,8 @@ func numberPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout, panelDa }, nil } -func textPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout) (map[string]interface{}, error) { - return map[string]interface{}{ +func textPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout) (map[string]any, error) { + return map[string]any{ "pos_x": panelLayout.X, "pos_y": panelLayout.Y, "width": panelLayout.W, @@ -935,8 +934,8 @@ func textPanelToResourceData(panel *v2.Panels, panelLayout *v2.Layout) (map[stri }, nil } -func queriesToResourceData(advancedQueries []*v2.AdvancedQueries, panelsData map[string]interface{}) ([]map[string]interface{}, error) { - var queries []map[string]interface{} +func queriesToResourceData(advancedQueries []*v2.AdvancedQueries, panelsData map[string]any) ([]map[string]any, error) { + var queries []map[string]any for queryIndex, query := range advancedQueries { unit := "" var defaultFormat v2.Format @@ -963,20 +962,20 @@ func queriesToResourceData(advancedQueries []*v2.AdvancedQueries, panelsData map return nil, fmt.Errorf("unsupported query format unit: %s", query.Format.Unit) } - q := map[string]interface{}{ + q := map[string]any{ "unit": unit, "promql": query.Query, } if query.DisplayInfo.DisplayName != "" || query.DisplayInfo.TimeSeriesDisplayNameTemplate != "" { - q["display_info"] = []map[string]interface{}{{ + q["display_info"] = []map[string]any{{ "display_name": query.DisplayInfo.DisplayName, "time_series_display_name_template": query.DisplayInfo.TimeSeriesDisplayNameTemplate, "type": query.DisplayInfo.Type, }} } - q["format"] = []map[string]interface{}{{ + q["format"] = []map[string]any{{ "decimals": query.Format.Decimals, "display_format": query.Format.DisplayFormat, "input_format": query.Format.InputFormat, @@ -986,9 +985,9 @@ func queriesToResourceData(advancedQueries []*v2.AdvancedQueries, panelsData map }} queriesData := panelsData["query"] - queryData := map[string]interface{}{} + queryData := map[string]any{} if queriesData != nil && queriesData.(*schema.Set).Len() > queryIndex { - queryData = queriesData.(*schema.Set).List()[queryIndex].(map[string]interface{}) + queryData = queriesData.(*schema.Set).List()[queryIndex].(map[string]any) } formatData := queryData["format"] diff --git a/sysdig/resource_sysdig_monitor_dashboard_test.go b/sysdig/resource_sysdig_monitor_dashboard_test.go index c8c372fdc..564359b16 100644 --- a/sysdig/resource_sysdig_monitor_dashboard_test.go +++ b/sysdig/resource_sysdig_monitor_dashboard_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_inhibition_rule.go b/sysdig/resource_sysdig_monitor_inhibition_rule.go index 0436e5d6f..83d867039 100644 --- a/sysdig/resource_sysdig_monitor_inhibition_rule.go +++ b/sysdig/resource_sysdig_monitor_inhibition_rule.go @@ -120,7 +120,7 @@ func getMonitorInhibitionRuleClient(c SysdigClients) (v2.InhibitionRuleInterface return client, nil } -func resourceSysdigMonitorInhibitionRuleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorInhibitionRuleCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorInhibitionRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -141,7 +141,7 @@ func resourceSysdigMonitorInhibitionRuleCreate(ctx context.Context, d *schema.Re return resourceSysdigMonitorInhibitionRuleRead(ctx, d, meta) } -func resourceSysdigMonitorInhibitionRuleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorInhibitionRuleRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorInhibitionRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -152,9 +152,9 @@ func resourceSysdigMonitorInhibitionRuleRead(ctx context.Context, d *schema.Reso return diag.FromErr(err) } - inhibitionRule, err := client.GetInhibitionRule(ctx, id) + inhibitionRule, err := client.GetInhibitionRuleByID(ctx, id) if err != nil { - if err == v2.AlertV2NotFound { + if err == v2.ErrAlertV2NotFound { d.SetId("") return nil } @@ -169,7 +169,7 @@ func resourceSysdigMonitorInhibitionRuleRead(ctx context.Context, d *schema.Reso return nil } -func resourceSysdigMonitorInhibitionRuleUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorInhibitionRuleUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorInhibitionRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -194,7 +194,7 @@ func resourceSysdigMonitorInhibitionRuleUpdate(ctx context.Context, d *schema.Re return nil } -func resourceSysdigMonitorInhibitionRuleDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorInhibitionRuleDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorInhibitionRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -220,8 +220,8 @@ func monitorInhibitionRuleFromResourceData(d *schema.ResourceData) (v2.Inhibitio inhibitionRule.Description = d.Get("description").(string) inhibitionRule.Enabled = d.Get("enabled").(bool) - for _, sourceMatcher := range d.Get("source_matchers").([]interface{}) { - sourceMatcherMap := sourceMatcher.(map[string]interface{}) + for _, sourceMatcher := range d.Get("source_matchers").([]any) { + sourceMatcherMap := sourceMatcher.(map[string]any) labelName := sourceMatcherMap["label_name"].(string) operator := sourceMatcherMap["operator"].(string) value := sourceMatcherMap["value"].(string) @@ -232,8 +232,8 @@ func monitorInhibitionRuleFromResourceData(d *schema.ResourceData) (v2.Inhibitio }) } - for _, targetMatcher := range d.Get("target_matchers").([]interface{}) { - targetMatcherMap := targetMatcher.(map[string]interface{}) + for _, targetMatcher := range d.Get("target_matchers").([]any) { + targetMatcherMap := targetMatcher.(map[string]any) labelName := targetMatcherMap["label_name"].(string) operator := targetMatcherMap["operator"].(string) value := targetMatcherMap["value"].(string) @@ -244,7 +244,7 @@ func monitorInhibitionRuleFromResourceData(d *schema.ResourceData) (v2.Inhibitio }) } - for _, equalItemRaw := range d.Get("equal").([]interface{}) { + for _, equalItemRaw := range d.Get("equal").([]any) { if equalItem, ok := equalItemRaw.(string); ok { inhibitionRule.Equal = append(inhibitionRule.Equal, equalItem) } @@ -259,9 +259,9 @@ func monitorInhibitionRuleToResourceData(inhibitionRule v2.InhibitionRule, d *sc _ = d.Set("description", inhibitionRule.Description) _ = d.Set("enabled", inhibitionRule.Enabled) - var sourceMatchers []interface{} + var sourceMatchers []any for _, m := range inhibitionRule.SourceMatchers { - sourceMatchers = append(sourceMatchers, map[string]interface{}{ + sourceMatchers = append(sourceMatchers, map[string]any{ "label_name": m.LabelName, "operator": m.Operator, "value": m.Value, @@ -269,9 +269,9 @@ func monitorInhibitionRuleToResourceData(inhibitionRule v2.InhibitionRule, d *sc } _ = d.Set("source_matchers", sourceMatchers) - var targetMatchers []interface{} + var targetMatchers []any for _, m := range inhibitionRule.TargetMatchers { - targetMatchers = append(targetMatchers, map[string]interface{}{ + targetMatchers = append(targetMatchers, map[string]any{ "label_name": m.LabelName, "operator": m.Operator, "value": m.Value, diff --git a/sysdig/resource_sysdig_monitor_inhibition_rule_test.go b/sysdig/resource_sysdig_monitor_inhibition_rule_test.go index 021747311..cbb9f8ca9 100644 --- a/sysdig/resource_sysdig_monitor_inhibition_rule_test.go +++ b/sysdig/resource_sysdig_monitor_inhibition_rule_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go index 8b4627384..56c5d93be 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go @@ -59,7 +59,7 @@ func resourceSysdigMonitorNotificationChannelCustomWebhook() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelCustomWebhookCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelCustomWebhookCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorNotificationChannelClient(clients) if err != nil { @@ -86,16 +86,16 @@ func resourceSysdigMonitorNotificationChannelCustomWebhookCreate(ctx context.Con return resourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -110,7 +110,7 @@ func resourceSysdigMonitorNotificationChannelCustomWebhookRead(ctx context.Conte return nil } -func resourceSysdigMonitorNotificationChannelCustomWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelCustomWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -137,7 +137,7 @@ func resourceSysdigMonitorNotificationChannelCustomWebhookUpdate(ctx context.Con return nil } -func resourceSysdigMonitorNotificationChannelCustomWebhookDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelCustomWebhookDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -159,11 +159,11 @@ func monitorNotificationChannelCustomWebhookFromResourceData(d *schema.ResourceD return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_CUSTOM_WEBHOOK - nc.Options.Url = d.Get("url").(string) - nc.Options.HttpMethod = d.Get("http_method").(string) + nc.Type = notificationChannelTypeCustomWebhook + nc.Options.URL = d.Get("url").(string) + nc.Options.HTTPMethod = d.Get("http_method").(string) nc.Options.MonitorTemplate = d.Get("template").(string) - nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]interface{}) + nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections return @@ -175,9 +175,9 @@ func monitorNotificationChannelCustomWebhookToResourceData(nc *v2.NotificationCh return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("additional_headers", nc.Options.AdditionalHeaders) - _ = d.Set("http_method", nc.Options.HttpMethod) + _ = d.Set("http_method", nc.Options.HTTPMethod) _ = d.Set("template", nc.Options.MonitorTemplate) if nc.Options.AllowInsecureConnections != nil { _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) diff --git a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook_test.go b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook_test.go index d73154454..0e8841195 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_email.go b/sysdig/resource_sysdig_monitor_notification_channel_email.go index 69f2971a4..bb01a7b1e 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_email.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_email.go @@ -42,7 +42,7 @@ func resourceSysdigMonitorNotificationChannelEmail() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelEmailCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelEmailCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -68,16 +68,16 @@ func resourceSysdigMonitorNotificationChannelEmailCreate(ctx context.Context, d return resourceSysdigMonitorNotificationChannelEmailRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -92,7 +92,7 @@ func resourceSysdigMonitorNotificationChannelEmailRead(ctx context.Context, d *s return nil } -func resourceSysdigMonitorNotificationChannelEmailUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelEmailUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -119,7 +119,7 @@ func resourceSysdigMonitorNotificationChannelEmailUpdate(ctx context.Context, d return nil } -func resourceSysdigMonitorNotificationChannelEmailDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelEmailDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -141,7 +141,7 @@ func monitorNotificationChannelEmailFromResourceData(d *schema.ResourceData, tea return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_EMAIL + nc.Type = notificationChannelTypeEmail nc.Options.EmailRecipients = cast.ToStringSlice(d.Get("recipients").(*schema.Set).List()) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_email_test.go b/sysdig/resource_sysdig_monitor_notification_channel_email_test.go index a7af499d9..0669bddd9 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_email_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go b/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go index 6b4fdc26d..2648d8415 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go @@ -39,7 +39,7 @@ func resourceSysdigMonitorNotificationChannelGoogleChat() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelGoogleChatCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelGoogleChatCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -65,7 +65,7 @@ func resourceSysdigMonitorNotificationChannelGoogleChatCreate(ctx context.Contex return resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -76,9 +76,9 @@ func resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -93,7 +93,7 @@ func resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelGoogleChatUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelGoogleChatUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -123,7 +123,7 @@ func resourceSysdigMonitorNotificationChannelGoogleChatUpdate(ctx context.Contex return resourceSysdigMonitorNotificationChannelGoogleChatRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelGoogleChatDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelGoogleChatDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,8 +148,8 @@ func monitorNotificationChannelGoogleChatFromResourceData(d *schema.ResourceData return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_GCHAT - nc.Options.Url = d.Get("url").(string) + nc.Type = notificationChannelTypeGChat + nc.Options.URL = d.Get("url").(string) return } @@ -159,7 +159,7 @@ func monitorNotificationChannelGoogleChatToResourceData(nc *v2.NotificationChann return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_google_chat_test.go b/sysdig/resource_sysdig_monitor_notification_channel_google_chat_test.go index bca990cb2..ca23ff8a5 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_google_chat_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_google_chat_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go b/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go index f45e5821b..a3d2e3c69 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go @@ -39,7 +39,7 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotification() *schema.Reso } } -func resourceSysdigMonitorNotificationChannelIBMEventNotificationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelIBMEventNotificationCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -65,7 +65,7 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotificationCreate(ctx cont return resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -76,9 +76,9 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx contex return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -93,7 +93,7 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx contex return nil } -func resourceSysdigMonitorNotificationChannelIBMEventNotificationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelIBMEventNotificationUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -123,7 +123,7 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotificationUpdate(ctx cont return resourceSysdigMonitorNotificationChannelIBMEventNotificationRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelIBMEventNotificationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelIBMEventNotificationDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,8 +148,8 @@ func monitorNotificationChannelIBMEventNotificationFromResourceData(d *schema.Re return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_IBM_EVENT_NOTIFICATION - nc.Options.InstanceId = d.Get("instance_id").(string) + nc.Type = notificationChannelTypeIBMEventNotification + nc.Options.InstanceID = d.Get("instance_id").(string) return } @@ -159,7 +159,7 @@ func monitorNotificationChannelIBMEventNotificationToResourceData(nc *v2.Notific return } - _ = d.Set("instance_id", nc.Options.InstanceId) + _ = d.Set("instance_id", nc.Options.InstanceID) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification_test.go b/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification_test.go index 75faf0c79..8c7b4d49e 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_ibm_monitor || tf_acc_ibm_common - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_msteams.go b/sysdig/resource_sysdig_monitor_notification_channel_msteams.go index 1f69082eb..092f899a6 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_msteams.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_msteams.go @@ -39,7 +39,7 @@ func resourceSysdigMonitorNotificationChannelMSTeams() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelMSTeamsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelMSTeamsCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -65,7 +65,7 @@ func resourceSysdigMonitorNotificationChannelMSTeamsCreate(ctx context.Context, return resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -76,9 +76,9 @@ func resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -93,7 +93,7 @@ func resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx context.Context, d return nil } -func resourceSysdigMonitorNotificationChannelMSTeamsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelMSTeamsUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -123,7 +123,7 @@ func resourceSysdigMonitorNotificationChannelMSTeamsUpdate(ctx context.Context, return resourceSysdigMonitorNotificationChannelMSTeamsRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelMSTeamsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelMSTeamsDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,8 +148,8 @@ func monitorNotificationChannelMSTeamsFromResourceData(d *schema.ResourceData, t return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_MS_TEAMS - nc.Options.Url = d.Get("url").(string) + nc.Type = notificationChannelTypeMSTeams + nc.Options.URL = d.Get("url").(string) return } @@ -159,7 +159,7 @@ func monitorNotificationChannelMSTeamsToResourceData(nc *v2.NotificationChannel, return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_msteams_test.go b/sysdig/resource_sysdig_monitor_notification_channel_msteams_test.go index e1d478e2e..b1082f7b6 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_msteams_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_msteams_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go index 09dcc159c..4270ef96b 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go @@ -47,7 +47,7 @@ func resourceSysdigMonitorNotificationChannelOpsGenie() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelOpsGenieCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelOpsGenieCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -73,16 +73,16 @@ func resourceSysdigMonitorNotificationChannelOpsGenieCreate(ctx context.Context, return resourceSysdigMonitorNotificationChannelOpsGenieRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -97,7 +97,7 @@ func resourceSysdigMonitorNotificationChannelOpsGenieRead(ctx context.Context, d return nil } -func resourceSysdigMonitorNotificationChannelOpsGenieUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelOpsGenieUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -124,7 +124,7 @@ func resourceSysdigMonitorNotificationChannelOpsGenieUpdate(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelOpsGenieDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelOpsGenieDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -146,7 +146,7 @@ func monitorNotificationChannelOpsGenieFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_OPSGENIE + nc.Type = notificationChannelTypeOpsGenie apiKey := d.Get("api_key").(string) nc.Options.APIKey = apiKey nc.Options.Region = d.Get("region").(string) diff --git a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie_test.go b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie_test.go index 0c1444231..91ea98873 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go index 0ea3e61e0..cf1e5b8c5 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go @@ -48,7 +48,7 @@ func resourceSysdigMonitorNotificationChannelPagerduty() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelPagerdutyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPagerdutyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -74,16 +74,16 @@ func resourceSysdigMonitorNotificationChannelPagerdutyCreate(ctx context.Context return resourceSysdigMonitorNotificationChannelPagerdutyRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -98,7 +98,7 @@ func resourceSysdigMonitorNotificationChannelPagerdutyRead(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelPagerdutyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPagerdutyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -125,7 +125,7 @@ func resourceSysdigMonitorNotificationChannelPagerdutyUpdate(ctx context.Context return nil } -func resourceSysdigMonitorNotificationChannelPagerdutyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPagerdutyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -147,7 +147,7 @@ func monitorNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_PAGERDUTY + nc.Type = notificationChannelTypePagerduty nc.Options.Account = d.Get("account").(string) nc.Options.ServiceKey = d.Get("service_key").(string) nc.Options.ServiceName = d.Get("service_name").(string) diff --git a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty_test.go b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty_test.go index d8040bb63..f1d98fe20 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go b/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go index 16db59cd9..f8d9a3097 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go @@ -49,7 +49,7 @@ func resourceSysdigMonitorNotificationChannelPrometheusAlertManager() *schema.Re } } -func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -75,16 +75,16 @@ func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerCreate(ctx co return resourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -99,7 +99,7 @@ func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerRead(ctx cont return nil } -func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -126,7 +126,7 @@ func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerUpdate(ctx co return nil } -func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,9 +148,9 @@ func monitorNotificationChannelPrometheusAlertManagerFromResourceData(d *schema. return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_PROMETHEUS_ALERT_MANAGER - nc.Options.Url = d.Get("url").(string) - nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]interface{}) + nc.Type = notificationChannelTypePrometheusAlertManager + nc.Options.URL = d.Get("url").(string) + nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections return @@ -162,7 +162,7 @@ func monitorNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.Notif return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("additional_headers", nc.Options.AdditionalHeaders) if nc.Options.AllowInsecureConnections != nil { diff --git a/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go b/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go index bcb732267..29950e450 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_slack.go b/sysdig/resource_sysdig_monitor_notification_channel_slack.go index 0b2fbb9c3..f1b9b3409 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_slack.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_slack.go @@ -90,7 +90,7 @@ func resourceSysdigMonitorNotificationChannelSlack() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelSlackCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSlackCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -116,7 +116,7 @@ func resourceSysdigMonitorNotificationChannelSlackCreate(ctx context.Context, d return resourceSysdigMonitorNotificationChannelSlackRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -127,9 +127,9 @@ func resourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *s return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -144,7 +144,7 @@ func resourceSysdigMonitorNotificationChannelSlackRead(ctx context.Context, d *s return nil } -func resourceSysdigMonitorNotificationChannelSlackUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSlackUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -176,7 +176,7 @@ func resourceSysdigMonitorNotificationChannelSlackUpdate(ctx context.Context, d return nil } -func resourceSysdigMonitorNotificationChannelSlackDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSlackDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -201,11 +201,11 @@ func monitorNotificationChannelSlackFromResourceData(d *schema.ResourceData, tea return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_SLACK - nc.Options.Url = d.Get("url").(string) + nc.Type = notificationChannelTypeSlack + nc.Options.URL = d.Get("url").(string) nc.Options.Channel = d.Get("channel").(string) nc.Options.PrivateChannel = d.Get("is_private_channel").(bool) - nc.Options.PrivateChannelUrl = d.Get("private_channel_url").(string) + nc.Options.PrivateChannelURL = d.Get("private_channel_url").(string) nc.Options.TemplateConfiguration = []v2.NotificationChannelTemplateConfiguration{ { TemplateKey: "SLACK_MONITOR_ALERT_NOTIFICATION_TEMPLATE_METADATA_v1", @@ -255,10 +255,10 @@ func monitorNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("channel", nc.Options.Channel) _ = d.Set("is_private_channel", nc.Options.PrivateChannel) - _ = d.Set("private_channel_url", nc.Options.PrivateChannelUrl) + _ = d.Set("private_channel_url", nc.Options.PrivateChannelURL) runbookLinks := true eventDetails := true diff --git a/sysdig/resource_sysdig_monitor_notification_channel_slack_test.go b/sysdig/resource_sysdig_monitor_notification_channel_slack_test.go index 75b1b0148..f1edd28b2 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_slack_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_slack_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_sns.go b/sysdig/resource_sysdig_monitor_notification_channel_sns.go index 0adf8a81e..d31b7a1a4 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_sns.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_sns.go @@ -41,7 +41,7 @@ func resourceSysdigMonitorNotificationChannelSNS() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelSNSCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSNSCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -67,16 +67,16 @@ func resourceSysdigMonitorNotificationChannelSNSCreate(ctx context.Context, d *s return resourceSysdigMonitorNotificationChannelSNSRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -91,7 +91,7 @@ func resourceSysdigMonitorNotificationChannelSNSRead(ctx context.Context, d *sch return nil } -func resourceSysdigMonitorNotificationChannelSNSUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSNSUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -118,7 +118,7 @@ func resourceSysdigMonitorNotificationChannelSNSUpdate(ctx context.Context, d *s return nil } -func resourceSysdigMonitorNotificationChannelSNSDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelSNSDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -140,7 +140,7 @@ func monitorNotificationChannelSNSFromResourceData(d *schema.ResourceData, teamI return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_AMAZON_SNS + nc.Type = notificationChannelTypeAmazonSNS nc.Options.SnsTopicARNs = cast.ToStringSlice(d.Get("topics").(*schema.Set).List()) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_sns_test.go b/sysdig/resource_sysdig_monitor_notification_channel_sns_test.go index bcee11352..7fcb75775 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_sns_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_sns_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_team_email.go b/sysdig/resource_sysdig_monitor_notification_channel_team_email.go index 5ca11564f..eca0277a7 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_team_email.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_team_email.go @@ -40,7 +40,7 @@ func resourceSysdigMonitorNotificationChannelTeamEmail() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelTeamEmailCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelTeamEmailCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -66,16 +66,16 @@ func resourceSysdigMonitorNotificationChannelTeamEmailCreate(ctx context.Context return resourceSysdigMonitorNotificationChannelTeamEmailRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -90,7 +90,7 @@ func resourceSysdigMonitorNotificationChannelTeamEmailRead(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelTeamEmailUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelTeamEmailUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -117,7 +117,7 @@ func resourceSysdigMonitorNotificationChannelTeamEmailUpdate(ctx context.Context return nil } -func resourceSysdigMonitorNotificationChannelTeamEmailDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelTeamEmailDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -139,8 +139,8 @@ func monitorNotificationChannelTeamEmailFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_TEAM_EMAIL - nc.Options.TeamId = d.Get("team_id").(int) + nc.Type = notificationChannelTypeTeamEmail + nc.Options.TeamID = d.Get("team_id").(int) return } @@ -150,7 +150,7 @@ func monitorNotificationChannelTeamEmailToResourceData(nc *v2.NotificationChanne return } - _ = d.Set("team_id", nc.Options.TeamId) + _ = d.Set("team_id", nc.Options.TeamID) return } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_team_email_test.go b/sysdig/resource_sysdig_monitor_notification_channel_team_email_test.go index b866b140b..2e25708ab 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_team_email_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_team_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_victorops.go b/sysdig/resource_sysdig_monitor_notification_channel_victorops.go index f32dfec1a..5ff6a92f1 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_victorops.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_victorops.go @@ -43,7 +43,7 @@ func resourceSysdigMonitorNotificationChannelVictorOps() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelVictorOpsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelVictorOpsCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -69,16 +69,16 @@ func resourceSysdigMonitorNotificationChannelVictorOpsCreate(ctx context.Context return resourceSysdigMonitorNotificationChannelVictorOpsRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -93,7 +93,7 @@ func resourceSysdigMonitorNotificationChannelVictorOpsRead(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelVictorOpsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelVictorOpsUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -120,7 +120,7 @@ func resourceSysdigMonitorNotificationChannelVictorOpsUpdate(ctx context.Context return nil } -func resourceSysdigMonitorNotificationChannelVictorOpsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelVictorOpsDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -141,7 +141,7 @@ func monitorNotificationChannelVictorOpsFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_VICTOROPS + nc.Type = notificationChannelTypeVictorOps nc.Options.APIKey = d.Get("api_key").(string) nc.Options.RoutingKey = d.Get("routing_key").(string) return diff --git a/sysdig/resource_sysdig_monitor_notification_channel_victorops_test.go b/sysdig/resource_sysdig_monitor_notification_channel_victorops_test.go index 197d7811f..4fab0db6f 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_victorops_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_victorops_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_notification_channel_webhook.go b/sysdig/resource_sysdig_monitor_notification_channel_webhook.go index c8b221b6f..ab15044cf 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_webhook.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_webhook.go @@ -53,7 +53,7 @@ func resourceSysdigMonitorNotificationChannelWebhook() *schema.Resource { } } -func resourceSysdigMonitorNotificationChannelWebhookCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelWebhookCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorNotificationChannelClient(clients) if err != nil { @@ -80,16 +80,16 @@ func resourceSysdigMonitorNotificationChannelWebhookCreate(ctx context.Context, return resourceSysdigMonitorNotificationChannelWebhookRead(ctx, d, meta) } -func resourceSysdigMonitorNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -104,7 +104,7 @@ func resourceSysdigMonitorNotificationChannelWebhookRead(ctx context.Context, d return nil } -func resourceSysdigMonitorNotificationChannelWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -131,7 +131,7 @@ func resourceSysdigMonitorNotificationChannelWebhookUpdate(ctx context.Context, return nil } -func resourceSysdigMonitorNotificationChannelWebhookDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorNotificationChannelWebhookDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -153,10 +153,10 @@ func monitorNotificationChannelWebhookFromResourceData(d *schema.ResourceData, t return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_WEBHOOK - nc.Options.Url = d.Get("url").(string) - nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]interface{}) - nc.Options.CustomData = d.Get("custom_data").(map[string]interface{}) + nc.Type = notificationChannelTypeWebhook + nc.Options.URL = d.Get("url").(string) + nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) + nc.Options.CustomData = d.Get("custom_data").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections return @@ -168,7 +168,7 @@ func monitorNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("additional_headers", nc.Options.AdditionalHeaders) _ = d.Set("custom_data", nc.Options.CustomData) if nc.Options.AllowInsecureConnections != nil { diff --git a/sysdig/resource_sysdig_monitor_notification_channel_webhook_test.go b/sysdig/resource_sysdig_monitor_notification_channel_webhook_test.go index cd3f36f08..3426a6bb0 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_webhook_test.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_ibm_monitor || tf_acc_ibm_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_silence_rule.go b/sysdig/resource_sysdig_monitor_silence_rule.go index 0e7be7285..93a11cc28 100644 --- a/sysdig/resource_sysdig_monitor_silence_rule.go +++ b/sysdig/resource_sysdig_monitor_silence_rule.go @@ -94,7 +94,7 @@ func getMonitorSilenceRuleClient(c SysdigClients) (v2.SilenceRuleInterface, erro return client, nil } -func resourceSysdigMonitorSilenceRuleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorSilenceRuleCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorSilenceRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -115,7 +115,7 @@ func resourceSysdigMonitorSilenceRuleCreate(ctx context.Context, d *schema.Resou return resourceSysdigMonitorSilenceRuleRead(ctx, d, meta) } -func resourceSysdigMonitorSilenceRuleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorSilenceRuleRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorSilenceRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -128,7 +128,7 @@ func resourceSysdigMonitorSilenceRuleRead(ctx context.Context, d *schema.Resourc silenceRule, err := client.GetSilenceRule(ctx, id) if err != nil { - if err == v2.SilenceRuleNotFound { + if err == v2.ErrSilenceRuleNotFound { d.SetId("") return nil } @@ -137,7 +137,7 @@ func resourceSysdigMonitorSilenceRuleRead(ctx context.Context, d *schema.Resourc // suppress diff of "enabled" field if the silence interval is over: it will always be false from the api // any update of an ended silence rule results in a 422 Unprocessable Entity error from the api - silenceRuleEnd := time.Unix(silenceRule.StartTs/1000+int64(silenceRule.DurationInSec), 0) + silenceRuleEnd := time.Unix(silenceRule.StartTS/1000+int64(silenceRule.DurationInSec), 0) if time.Now().After(silenceRuleEnd) { silenceRule.Enabled = d.Get("enabled").(bool) } @@ -150,7 +150,7 @@ func resourceSysdigMonitorSilenceRuleRead(ctx context.Context, d *schema.Resourc return nil } -func resourceSysdigMonitorSilenceRuleUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorSilenceRuleUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorSilenceRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -175,7 +175,7 @@ func resourceSysdigMonitorSilenceRuleUpdate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigMonitorSilenceRuleDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorSilenceRuleDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorSilenceRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -199,23 +199,23 @@ func monitorSilenceRuleFromResourceData(d *schema.ResourceData) (v2.SilenceRule, silenceRule.Name = d.Get("name").(string) silenceRule.Enabled = d.Get("enabled").(bool) - startTs, err := strconv.ParseInt(d.Get("start_ts").(string), 10, 64) + startTS, err := strconv.ParseInt(d.Get("start_ts").(string), 10, 64) if err != nil { return silenceRule, err } - silenceRule.StartTs = startTs + silenceRule.StartTS = startTS silenceRule.DurationInSec = d.Get("duration_seconds").(int) silenceRule.Scope = d.Get("scope").(string) alertIds := d.Get("alert_ids").(*schema.Set) - for _, rawAlertId := range alertIds.List() { - if alertId, ok := rawAlertId.(int); ok { - silenceRule.AlertIds = append(silenceRule.AlertIds, alertId) + for _, rawAlertID := range alertIds.List() { + if alertID, ok := rawAlertID.(int); ok { + silenceRule.AlertIds = append(silenceRule.AlertIds, alertID) } } notificationChannelIds := d.Get("notification_channel_ids").(*schema.Set) - for _, rawNotificationChannelId := range notificationChannelIds.List() { - if notificationChannelId, ok := rawNotificationChannelId.(int); ok { - silenceRule.NotificationChannelIds = append(silenceRule.NotificationChannelIds, notificationChannelId) + for _, rawNotificationChannelID := range notificationChannelIds.List() { + if notificationChannelID, ok := rawNotificationChannelID.(int); ok { + silenceRule.NotificationChannelIds = append(silenceRule.NotificationChannelIds, notificationChannelID) } } return silenceRule, nil @@ -224,7 +224,7 @@ func monitorSilenceRuleFromResourceData(d *schema.ResourceData) (v2.SilenceRule, func monitorSilenceRuleToResourceData(silenceRule v2.SilenceRule, d *schema.ResourceData) (err error) { _ = d.Set("name", silenceRule.Name) _ = d.Set("enabled", silenceRule.Enabled) - _ = d.Set("start_ts", strconv.FormatInt(silenceRule.StartTs, 10)) + _ = d.Set("start_ts", strconv.FormatInt(silenceRule.StartTS, 10)) _ = d.Set("duration_seconds", silenceRule.DurationInSec) _ = d.Set("alert_ids", silenceRule.AlertIds) _ = d.Set("scope", silenceRule.Scope) diff --git a/sysdig/resource_sysdig_monitor_silence_rule_test.go b/sysdig/resource_sysdig_monitor_silence_rule_test.go index c8ef0b382..bf725a70f 100644 --- a/sysdig/resource_sysdig_monitor_silence_rule_test.go +++ b/sysdig/resource_sysdig_monitor_silence_rule_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_team.go b/sysdig/resource_sysdig_monitor_team.go index d059066aa..a52044ba0 100644 --- a/sysdig/resource_sysdig_monitor_team.go +++ b/sysdig/resource_sysdig_monitor_team.go @@ -153,14 +153,14 @@ func getMonitorTeamClient(c SysdigClients) (v2.TeamInterface, error) { return client, nil } -func resourceSysdigMonitorTeamCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorTeamCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorTeamClient(clients) if err != nil { return diag.FromErr(err) } - team := teamFromResourceData(d, clients.GetClientType()) + team := teamFromResourceData(d) team.Products = []string{"SDC"} team, err = client.CreateTeam(ctx, team) @@ -175,7 +175,7 @@ func resourceSysdigMonitorTeamCreate(ctx context.Context, d *schema.ResourceData } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorTeamClient(clients) if err != nil { @@ -183,7 +183,7 @@ func resourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, } id, _ := strconv.Atoi(d.Id()) - t, err := client.GetTeamById(ctx, id) + t, err := client.GetTeamByID(ctx, id) if err != nil { d.SetId("") return diag.FromErr(err) @@ -216,13 +216,13 @@ func resourceSysdigMonitorTeamRead(ctx context.Context, d *schema.ResourceData, return nil } -func userMonitorRolesToSet(userRoles []v2.UserRoles) (res []map[string]interface{}) { +func userMonitorRolesToSet(userRoles []v2.UserRoles) (res []map[string]any) { for _, role := range userRoles { if role.Admin { // Admins are added by default, so skip them continue } - roleMap := map[string]interface{}{ + roleMap := map[string]any{ "email": role.Email, "role": role.Role, } @@ -231,7 +231,7 @@ func userMonitorRolesToSet(userRoles []v2.UserRoles) (res []map[string]interface return } -func entrypointToSet(entrypoint *v2.EntryPoint) (res []map[string]interface{}) { +func entrypointToSet(entrypoint *v2.EntryPoint) (res []map[string]any) { if entrypoint == nil { return } @@ -240,21 +240,21 @@ func entrypointToSet(entrypoint *v2.EntryPoint) (res []map[string]interface{}) { if module == "Overview" { module = "Advisor" } - entrypointMap := map[string]interface{}{ + entrypointMap := map[string]any{ "type": module, "selection": entrypoint.Selection, } return append(res, entrypointMap) } -func resourceSysdigMonitorTeamUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorTeamUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getMonitorTeamClient(clients) if err != nil { return diag.FromErr(err) } - t := teamFromResourceData(d, clients.GetClientType()) + t := teamFromResourceData(d) t.Products = []string{"SDC"} t.Version = d.Get("version").(int) @@ -269,7 +269,7 @@ func resourceSysdigMonitorTeamUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigMonitorTeamDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMonitorTeamDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getMonitorTeamClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -284,7 +284,7 @@ func resourceSysdigMonitorTeamDelete(ctx context.Context, d *schema.ResourceData return nil } -func teamFromResourceData(d *schema.ResourceData, clientType ClientType) v2.Team { +func teamFromResourceData(d *schema.ResourceData) v2.Team { canUseSysdigCapture := d.Get("can_use_sysdig_capture").(bool) canUseCustomEvents := d.Get("can_see_infrastructure_events").(bool) canUseAgentCli := d.Get("can_use_agent_cli").(bool) @@ -304,7 +304,7 @@ func teamFromResourceData(d *schema.ResourceData, clientType ClientType) v2.Team userRoles := make([]v2.UserRoles, 0) for _, userRole := range d.Get("user_roles").(*schema.Set).List() { - ur := userRole.(map[string]interface{}) + ur := userRole.(map[string]any) userRoles = append(userRoles, v2.UserRoles{ Email: ur["email"].(string), Role: ur["role"].(string), diff --git a/sysdig/resource_sysdig_monitor_team_ibm_test.go b/sysdig/resource_sysdig_monitor_team_ibm_test.go index 5fc07f176..49eb9c7e9 100644 --- a/sysdig/resource_sysdig_monitor_team_ibm_test.go +++ b/sysdig/resource_sysdig_monitor_team_ibm_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_ibm_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_monitor_team_test.go b/sysdig/resource_sysdig_monitor_team_test.go index bc32edf6f..94798cde4 100644 --- a/sysdig/resource_sysdig_monitor_team_test.go +++ b/sysdig/resource_sysdig_monitor_team_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_common || tf_acc_onprem_monitor - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_accept_posture_risk.go b/sysdig/resource_sysdig_secure_accept_posture_risk.go index bd255c49a..7d663fb4e 100644 --- a/sysdig/resource_sysdig_secure_accept_posture_risk.go +++ b/sysdig/resource_sysdig_secure_accept_posture_risk.go @@ -96,7 +96,7 @@ func resourceSysdigSecureAcceptPostureRisk() *schema.Resource { } } -func resourceSysdigSecureAcceptPostureControlCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureAcceptPostureControlCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Extract 'group' field from Terraform configuration client, err := getPostureAcceptRiskClient(meta.(SysdigClients)) if err != nil { @@ -113,17 +113,18 @@ func resourceSysdigSecureAcceptPostureControlCreate(ctx context.Context, d *sche } var endTime int64 expiresIn := d.Get(SchemaExpiresInKey).(string) - if expiresIn == "7 Days" { + switch expiresIn { + case "7 Days": endTime = time.Now().AddDate(0, 0, 7).UTC().UnixMilli() - } else if expiresIn == "30 Days" { + case "30 Days": endTime = time.Now().AddDate(0, 0, 30).UTC().UnixMilli() - } else if expiresIn == "60 Days" { + case "60 Days": endTime = time.Now().AddDate(0, 0, 60).UTC().UnixMilli() - } else if expiresIn == "90 Days" { + case "90 Days": endTime = time.Now().AddDate(0, 0, 90).UTC().UnixMilli() - } else if expiresIn == "Never" { + case "Never": endTime = 0 - } else { + default: t := d.Get(SchemaEndTimeKey).(string) endTime, _ = strconv.ParseInt(t, 10, 64) } @@ -140,7 +141,7 @@ func resourceSysdigSecureAcceptPostureControlCreate(ctx context.Context, d *sche return nil } -func resourceSysdigSecureAcceptPostureControlUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureAcceptPostureControlUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Extract 'group' field from Terraform configuration client, err := getPostureAcceptRiskClient(meta.(SysdigClients)) if err != nil { @@ -153,22 +154,23 @@ func resourceSysdigSecureAcceptPostureControlUpdate(ctx context.Context, d *sche } expiresIn := d.Get(SchemaExpiresInKey).(string) var millis int64 - if expiresIn == "7 Days" { + switch expiresIn { + case "7 Days": req.Acceptance.AcceptPeriod = "7" millis = time.Now().AddDate(0, 0, 7).UTC().UnixMilli() - } else if expiresIn == "30 Days" { + case "30 Days": req.Acceptance.AcceptPeriod = "30" millis = time.Now().AddDate(0, 0, 30).UTC().UnixMilli() - } else if expiresIn == "60 Days" { + case "60 Days": req.Acceptance.AcceptPeriod = "60" millis = time.Now().AddDate(0, 0, 60).UTC().UnixMilli() - } else if expiresIn == "90 Days" { + case "90 Days": req.Acceptance.AcceptPeriod = "90" millis = time.Now().AddDate(0, 0, 90).UTC().UnixMilli() - } else if expiresIn == "Never" { + case "Never": req.Acceptance.AcceptPeriod = "Never" millis = 0 - } else { + default: req.Acceptance.AcceptPeriod = "Custom" t := d.Get(SchemaEndTimeKey).(string) millis, err = strconv.ParseInt(t, 10, 64) @@ -192,7 +194,7 @@ func resourceSysdigSecureAcceptPostureControlUpdate(ctx context.Context, d *sche return nil } -func resourceSysdigSecureAcceptPostureControlRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureAcceptPostureControlRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -273,7 +275,7 @@ func resourceSysdigSecureAcceptPostureControlRead(ctx context.Context, d *schema return nil } -func resourceSysdigSecureAcceptPostureControlDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureAcceptPostureControlDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_secure_accept_posture_risk_test.go b/sysdig/resource_sysdig_secure_accept_posture_risk_test.go index 826750a05..4daf84182 100644 --- a/sysdig/resource_sysdig_secure_accept_posture_risk_test.go +++ b/sysdig/resource_sysdig_secure_accept_posture_risk_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_accept_vulnerability_risk.go b/sysdig/resource_sysdig_secure_accept_vulnerability_risk.go index 1e6a12bee..3ea85739f 100644 --- a/sysdig/resource_sysdig_secure_accept_vulnerability_risk.go +++ b/sysdig/resource_sysdig_secure_accept_vulnerability_risk.go @@ -80,7 +80,7 @@ func resourceSysdigSecureVulnerabilityAcceptRisk() *schema.Resource { } } -func resourceSysdigSecureVulnerabilityAcceptRiskCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureVulnerabilityAcceptRiskCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getVulnerabilityAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -128,7 +128,7 @@ func resourceSysdigSecureVulnerabilityAcceptRiskCreate(ctx context.Context, d *s } if stages, ok := d.GetOk("stages"); ok { - for _, stage := range stages.([]interface{}) { + for _, stage := range stages.([]any) { req.Stages = append(req.Stages, v2.StageType(stage.(string))) } } @@ -245,14 +245,14 @@ func setContextFromFields(d *schema.ResourceData, req *v2.AcceptVulnerabilityRis } } -func resourceSysdigSecureVulnerabilityAcceptRiskRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureVulnerabilityAcceptRiskRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getVulnerabilityAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id := d.Id() - result, statusCode, err := client.GetAcceptanceVulnerabilityRisk(ctx, id) + result, statusCode, err := client.GetAcceptanceVulnerabilityRiskByID(ctx, id) if err != nil { if statusCode == http.StatusNotFound { d.SetId("") @@ -321,7 +321,7 @@ func fillResourceDataFromContext(d *schema.ResourceData, context v2.AcceptVulner } } -func resourceSysdigSecureVulnerabilityAcceptRiskUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureVulnerabilityAcceptRiskUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getVulnerabilityAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -351,7 +351,7 @@ func resourceSysdigSecureVulnerabilityAcceptRiskUpdate(ctx context.Context, d *s return resourceSysdigSecureVulnerabilityAcceptRiskRead(ctx, d, meta) } -func resourceSysdigSecureVulnerabilityAcceptRiskDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureVulnerabilityAcceptRiskDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getVulnerabilityAcceptRiskClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_secure_accept_vulnerability_risk_test.go b/sysdig/resource_sysdig_secure_accept_vulnerability_risk_test.go index 9cbb94127..bf0fa9907 100644 --- a/sysdig/resource_sysdig_secure_accept_vulnerability_risk_test.go +++ b/sysdig/resource_sysdig_secure_accept_vulnerability_risk_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_aws_ml_policy.go b/sysdig/resource_sysdig_secure_aws_ml_policy.go index 00c581522..f7fe4bd73 100644 --- a/sysdig/resource_sysdig_secure_aws_ml_policy.go +++ b/sysdig/resource_sysdig_secure_aws_ml_policy.go @@ -88,7 +88,7 @@ func awsMLPolicyToResourceData(policy *v2.PolicyRulesComposite, d *schema.Resour return awsMLTFResourceReducer(d, *policy) } -func resourceSysdigAWSMLPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAWSMLPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -115,7 +115,7 @@ func resourceSysdigAWSMLPolicyCreate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigAWSMLPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAWSMLPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -136,7 +136,7 @@ func resourceSysdigAWSMLPolicyUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigAWSMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAWSMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -160,7 +160,7 @@ func resourceSysdigAWSMLPolicyRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigAWSMLPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigAWSMLPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -173,7 +173,7 @@ func resourceSysdigAWSMLPolicyDelete(ctx context.Context, d *schema.ResourceData } if policy.Policy.ID == 0 { - return diag.FromErr(errors.New("Policy ID is missing")) + return diag.FromErr(errors.New("policy ID is missing")) } err = client.DeleteCompositePolicy(ctx, policy.Policy.ID) @@ -185,7 +185,7 @@ func resourceSysdigAWSMLPolicyDelete(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigSecureAWSMLPolicyImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureAWSMLPolicyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -197,7 +197,7 @@ func resourceSysdigSecureAWSMLPolicyImportState(ctx context.Context, d *schema.R } if policy.Policy.ID == 0 { - return nil, errors.New("Policy ID is missing") + return nil, errors.New("policy ID is missing") } policy, _, err = client.GetCompositePolicyByID(ctx, policy.Policy.ID) @@ -205,7 +205,7 @@ func resourceSysdigSecureAWSMLPolicyImportState(ctx context.Context, d *schema.R return nil, err } - if policy.Policy.IsDefault || policy.Policy.TemplateId != 0 { + if policy.Policy.IsDefault || policy.Policy.TemplateID != 0 { return nil, errors.New("unable to import policy that is not a custom policy") } diff --git a/sysdig/resource_sysdig_secure_aws_ml_policy_test.go b/sysdig/resource_sysdig_secure_aws_ml_policy_test.go index 017cc6950..158903637 100644 --- a/sysdig/resource_sysdig_secure_aws_ml_policy_test.go +++ b/sysdig/resource_sysdig_secure_aws_ml_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_cloud_account.go b/sysdig/resource_sysdig_secure_cloud_account.go index aebd2b5f6..8c9fffac9 100644 --- a/sysdig/resource_sysdig_secure_cloud_account.go +++ b/sysdig/resource_sysdig_secure_cloud_account.go @@ -74,7 +74,7 @@ func getSecureCloudAccountClient(c SysdigClients) (v2.CloudAccountSecureInterfac return c.sysdigSecureClientV2() } -func resourceSysdigSecureCloudAccountCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudAccountCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -98,14 +98,14 @@ func resourceSysdigSecureCloudAccountCreate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigSecureCloudAccountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudAccountRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudAccountClient(meta.(SysdigClients)) if err != nil { d.SetId("") return diag.FromErr(err) } - cloudAccount, err := client.GetCloudAccountSecure(ctx, d.Id()) + cloudAccount, err := client.GetCloudAccountSecureByID(ctx, d.Id()) if err != nil { d.SetId("") if strings.Contains(err.Error(), "404") { @@ -126,7 +126,7 @@ func resourceSysdigSecureCloudAccountRead(ctx context.Context, d *schema.Resourc return nil } -func resourceSysdigSecureCloudAccountUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudAccountUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -143,7 +143,7 @@ func resourceSysdigSecureCloudAccountUpdate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigSecureCloudAccountDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudAccountDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_secure_cloud_account_test.go b/sysdig/resource_sysdig_secure_cloud_account_test.go index cd29230a8..1c87c845a 100644 --- a/sysdig/resource_sysdig_secure_cloud_account_test.go +++ b/sysdig/resource_sysdig_secure_cloud_account_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account.go b/sysdig/resource_sysdig_secure_cloud_auth_account.go index 56b9f95f3..ac67c4fcf 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "reflect" "strings" "time" @@ -149,7 +150,7 @@ func resourceSysdigSecureCloudauthAccount() *schema.Resource { Optional: true, Computed: true, }, - SchemaCloudProviderId: { + SchemaCloudProviderID: { Type: schema.TypeString, Required: true, }, @@ -176,7 +177,7 @@ func resourceSysdigSecureCloudauthAccount() *schema.Resource { Type: schema.TypeString, Computed: true, }, - SchemaCloudProviderTenantId: { + SchemaCloudProviderTenantID: { Type: schema.TypeString, Optional: true, }, @@ -196,7 +197,7 @@ func getSecureCloudauthAccountClient(client SysdigClients) (v2.CloudauthAccountS return client.sysdigSecureClientV2() } -func resourceSysdigSecureCloudauthAccountCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountCreate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountClient((meta.(SysdigClients))) if err != nil { return diag.FromErr(err) @@ -216,13 +217,13 @@ func resourceSysdigSecureCloudauthAccountCreate(ctx context.Context, data *schem return nil } -func resourceSysdigSecureCloudauthAccountRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountRead(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } - cloudauthAccount, errStatus, err := client.GetCloudauthAccountSecure(ctx, data.Id()) + cloudauthAccount, errStatus, err := client.GetCloudauthAccountSecureByID(ctx, data.Id()) if err != nil { return diag.Errorf("Error reading resource: %s %s", errStatus, err) } @@ -235,13 +236,13 @@ func resourceSysdigSecureCloudauthAccountRead(ctx context.Context, data *schema. return nil } -func resourceSysdigSecureCloudauthAccountUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountUpdate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } - existingCloudAccount, errStatus, err := client.GetCloudauthAccountSecure(ctx, data.Id()) + existingCloudAccount, errStatus, err := client.GetCloudauthAccountSecureByID(ctx, data.Id()) if err != nil { return diag.Errorf("Error reading resource: %s %s", errStatus, err) } @@ -262,7 +263,7 @@ func resourceSysdigSecureCloudauthAccountUpdate(ctx context.Context, data *schem return nil } -func resourceSysdigSecureCloudauthAccountDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountDelete(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -295,14 +296,12 @@ func validateCloudauthAccountUpdate(existingCloudAccount *v2.CloudauthAccountSec /* This function converts a schema set to map for iteration. */ -func convertSchemaSetToMap(set *schema.Set) map[string]interface{} { - result := make(map[string]interface{}) +func convertSchemaSetToMap(set *schema.Set) map[string]any { + result := make(map[string]any) for _, element := range set.List() { - if entry, ok := element.(map[string]interface{}); ok { - for key, value := range entry { - result[key] = value - } + if entry, ok := element.(map[string]any); ok { + maps.Copy(result, entry) } } @@ -312,7 +311,7 @@ func convertSchemaSetToMap(set *schema.Set) map[string]interface{} { /* This helper function dynamically populates the account features object for account creation */ -func setAccountFeature(accountFeatures *cloudauth.AccountFeatures, fieldName string, featureType cloudauth.Feature, valueMap map[string]interface{}) { +func setAccountFeature(accountFeatures *cloudauth.AccountFeatures, fieldName string, featureType cloudauth.Feature, valueMap map[string]any) { target := reflect.ValueOf(accountFeatures).Elem().FieldByName(fieldName) target.Elem().FieldByName("Type").Set(reflect.ValueOf(cloudauth.Feature(featureType))) @@ -321,7 +320,7 @@ func setAccountFeature(accountFeatures *cloudauth.AccountFeatures, fieldName str case SchemaEnabled: target.Elem().FieldByName("Enabled").SetBool(value.(bool)) case SchemaComponents: - for _, componentID := range value.([]interface{}) { + for _, componentID := range value.([]any) { target.Elem().FieldByName("Components").Set(reflect.Append(target.Elem().FieldByName("Components"), reflect.ValueOf(componentID.(string)))) } } @@ -370,7 +369,7 @@ func constructAccountComponents(data *schema.ResourceData) []*cloudauth.AccountC accountComponents := []*cloudauth.AccountComponent{} for _, rc := range data.Get(SchemaComponent).(*schema.Set).List() { - resourceComponent := rc.(map[string]interface{}) + resourceComponent := rc.(map[string]any) component := &cloudauth.AccountComponent{} var err error @@ -425,11 +424,11 @@ func cloudauthAccountFromResourceData(data *schema.ResourceData) *v2.CloudauthAc CloudAccount: cloudauth.CloudAccount{ Enabled: data.Get(SchemaEnabled).(bool), OrganizationId: data.Get(SchemaOrganizationIDKey).(string), - ProviderId: data.Get(SchemaCloudProviderId).(string), + ProviderId: data.Get(SchemaCloudProviderID).(string), Provider: cloudauth.Provider(cloudauth.Provider_value[data.Get(SchemaCloudProviderType).(string)]), Components: constructAccountComponents(data), Feature: constructAccountFeatures(data), - ProviderTenantId: data.Get(SchemaCloudProviderTenantId).(string), + ProviderTenantId: data.Get(SchemaCloudProviderTenantID).(string), ProviderAlias: data.Get(SchemaCloudProviderAlias).(string), ProviderPartition: cloudauth.ProviderPartition(cloudauth.ProviderPartition_value[data.Get(SchemaProviderPartition).(string)]), }, @@ -439,8 +438,8 @@ func cloudauthAccountFromResourceData(data *schema.ResourceData) *v2.CloudauthAc /* This helper function converts feature values from *cloudauth.AccountFeature to resource data schema. */ -func featureValuesToResourceData(feature *cloudauth.AccountFeature) map[string]interface{} { - valuesMap := make(map[string]interface{}) +func featureValuesToResourceData(feature *cloudauth.AccountFeature) map[string]any { + valuesMap := make(map[string]any) valuesMap["type"] = feature.Type.String() valuesMap["enabled"] = feature.Enabled @@ -453,10 +452,10 @@ func featureValuesToResourceData(feature *cloudauth.AccountFeature) map[string]i This helper function converts the features data from *cloudauth.AccountFeatures to resource data schema. This is needed to set the value in cloudauthAccountToResourceData(). */ -func featureToResourceData(features *cloudauth.AccountFeatures) []interface{} { +func featureToResourceData(features *cloudauth.AccountFeatures) []any { // In the resource data, SchemaFeature field is a nested set[] of sets[] of individual features // Hence we need to return this uber level set[] to cloudauthAccountToResourceData - featureMap := []interface{}{} + featureMap := []any{} featureFields := map[string]*cloudauth.AccountFeature{ SchemaSecureThreatDetection: features.SecureThreatDetection, @@ -466,10 +465,10 @@ func featureToResourceData(features *cloudauth.AccountFeatures) []interface{} { SchemaSecureAgentlessScanning: features.SecureAgentlessScanning, } - allFeatures := make(map[string]interface{}) + allFeatures := make(map[string]any) for name, feature := range featureFields { if feature != nil { - featureBlock := make([]map[string]interface{}, 0) + featureBlock := make([]map[string]any, 0) value := featureValuesToResourceData(feature) featureBlock = append(featureBlock, value) @@ -489,10 +488,10 @@ func featureToResourceData(features *cloudauth.AccountFeatures) []interface{} { This helper function converts the components data from []*cloudauth.AccountComponent to resource data schema. This is needed to set the value in cloudauthAccountToResourceData(). */ -func componentsToResourceData(components []*cloudauth.AccountComponent) []map[string]interface{} { - resourceList := []map[string]interface{}{} +func componentsToResourceData(components []*cloudauth.AccountComponent) []map[string]any { + resourceList := []map[string]any{} for _, component := range components { - resourceData := map[string]interface{}{} + resourceData := map[string]any{} resourceData[SchemaType] = component.GetType().String() resourceData[SchemaInstance] = component.GetInstance() resourceData[SchemaVersion] = component.GetVersion() @@ -526,13 +525,13 @@ func componentsToResourceData(components []*cloudauth.AccountComponent) []map[st func getComponentMetadataString(message protoreflect.ProtoMessage) string { // marshal through protojson get correct snake case keys - protoJsonMessage, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(message) + protoJSONMessage, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(message) if err != nil { diag.FromErr(err) } // re-marshal through encoding/json to get consistent key ordering, avoiding diff errors with TF internals - metadataMap := make(map[string]interface{}) - err = json.Unmarshal(protoJsonMessage, &metadataMap) + metadataMap := make(map[string]any) + err = json.Unmarshal(protoJSONMessage, &metadataMap) if err != nil { diag.FromErr(err) } @@ -554,7 +553,7 @@ func cloudauthAccountToResourceData(data *schema.ResourceData, cloudAccount *v2. return err } - err = data.Set(SchemaCloudProviderId, cloudAccount.ProviderId) + err = data.Set(SchemaCloudProviderID, cloudAccount.ProviderId) if err != nil { return err } @@ -580,7 +579,7 @@ func cloudauthAccountToResourceData(data *schema.ResourceData, cloudAccount *v2. } if cloudAccount.Provider == cloudauth.Provider_PROVIDER_AZURE { - err = data.Set(SchemaCloudProviderTenantId, cloudAccount.ProviderTenantId) + err = data.Set(SchemaCloudProviderTenantID, cloudAccount.ProviderTenantId) if err != nil { return err } @@ -592,13 +591,13 @@ func cloudauthAccountToResourceData(data *schema.ResourceData, cloudAccount *v2. } if cloudAccount.Provider == cloudauth.Provider_PROVIDER_ORACLECLOUD { - err = data.Set(SchemaCloudProviderTenantId, cloudAccount.ProviderTenantId) + err = data.Set(SchemaCloudProviderTenantID, cloudAccount.ProviderTenantId) if err != nil { return err } } - if !(cloudAccount.ProviderPartition.String() == cloudauth.ProviderPartition_PROVIDER_PARTITION_UNSPECIFIED.String()) { + if cloudAccount.ProviderPartition.String() != cloudauth.ProviderPartition_PROVIDER_PARTITION_UNSPECIFIED.String() { err = data.Set(SchemaProviderPartition, cloudAccount.ProviderPartition.String()) if err != nil { return err diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account_component.go b/sysdig/resource_sysdig_secure_cloud_auth_account_component.go index fcd64e405..3c8797cda 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account_component.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account_component.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "strings" "time" @@ -42,15 +43,13 @@ func resourceSysdigSecureCloudauthAccountComponent() *schema.Resource { func getAccountComponentSchema() map[string]*schema.Schema { // for AccountComponent resource, account_id is needed additionally componentSchema := map[string]*schema.Schema{ - SchemaAccountId: { + SchemaAccountID: { Type: schema.TypeString, Required: true, }, } - for field, schema := range accountComponent.Schema { - componentSchema[field] = schema - } + maps.Copy(componentSchema, accountComponent.Schema) return componentSchema } @@ -58,21 +57,21 @@ func getSecureCloudauthAccountComponentClient(client SysdigClients) (v2.Cloudaut return client.sysdigSecureClientV2() } -func resourceSysdigSecureCloudauthAccountComponentCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountComponentCreate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountComponentClient((meta.(SysdigClients))) if err != nil { return diag.FromErr(err) } - accountId := data.Get(SchemaAccountId).(string) - cloudauthAccountComponent, errStatus, err := client.CreateCloudauthAccountComponentSecure(ctx, accountId, cloudauthAccountComponentFromResourceData(data)) + accountID := data.Get(SchemaAccountID).(string) + cloudauthAccountComponent, errStatus, err := client.CreateCloudauthAccountComponentSecure(ctx, accountID, cloudauthAccountComponentFromResourceData(data)) if err != nil { return diag.Errorf("Error creating resource: %s %s", errStatus, err) } // using tuple 'accountId/componentType/componentInstance' as TF resource identifier - data.SetId(accountId + "/" + cloudauthAccountComponent.GetType().String() + "/" + cloudauthAccountComponent.GetInstance()) - err = data.Set(SchemaAccountId, accountId) + data.SetId(accountID + "/" + cloudauthAccountComponent.GetType().String() + "/" + cloudauthAccountComponent.GetInstance()) + err = data.Set(SchemaAccountID, accountID) if err != nil { return diag.FromErr(err) } @@ -80,15 +79,14 @@ func resourceSysdigSecureCloudauthAccountComponentCreate(ctx context.Context, da return nil } -func resourceSysdigSecureCloudauthAccountComponentRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountComponentRead(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountComponentClient((meta.(SysdigClients))) if err != nil { return diag.FromErr(err) } cloudauthAccountComponent, errStatus, err := client.GetCloudauthAccountComponentSecure( - ctx, data.Get(SchemaAccountId).(string), data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) - + ctx, data.Get(SchemaAccountID).(string), data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -104,15 +102,15 @@ func resourceSysdigSecureCloudauthAccountComponentRead(ctx context.Context, data return nil } -func resourceSysdigSecureCloudauthAccountComponentUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountComponentUpdate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountComponentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } - accountId := data.Get(SchemaAccountId).(string) + accountID := data.Get(SchemaAccountID).(string) existingCloudAccountComponent, errStatus, err := client.GetCloudauthAccountComponentSecure( - ctx, accountId, data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) + ctx, accountID, data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -129,7 +127,7 @@ func resourceSysdigSecureCloudauthAccountComponentUpdate(ctx context.Context, da } _, errStatus, err = client.UpdateCloudauthAccountComponentSecure( - ctx, accountId, data.Get(SchemaType).(string), data.Get(SchemaInstance).(string), newCloudAccountComponent) + ctx, accountID, data.Get(SchemaType).(string), data.Get(SchemaInstance).(string), newCloudAccountComponent) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -140,14 +138,14 @@ func resourceSysdigSecureCloudauthAccountComponentUpdate(ctx context.Context, da return nil } -func resourceSysdigSecureCloudauthAccountComponentDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountComponentDelete(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountComponentClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } errStatus, err := client.DeleteCloudauthAccountComponentSecure( - ctx, data.Get(SchemaAccountId).(string), data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) + ctx, data.Get(SchemaAccountID).(string), data.Get(SchemaType).(string), data.Get(SchemaInstance).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -225,11 +223,10 @@ func cloudauthAccountComponentFromResourceData(data *schema.ResourceData) *v2.Cl } func cloudauthAccountComponentToResourceData(data *schema.ResourceData, cloudAccountComponent *v2.CloudauthAccountComponentSecure) error { + accountID := data.Get(SchemaAccountID).(string) + data.SetId(accountID + "/" + cloudAccountComponent.GetType().String() + "/" + cloudAccountComponent.GetInstance()) - accountId := data.Get(SchemaAccountId).(string) - data.SetId(accountId + "/" + cloudAccountComponent.GetType().String() + "/" + cloudAccountComponent.GetInstance()) - - err := data.Set(SchemaAccountId, accountId) + err := data.Set(SchemaAccountID, accountID) if err != nil { return err } @@ -284,13 +281,13 @@ func cloudauthAccountComponentToResourceData(data *schema.ResourceData, cloudAcc // This exists because in terraform, the key is originally provided in the form of a base64 encoded json string // note; caution with order of fields, they have to go in alphabetical ASC so that the json marshalled on the tf read phase produces no drift https://github.com/golang/go/issues/27179 -type internalServicePrincipalMetadata_GCP struct { +type internalServicePrincipalMetadataGCP struct { Email string `json:"email,omitempty"` Key string `json:"key,omitempty"` // base64 encoded WorkloadIdentityFederation *cloudauth.ServicePrincipalMetadata_GCP_WorkloadIdentityFederation `json:"workload_identity_federation,omitempty"` } type internalServicePrincipalMetadata struct { - Gcp *internalServicePrincipalMetadata_GCP `json:"gcp,omitempty"` + Gcp *internalServicePrincipalMetadataGCP `json:"gcp,omitempty"` } /* @@ -349,7 +346,7 @@ func getGcpServicePrincipalMetadata(metadata *cloudauth.ServicePrincipalMetadata gcpKeyBytes = append(gcpKeyBytesBuffer.Bytes(), '\n') } spGcpBytes, err := json.Marshal(&internalServicePrincipalMetadata{ - Gcp: &internalServicePrincipalMetadata_GCP{ + Gcp: &internalServicePrincipalMetadataGCP{ Key: base64.StdEncoding.EncodeToString(gcpKeyBytes), WorkloadIdentityFederation: metadata.GetGcp().GetWorkloadIdentityFederation(), Email: metadata.GetGcp().GetEmail(), diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account_component_test.go b/sysdig/resource_sysdig_secure_cloud_auth_account_component_test.go index a1f0a646e..173068358 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account_component_test.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account_component_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account_feature.go b/sysdig/resource_sysdig_secure_cloud_auth_account_feature.go index d6f2d8b7f..6aa033545 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account_feature.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account_feature.go @@ -38,7 +38,7 @@ func getAccountFeatureSchema() map[string]*schema.Schema { // though the schema fields are already defined in cloud_auth_account resource, for AccountFeature // calls they are required fields. Also, account_id & flags are needed additionally. featureSchema := map[string]*schema.Schema{ - SchemaAccountId: { + SchemaAccountID: { Type: schema.TypeString, Required: true, }, @@ -70,22 +70,22 @@ func getSecureCloudauthAccountFeatureClient(client SysdigClients) (v2.CloudauthA return client.sysdigSecureClientV2() } -func resourceSysdigSecureCloudauthAccountFeatureCreate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountFeatureCreate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountFeatureClient((meta.(SysdigClients))) if err != nil { return diag.FromErr(err) } - accountId := data.Get(SchemaAccountId).(string) + accountID := data.Get(SchemaAccountID).(string) cloudauthAccountFeature, errStatus, err := client.CreateOrUpdateCloudauthAccountFeatureSecure( - ctx, accountId, data.Get(SchemaType).(string), cloudauthAccountFeatureFromResourceData(data)) + ctx, accountID, data.Get(SchemaType).(string), cloudauthAccountFeatureFromResourceData(data)) if err != nil { return diag.Errorf("Error creating resource: %s %s", errStatus, err) } // using tuple 'accountId/featureType' as TF resource identifier - data.SetId(accountId + "/" + cloudauthAccountFeature.GetType().String()) - err = data.Set(SchemaAccountId, accountId) + data.SetId(accountID + "/" + cloudauthAccountFeature.GetType().String()) + err = data.Set(SchemaAccountID, accountID) if err != nil { return diag.FromErr(err) } @@ -93,15 +93,14 @@ func resourceSysdigSecureCloudauthAccountFeatureCreate(ctx context.Context, data return nil } -func resourceSysdigSecureCloudauthAccountFeatureRead(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountFeatureRead(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountFeatureClient((meta.(SysdigClients))) if err != nil { return diag.FromErr(err) } cloudauthAccountFeature, errStatus, err := client.GetCloudauthAccountFeatureSecure( - ctx, data.Get(SchemaAccountId).(string), data.Get(SchemaType).(string)) - + ctx, data.Get(SchemaAccountID).(string), data.Get(SchemaType).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -117,15 +116,15 @@ func resourceSysdigSecureCloudauthAccountFeatureRead(ctx context.Context, data * return nil } -func resourceSysdigSecureCloudauthAccountFeatureUpdate(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountFeatureUpdate(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountFeatureClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } - accountId := data.Get(SchemaAccountId).(string) + accountID := data.Get(SchemaAccountID).(string) existingCloudAccountFeature, errStatus, err := client.GetCloudauthAccountFeatureSecure( - ctx, accountId, data.Get(SchemaType).(string)) + ctx, accountID, data.Get(SchemaType).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -142,7 +141,7 @@ func resourceSysdigSecureCloudauthAccountFeatureUpdate(ctx context.Context, data } _, errStatus, err = client.CreateOrUpdateCloudauthAccountFeatureSecure( - ctx, accountId, data.Get(SchemaType).(string), newCloudAccountFeature) + ctx, accountID, data.Get(SchemaType).(string), newCloudAccountFeature) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -153,14 +152,14 @@ func resourceSysdigSecureCloudauthAccountFeatureUpdate(ctx context.Context, data return nil } -func resourceSysdigSecureCloudauthAccountFeatureDelete(ctx context.Context, data *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureCloudauthAccountFeatureDelete(ctx context.Context, data *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCloudauthAccountFeatureClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } errStatus, err := client.DeleteCloudauthAccountFeatureSecure( - ctx, data.Get(SchemaAccountId).(string), data.Get(SchemaType).(string)) + ctx, data.Get(SchemaAccountID).(string), data.Get(SchemaType).(string)) if err != nil { if strings.Contains(errStatus, "404") { return nil @@ -185,7 +184,7 @@ func validateCloudauthAccountFeatureUpdate(existingFeature *v2.CloudauthAccountF func getFeatureComponentsList(data *schema.ResourceData) []string { componentsList := []string{} - componentsResourceList := data.Get(SchemaComponents).([]interface{}) + componentsResourceList := data.Get(SchemaComponents).([]any) for _, componentID := range componentsResourceList { componentsList = append(componentsList, componentID.(string)) } @@ -194,7 +193,7 @@ func getFeatureComponentsList(data *schema.ResourceData) []string { func getFeatureFlags(data *schema.ResourceData) map[string]string { featureFlags := map[string]string{} - flagsResource := data.Get(SchemaFeatureFlags).(map[string]interface{}) + flagsResource := data.Get(SchemaFeatureFlags).(map[string]any) for name, value := range flagsResource { featureFlags[name] = value.(string) } @@ -215,11 +214,10 @@ func cloudauthAccountFeatureFromResourceData(data *schema.ResourceData) *v2.Clou } func cloudauthAccountFeatureToResourceData(data *schema.ResourceData, cloudAccountFeature *v2.CloudauthAccountFeatureSecure) error { + accountID := data.Get(SchemaAccountID).(string) + data.SetId(accountID + "/" + cloudAccountFeature.GetType().String()) - accountId := data.Get(SchemaAccountId).(string) - data.SetId(accountId + "/" + cloudAccountFeature.GetType().String()) - - err := data.Set(SchemaAccountId, accountId) + err := data.Set(SchemaAccountID, accountID) if err != nil { return err } diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account_feature_test.go b/sysdig/resource_sysdig_secure_cloud_auth_account_feature_test.go index bb18421e8..076fee89f 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account_feature_test.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account_feature_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_cloud_auth_account_test.go b/sysdig/resource_sysdig_secure_cloud_auth_account_test.go index 17d06ca6b..bcd8bf583 100644 --- a/sysdig/resource_sysdig_secure_cloud_auth_account_test.go +++ b/sysdig/resource_sysdig_secure_cloud_auth_account_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( @@ -765,5 +763,4 @@ resource "sysdig_secure_cloud_auth_account" "sample" { }) } }`, fmt.Sprintf("ocid1.tenancy.oc1..%s", compartmentID), fmt.Sprintf("ocid1.tenancy.oc1..%s", tenantID)) - } diff --git a/sysdig/resource_sysdig_secure_custom_policy.go b/sysdig/resource_sysdig_secure_custom_policy.go index 7b7d31858..d652deae3 100644 --- a/sysdig/resource_sysdig_secure_custom_policy.go +++ b/sysdig/resource_sysdig_secure_custom_policy.go @@ -70,7 +70,7 @@ func resourceSysdigSecureCustomPolicy() *schema.Resource { } } -func resourceSysdigCustomPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigCustomPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -100,7 +100,7 @@ func customPolicyFromResourceData(d *schema.ResourceData) v2.Policy { policy.Rules = []*v2.PolicyRule{} for _, ruleItr := range d.Get("rules").(*schema.Set).List() { - ruleInfo := ruleItr.(map[string]interface{}) + ruleInfo := ruleItr.(map[string]any) rule := &v2.PolicyRule{ Name: ruleInfo["name"].(string), Enabled: ruleInfo["enabled"].(bool), @@ -123,16 +123,16 @@ func customPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { } rules := getPolicyRulesFromResourceData(d) - newRules := []map[string]interface{}{} + newRules := []map[string]any{} for _, rule := range policy.Rules { - newRules = append(newRules, map[string]interface{}{ + newRules = append(newRules, map[string]any{ "name": rule.Name, "enabled": rule.Enabled, }) } - currentRules := []map[string]interface{}{} + currentRules := []map[string]any{} for _, rule := range rules { - currentRules = append(currentRules, map[string]interface{}{ + currentRules = append(currentRules, map[string]any{ "name": rule.Name, "enabled": rule.Enabled, }) @@ -150,7 +150,7 @@ func getPolicyRulesFromResourceData(d *schema.ResourceData) []*v2.PolicyRule { policyRules := make([]*v2.PolicyRule, len(rules)) for i, ruleItr := range rules { - ruleInfo := ruleItr.(map[string]interface{}) + ruleInfo := ruleItr.(map[string]any) policyRules[i] = &v2.PolicyRule{ Name: ruleInfo["name"].(string), Enabled: ruleInfo["enabled"].(bool), @@ -160,7 +160,7 @@ func getPolicyRulesFromResourceData(d *schema.ResourceData) []*v2.PolicyRule { return policyRules } -func arePolicyRulesEquivalent(newRules []map[string]interface{}, currentRules []map[string]interface{}) bool { +func arePolicyRulesEquivalent(newRules []map[string]any, currentRules []map[string]any) bool { if len(newRules) != len(currentRules) { return false } @@ -182,7 +182,7 @@ func arePolicyRulesEquivalent(newRules []map[string]interface{}, currentRules [] return true } -func resourceSysdigCustomPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigCustomPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -203,7 +203,7 @@ func resourceSysdigCustomPolicyRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigCustomPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigCustomPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -221,7 +221,7 @@ func resourceSysdigCustomPolicyDelete(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigCustomPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigCustomPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -243,7 +243,7 @@ func resourceSysdigCustomPolicyUpdate(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigSecureCustomPolicyImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureCustomPolicyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -259,7 +259,7 @@ func resourceSysdigSecureCustomPolicyImportState(ctx context.Context, d *schema. return nil, err } - if policy.IsDefault || policy.TemplateId != 0 { + if policy.IsDefault || policy.TemplateID != 0 { return nil, errors.New("unable to import policy that is not a custom policy") } diff --git a/sysdig/resource_sysdig_secure_custom_policy_test.go b/sysdig/resource_sysdig_secure_custom_policy_test.go index cf80c8cb3..1c1d9df80 100644 --- a/sysdig/resource_sysdig_secure_custom_policy_test.go +++ b/sysdig/resource_sysdig_secure_custom_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_drift_policy.go b/sysdig/resource_sysdig_secure_drift_policy.go index 7927a6eca..d46202cbe 100644 --- a/sysdig/resource_sysdig_secure_drift_policy.go +++ b/sysdig/resource_sysdig_secure_drift_policy.go @@ -103,7 +103,7 @@ func driftPolicyToResourceData(policy *v2.PolicyRulesComposite, d *schema.Resour return driftTFResourceReducer(d, *policy) } -func resourceSysdigDriftPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigDriftPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -129,7 +129,7 @@ func resourceSysdigDriftPolicyCreate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigDriftPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigDriftPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -150,7 +150,7 @@ func resourceSysdigDriftPolicyUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigDriftPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigDriftPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -174,7 +174,7 @@ func resourceSysdigDriftPolicyRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigDriftPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigDriftPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -187,7 +187,7 @@ func resourceSysdigDriftPolicyDelete(ctx context.Context, d *schema.ResourceData } if policy.Policy.ID == 0 { - return diag.FromErr(errors.New("Policy ID is missing")) + return diag.FromErr(errors.New("policy ID is missing")) } err = client.DeleteCompositePolicy(ctx, policy.Policy.ID) @@ -199,7 +199,7 @@ func resourceSysdigDriftPolicyDelete(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigSecureDriftPolicyImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureDriftPolicyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -211,7 +211,7 @@ func resourceSysdigSecureDriftPolicyImportState(ctx context.Context, d *schema.R } if policy.Policy.ID == 0 { - return nil, errors.New("Policy ID is missing") + return nil, errors.New("policy ID is missing") } policy, _, err = client.GetCompositePolicyByID(ctx, policy.Policy.ID) @@ -219,7 +219,7 @@ func resourceSysdigSecureDriftPolicyImportState(ctx context.Context, d *schema.R return nil, err } - if policy.Policy.IsDefault || policy.Policy.TemplateId != 0 { + if policy.Policy.IsDefault || policy.Policy.TemplateID != 0 { return nil, errors.New("unable to import policy that is not a custom policy") } diff --git a/sysdig/resource_sysdig_secure_drift_policy_test.go b/sysdig/resource_sysdig_secure_drift_policy_test.go index 8916f1f3d..03390abdc 100644 --- a/sysdig/resource_sysdig_secure_drift_policy_test.go +++ b/sysdig/resource_sysdig_secure_drift_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_list.go b/sysdig/resource_sysdig_secure_list.go index 6e4be74e7..0f15ce1f8 100644 --- a/sysdig/resource_sysdig_secure_list.go +++ b/sysdig/resource_sysdig_secure_list.go @@ -61,7 +61,7 @@ func getSecureListClient(c SysdigClients) (v2.ListInterface, error) { return c.sysdigSecureClientV2() } -func resourceSysdigListCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigListCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureListClient(sysdigClients) if err != nil { @@ -81,7 +81,7 @@ func resourceSysdigListCreate(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigListUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigListUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureListClient(sysdigClients) if err != nil { @@ -103,7 +103,7 @@ func resourceSysdigListUpdate(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigListRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureListClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -123,7 +123,7 @@ func resourceSysdigListRead(ctx context.Context, d *schema.ResourceData, meta in return nil } -func resourceSysdigListDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigListDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureListClient(sysdigClients) if err != nil { @@ -148,11 +148,11 @@ func listFromResourceData(d *schema.ResourceData) v2.List { Items: v2.Items{Items: []string{}}, } - items := d.Get("items").([]interface{}) + items := d.Get("items").([]any) for _, item := range items { - if item_str, ok := item.(string); ok { - item_str = strings.TrimSpace(item_str) - list.Items.Items = append(list.Items.Items, item_str) + if itemStr, ok := item.(string); ok { + itemStr = strings.TrimSpace(itemStr) + list.Items.Items = append(list.Items.Items, itemStr) } } diff --git a/sysdig/resource_sysdig_secure_list_test.go b/sysdig/resource_sysdig_secure_list_test.go index 527384e61..ef73a176b 100644 --- a/sysdig/resource_sysdig_secure_list_test.go +++ b/sysdig/resource_sysdig_secure_list_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_macro.go b/sysdig/resource_sysdig_secure_macro.go index 03940fa5d..365ba36e7 100644 --- a/sysdig/resource_sysdig_secure_macro.go +++ b/sysdig/resource_sysdig_secure_macro.go @@ -61,7 +61,7 @@ func getSecureMacroClient(c SysdigClients) (v2.MacroInterface, error) { return c.sysdigSecureClientV2() } -func resourceSysdigMacroCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMacroCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureMacroClient(sysdigClients) if err != nil { @@ -81,7 +81,7 @@ func resourceSysdigMacroCreate(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigMacroUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMacroUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureMacroClient(sysdigClients) if err != nil { @@ -103,7 +103,7 @@ func resourceSysdigMacroUpdate(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigMacroRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMacroRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureMacroClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -126,7 +126,7 @@ func resourceSysdigMacroRead(ctx context.Context, d *schema.ResourceData, meta i return nil } -func resourceSysdigMacroDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMacroDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureMacroClient(sysdigClients) if err != nil { diff --git a/sysdig/resource_sysdig_secure_macro_test.go b/sysdig/resource_sysdig_secure_macro_test.go index 8e1213889..8e8f57635 100644 --- a/sysdig/resource_sysdig_secure_macro_test.go +++ b/sysdig/resource_sysdig_secure_macro_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_malware_policy.go b/sysdig/resource_sysdig_secure_malware_policy.go index c5b29b4e3..364ec673a 100644 --- a/sysdig/resource_sysdig_secure_malware_policy.go +++ b/sysdig/resource_sysdig_secure_malware_policy.go @@ -106,7 +106,7 @@ func malwarePolicyToResourceData(policy *v2.PolicyRulesComposite, d *schema.Reso return malwareTFResourceReducer(d, *policy) } -func resourceSysdigMalwarePolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMalwarePolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -132,7 +132,7 @@ func resourceSysdigMalwarePolicyCreate(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigMalwarePolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMalwarePolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -153,7 +153,7 @@ func resourceSysdigMalwarePolicyUpdate(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigMalwarePolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMalwarePolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -177,7 +177,7 @@ func resourceSysdigMalwarePolicyRead(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigMalwarePolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMalwarePolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -190,7 +190,7 @@ func resourceSysdigMalwarePolicyDelete(ctx context.Context, d *schema.ResourceDa } if policy.Policy.ID == 0 { - return diag.FromErr(errors.New("Policy ID is missing")) + return diag.FromErr(errors.New("policy ID is missing")) } err = client.DeleteCompositePolicy(ctx, policy.Policy.ID) @@ -202,7 +202,7 @@ func resourceSysdigMalwarePolicyDelete(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigSecureMalwarePolicyImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureMalwarePolicyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -214,7 +214,7 @@ func resourceSysdigSecureMalwarePolicyImportState(ctx context.Context, d *schema } if policy.Policy.ID == 0 { - return nil, errors.New("Policy ID is missing") + return nil, errors.New("policy ID is missing") } policy, _, err = client.GetCompositePolicyByID(ctx, policy.Policy.ID) @@ -222,7 +222,7 @@ func resourceSysdigSecureMalwarePolicyImportState(ctx context.Context, d *schema return nil, err } - if policy.Policy.IsDefault || policy.Policy.TemplateId != 0 { + if policy.Policy.IsDefault || policy.Policy.TemplateID != 0 { return nil, errors.New("unable to import policy that is not a custom policy") } diff --git a/sysdig/resource_sysdig_secure_malware_policy_test.go b/sysdig/resource_sysdig_secure_malware_policy_test.go index 1e64efd36..cd8a0fcb6 100644 --- a/sysdig/resource_sysdig_secure_malware_policy_test.go +++ b/sysdig/resource_sysdig_secure_malware_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_managed_policy.go b/sysdig/resource_sysdig_secure_managed_policy.go index 5f5830616..0b7537984 100644 --- a/sysdig/resource_sysdig_secure_managed_policy.go +++ b/sysdig/resource_sysdig_secure_managed_policy.go @@ -45,7 +45,7 @@ func resourceSysdigSecureManagedPolicy() *schema.Resource { } } -func resourceSysdigManagedPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -104,7 +104,7 @@ func updateManagedPolicyFromResourceData(policy *v2.Policy, d *schema.ResourceDa } } -func resourceSysdigManagedPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -125,7 +125,7 @@ func resourceSysdigManagedPolicyRead(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigManagedPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -163,7 +163,7 @@ func resourceSysdigManagedPolicyDelete(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigManagedPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { diff --git a/sysdig/resource_sysdig_secure_managed_policy_test.go b/sysdig/resource_sysdig_secure_managed_policy_test.go index a873f4f0b..0c54b8e72 100644 --- a/sysdig/resource_sysdig_secure_managed_policy_test.go +++ b/sysdig/resource_sysdig_secure_managed_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_managed_ruleset.go b/sysdig/resource_sysdig_secure_managed_ruleset.go index 0625f824b..cd1391fe5 100644 --- a/sysdig/resource_sysdig_secure_managed_ruleset.go +++ b/sysdig/resource_sysdig_secure_managed_ruleset.go @@ -76,7 +76,7 @@ func resourceSysdigSecureManagedRuleset() *schema.Resource { } } -func resourceSysdigManagedRulesetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedRulesetCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -95,7 +95,7 @@ func resourceSysdigManagedRulesetCreate(ctx context.Context, d *schema.ResourceD policy.Rules = managedPolicy.Rules updateManagedRulesetFromResourceData(&policy, d) - policy.TemplateId = managedPolicy.TemplateId + policy.TemplateID = managedPolicy.TemplateID policy.TemplateVersion = managedPolicy.TemplateVersion createdPolicy, err := client.CreatePolicy(ctx, policy) @@ -114,7 +114,7 @@ func managedRulesetToResourceData(policy *v2.Policy, d *schema.ResourceData) { _ = d.Set("description", policy.Description) _ = d.Set("severity", policy.Severity) - _ = d.Set("template_id", policy.TemplateId) + _ = d.Set("template_id", policy.TemplateID) disabledRules := []string{} for _, rule := range policy.Rules { @@ -129,7 +129,7 @@ func updateManagedRulesetFromResourceData(policy *v2.Policy, d *schema.ResourceD commonPolicyFromResourceData(policy, d) policy.Description = d.Get("description").(string) policy.Severity = d.Get("severity").(int) - policy.TemplateId = d.Get("template_id").(int) + policy.TemplateID = d.Get("template_id").(int) disabledRules := d.Get("disabled_rules").(*schema.Set) for _, rule := range policy.Rules { @@ -141,7 +141,7 @@ func updateManagedRulesetFromResourceData(policy *v2.Policy, d *schema.ResourceD } } -func resourceSysdigManagedRulesetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedRulesetRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -162,7 +162,7 @@ func resourceSysdigManagedRulesetRead(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigManagedRulesetDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedRulesetDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -180,7 +180,7 @@ func resourceSysdigManagedRulesetDelete(ctx context.Context, d *schema.ResourceD return nil } -func resourceSysdigManagedRulesetUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigManagedRulesetUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -209,7 +209,7 @@ func resourceSysdigManagedRulesetUpdate(ctx context.Context, d *schema.ResourceD return nil } -func resourceSysdigSecureManagedRulesetImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureManagedRulesetImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -225,7 +225,7 @@ func resourceSysdigSecureManagedRulesetImportState(ctx context.Context, d *schem return nil, err } - if managedRuleset.TemplateId == 0 || managedRuleset.IsDefault { + if managedRuleset.TemplateID == 0 || managedRuleset.IsDefault { return nil, errors.New("unable to import policy that is not a managed ruleset") } @@ -235,7 +235,7 @@ func resourceSysdigSecureManagedRulesetImportState(ctx context.Context, d *schem } for _, policy := range policies { - if policy.IsDefault && policy.TemplateId == managedRuleset.TemplateId { + if policy.IsDefault && policy.TemplateID == managedRuleset.TemplateID { inheritedFrom := map[string]string{ "name": policy.Name, "type": policy.Type, diff --git a/sysdig/resource_sysdig_secure_managed_ruleset_test.go b/sysdig/resource_sysdig_secure_managed_ruleset_test.go index 98dbdce94..443953d2e 100644 --- a/sysdig/resource_sysdig_secure_managed_ruleset_test.go +++ b/sysdig/resource_sysdig_secure_managed_ruleset_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_ml_policy.go b/sysdig/resource_sysdig_secure_ml_policy.go index c4008db3d..e16e7ea31 100644 --- a/sysdig/resource_sysdig_secure_ml_policy.go +++ b/sysdig/resource_sysdig_secure_ml_policy.go @@ -88,7 +88,7 @@ func mlPolicyToResourceData(policy *v2.PolicyRulesComposite, d *schema.ResourceD return mlTFResourceReducer(d, *policy) } -func resourceSysdigMLPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMLPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -115,7 +115,7 @@ func resourceSysdigMLPolicyCreate(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigMLPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMLPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -136,7 +136,7 @@ func resourceSysdigMLPolicyUpdate(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMLPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -160,7 +160,7 @@ func resourceSysdigMLPolicyRead(ctx context.Context, d *schema.ResourceData, met return nil } -func resourceSysdigMLPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigMLPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureCompositePolicyClient(sysdigClients) if err != nil { @@ -173,7 +173,7 @@ func resourceSysdigMLPolicyDelete(ctx context.Context, d *schema.ResourceData, m } if policy.Policy.ID == 0 { - return diag.FromErr(errors.New("Policy ID is missing")) + return diag.FromErr(errors.New("policy ID is missing")) } err = client.DeleteCompositePolicy(ctx, policy.Policy.ID) @@ -185,7 +185,7 @@ func resourceSysdigMLPolicyDelete(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigSecureMLPolicyImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceSysdigSecureMLPolicyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { client, err := getSecureCompositePolicyClient(meta.(SysdigClients)) if err != nil { return nil, err @@ -197,7 +197,7 @@ func resourceSysdigSecureMLPolicyImportState(ctx context.Context, d *schema.Reso } if policy.Policy.ID == 0 { - return nil, errors.New("Policy ID is missing") + return nil, errors.New("policy ID is missing") } policy, _, err = client.GetCompositePolicyByID(ctx, policy.Policy.ID) @@ -205,7 +205,7 @@ func resourceSysdigSecureMLPolicyImportState(ctx context.Context, d *schema.Reso return nil, err } - if policy.Policy.IsDefault || policy.Policy.TemplateId != 0 { + if policy.Policy.IsDefault || policy.Policy.TemplateID != 0 { return nil, errors.New("unable to import policy that is not a custom policy") } diff --git a/sysdig/resource_sysdig_secure_ml_policy_test.go b/sysdig/resource_sysdig_secure_ml_policy_test.go index ab4f73b94..e35078435 100644 --- a/sysdig/resource_sysdig_secure_ml_policy_test.go +++ b/sysdig/resource_sysdig_secure_ml_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies_aws || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_email.go b/sysdig/resource_sysdig_secure_notification_channel_email.go index 62d8585df..e270e9127 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_email.go +++ b/sysdig/resource_sysdig_secure_notification_channel_email.go @@ -42,7 +42,7 @@ func resourceSysdigSecureNotificationChannelEmail() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelEmailCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelEmailCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -68,16 +68,16 @@ func resourceSysdigSecureNotificationChannelEmailCreate(ctx context.Context, d * return resourceSysdigSecureNotificationChannelEmailRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -92,7 +92,7 @@ func resourceSysdigSecureNotificationChannelEmailRead(ctx context.Context, d *sc return nil } -func resourceSysdigSecureNotificationChannelEmailUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelEmailUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -119,7 +119,7 @@ func resourceSysdigSecureNotificationChannelEmailUpdate(ctx context.Context, d * return nil } -func resourceSysdigSecureNotificationChannelEmailDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelEmailDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -141,7 +141,7 @@ func secureNotificationChannelEmailFromResourceData(d *schema.ResourceData, team return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_EMAIL + nc.Type = notificationChannelTypeEmail nc.Options.EmailRecipients = cast.ToStringSlice(d.Get("recipients").(*schema.Set).List()) return } diff --git a/sysdig/resource_sysdig_secure_notification_channel_email_test.go b/sysdig/resource_sysdig_secure_notification_channel_email_test.go index d489e3334..104b322b5 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_email_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_msteams.go b/sysdig/resource_sysdig_secure_notification_channel_msteams.go index 7b6f4fdf6..e4054ca36 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_msteams.go +++ b/sysdig/resource_sysdig_secure_notification_channel_msteams.go @@ -44,7 +44,7 @@ func resourceSysdigSecureNotificationChannelMSTeams() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelMSTeamsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelMSTeamsCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -70,7 +70,7 @@ func resourceSysdigSecureNotificationChannelMSTeamsCreate(ctx context.Context, d return resourceSysdigSecureNotificationChannelMSTeamsRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -81,9 +81,9 @@ func resourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d * return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -98,7 +98,7 @@ func resourceSysdigSecureNotificationChannelMSTeamsRead(ctx context.Context, d * return nil } -func resourceSysdigSecureNotificationChannelMSTeamsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelMSTeamsUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -128,7 +128,7 @@ func resourceSysdigSecureNotificationChannelMSTeamsUpdate(ctx context.Context, d return resourceSysdigSecureNotificationChannelMSTeamsRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelMSTeamsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelMSTeamsDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -153,8 +153,8 @@ func secureNotificationChannelMSTeamsFromResourceData(d *schema.ResourceData, te return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_MS_TEAMS - nc.Options.Url = d.Get("url").(string) + nc.Type = notificationChannelTypeMSTeams + nc.Options.URL = d.Get("url").(string) setNotificationChannelMSTeamsTemplateConfig(&nc, d) @@ -168,10 +168,10 @@ func setNotificationChannelMSTeamsTemplateConfig(nc *v2.NotificationChannel, d * case "v1": nc.Options.TemplateConfiguration = []v2.NotificationChannelTemplateConfiguration{ { - TemplateKey: NOTIFICATION_CHANNEL_TYPE_MS_TEAMS_TEMPLATE_KEY_V1, + TemplateKey: notificationChannelTypeMSTeamsTemplateKeyV1, TemplateConfigurationSections: []v2.NotificationChannelTemplateConfigurationSection{ { - SectionName: NOTIFICATION_CHANNEL_SECURE_EVENT_NOTIFICATION_CONTENT_SECTION, + SectionName: notificationChannelSecureEventNotificationContentSection, ShouldShow: true, }, }, @@ -180,10 +180,10 @@ func setNotificationChannelMSTeamsTemplateConfig(nc *v2.NotificationChannel, d * case "v2": nc.Options.TemplateConfiguration = []v2.NotificationChannelTemplateConfiguration{ { - TemplateKey: NOTIFICATION_CHANNEL_TYPE_MS_TEAMS_TEMPLATE_KEY_V2, + TemplateKey: notificationChannelTypeMSTeamsTemplateKeyV2, TemplateConfigurationSections: []v2.NotificationChannelTemplateConfigurationSection{ { - SectionName: NOTIFICATION_CHANNEL_SECURE_EVENT_NOTIFICATION_CONTENT_SECTION, + SectionName: notificationChannelSecureEventNotificationContentSection, ShouldShow: true, }, }, @@ -198,7 +198,7 @@ func secureNotificationChannelMSTeamsToResourceData(nc *v2.NotificationChannel, return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) err = getTemplateVersionFromNotificationChannelMSTeams(nc, d) @@ -215,7 +215,7 @@ func getTemplateVersionFromNotificationChannelMSTeams(nc *v2.NotificationChannel } switch nc.Options.TemplateConfiguration[0].TemplateKey { - case NOTIFICATION_CHANNEL_TYPE_MS_TEAMS_TEMPLATE_KEY_V2: + case notificationChannelTypeMSTeamsTemplateKeyV2: _ = d.Set("template_version", "v2") default: _ = d.Set("template_version", "v1") diff --git a/sysdig/resource_sysdig_secure_notification_channel_msteams_test.go b/sysdig/resource_sysdig_secure_notification_channel_msteams_test.go index a42046b14..31fe4f51e 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_msteams_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_msteams_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go b/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go index d453d2c22..2b6ae82b6 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go +++ b/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go @@ -47,7 +47,7 @@ func resourceSysdigSecureNotificationChannelOpsGenie() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelOpsGenieCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelOpsGenieCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -73,16 +73,16 @@ func resourceSysdigSecureNotificationChannelOpsGenieCreate(ctx context.Context, return resourceSysdigSecureNotificationChannelOpsGenieRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelOpsGenieRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -97,7 +97,7 @@ func resourceSysdigSecureNotificationChannelOpsGenieRead(ctx context.Context, d return nil } -func resourceSysdigSecureNotificationChannelOpsGenieUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelOpsGenieUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -124,7 +124,7 @@ func resourceSysdigSecureNotificationChannelOpsGenieUpdate(ctx context.Context, return nil } -func resourceSysdigSecureNotificationChannelOpsGenieDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelOpsGenieDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -146,7 +146,7 @@ func secureNotificationChannelOpsGenieFromResourceData(d *schema.ResourceData, t return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_OPSGENIE + nc.Type = notificationChannelTypeOpsGenie apiKey := d.Get("api_key").(string) nc.Options.APIKey = apiKey nc.Options.Region = d.Get("region").(string) diff --git a/sysdig/resource_sysdig_secure_notification_channel_opsgenie_test.go b/sysdig/resource_sysdig_secure_notification_channel_opsgenie_test.go index 8e816504a..693e6aa59 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_opsgenie_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_opsgenie_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go b/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go index 10d000bbe..88c58ac5e 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go +++ b/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go @@ -48,7 +48,7 @@ func resourceSysdigSecureNotificationChannelPagerduty() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelPagerdutyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPagerdutyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -74,16 +74,16 @@ func resourceSysdigSecureNotificationChannelPagerdutyCreate(ctx context.Context, return resourceSysdigSecureNotificationChannelPagerdutyRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPagerdutyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -98,7 +98,7 @@ func resourceSysdigSecureNotificationChannelPagerdutyRead(ctx context.Context, d return nil } -func resourceSysdigSecureNotificationChannelPagerdutyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPagerdutyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -125,7 +125,7 @@ func resourceSysdigSecureNotificationChannelPagerdutyUpdate(ctx context.Context, return nil } -func resourceSysdigSecureNotificationChannelPagerdutyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPagerdutyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -147,7 +147,7 @@ func secureNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_PAGERDUTY + nc.Type = notificationChannelTypePagerduty nc.Options.Account = d.Get("account").(string) nc.Options.ServiceKey = d.Get("service_key").(string) nc.Options.ServiceName = d.Get("service_name").(string) diff --git a/sysdig/resource_sysdig_secure_notification_channel_pagerduty_test.go b/sysdig/resource_sysdig_secure_notification_channel_pagerduty_test.go index 58c9445de..e3934ddf1 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_pagerduty_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_pagerduty_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go b/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go index 6c39bf2ce..e97b1ceb7 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go +++ b/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go @@ -49,7 +49,7 @@ func resourceSysdigSecureNotificationChannelPrometheusAlertManager() *schema.Res } } -func resourceSysdigSecureNotificationChannelPrometheusAlertManagerCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPrometheusAlertManagerCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureNotificationChannelClient(clients) if err != nil { @@ -76,16 +76,16 @@ func resourceSysdigSecureNotificationChannelPrometheusAlertManagerCreate(ctx con return resourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -100,7 +100,7 @@ func resourceSysdigSecureNotificationChannelPrometheusAlertManagerRead(ctx conte return nil } -func resourceSysdigSecureNotificationChannelPrometheusAlertManagerUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPrometheusAlertManagerUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -127,7 +127,7 @@ func resourceSysdigSecureNotificationChannelPrometheusAlertManagerUpdate(ctx con return nil } -func resourceSysdigSecureNotificationChannelPrometheusAlertManagerDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelPrometheusAlertManagerDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -149,9 +149,9 @@ func secureNotificationChannelPrometheusAlertManagerFromResourceData(d *schema.R return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_PROMETHEUS_ALERT_MANAGER - nc.Options.Url = d.Get("url").(string) - nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]interface{}) + nc.Type = notificationChannelTypePrometheusAlertManager + nc.Options.URL = d.Get("url").(string) + nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections return @@ -163,7 +163,7 @@ func secureNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.Notifi return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("additional_headers", nc.Options.AdditionalHeaders) if nc.Options.AllowInsecureConnections != nil { diff --git a/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager_test.go b/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager_test.go index 925cab19f..ef612ca98 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_slack.go b/sysdig/resource_sysdig_secure_notification_channel_slack.go index 23b8cb6b9..a913bebe8 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_slack.go +++ b/sysdig/resource_sysdig_secure_notification_channel_slack.go @@ -60,7 +60,7 @@ func resourceSysdigSecureNotificationChannelSlack() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelSlackCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSlackCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -86,7 +86,7 @@ func resourceSysdigSecureNotificationChannelSlackCreate(ctx context.Context, d * return resourceSysdigSecureNotificationChannelSlackRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -97,9 +97,9 @@ func resourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *sc return diag.FromErr(err) } - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -114,7 +114,7 @@ func resourceSysdigSecureNotificationChannelSlackRead(ctx context.Context, d *sc return nil } -func resourceSysdigSecureNotificationChannelSlackUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSlackUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -146,7 +146,7 @@ func resourceSysdigSecureNotificationChannelSlackUpdate(ctx context.Context, d * return nil } -func resourceSysdigSecureNotificationChannelSlackDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSlackDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -171,11 +171,11 @@ func secureNotificationChannelSlackFromResourceData(d *schema.ResourceData, team return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_SLACK - nc.Options.Url = d.Get("url").(string) + nc.Type = notificationChannelTypeSlack + nc.Options.URL = d.Get("url").(string) nc.Options.Channel = d.Get("channel").(string) nc.Options.PrivateChannel = d.Get("is_private_channel").(bool) - nc.Options.PrivateChannelUrl = d.Get("private_channel_url").(string) + nc.Options.PrivateChannelURL = d.Get("private_channel_url").(string) setNotificationChannelSlackTemplateConfig(&nc, d) @@ -189,10 +189,10 @@ func setNotificationChannelSlackTemplateConfig(nc *v2.NotificationChannel, d *sc case "v1": nc.Options.TemplateConfiguration = []v2.NotificationChannelTemplateConfiguration{ { - TemplateKey: NOTIFICATION_CHANNEL_TYPE_SLACK_TEMPLATE_KEY_V1, + TemplateKey: notificationChannelTypeSlackTemplateKeyV1, TemplateConfigurationSections: []v2.NotificationChannelTemplateConfigurationSection{ { - SectionName: NOTIFICATION_CHANNEL_SECURE_EVENT_NOTIFICATION_CONTENT_SECTION, + SectionName: notificationChannelSecureEventNotificationContentSection, ShouldShow: true, }, }, @@ -201,10 +201,10 @@ func setNotificationChannelSlackTemplateConfig(nc *v2.NotificationChannel, d *sc case "v2": nc.Options.TemplateConfiguration = []v2.NotificationChannelTemplateConfiguration{ { - TemplateKey: NOTIFICATION_CHANNEL_TYPE_SLACK_TEMPLATE_KEY_V2, + TemplateKey: notificationChannelTypeMSTeamsTemplateKeyV2, TemplateConfigurationSections: []v2.NotificationChannelTemplateConfigurationSection{ { - SectionName: NOTIFICATION_CHANNEL_SECURE_EVENT_NOTIFICATION_CONTENT_SECTION, + SectionName: notificationChannelSecureEventNotificationContentSection, ShouldShow: true, }, }, @@ -219,10 +219,10 @@ func secureNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("channel", nc.Options.Channel) _ = d.Set("is_private_channel", nc.Options.PrivateChannel) - _ = d.Set("private_channel_url", nc.Options.PrivateChannelUrl) + _ = d.Set("private_channel_url", nc.Options.PrivateChannelURL) err = getTemplateVersionFromNotificationChannelSlack(nc, d) @@ -239,7 +239,7 @@ func getTemplateVersionFromNotificationChannelSlack(nc *v2.NotificationChannel, } switch nc.Options.TemplateConfiguration[0].TemplateKey { - case NOTIFICATION_CHANNEL_TYPE_SLACK_TEMPLATE_KEY_V2: + case notificationChannelTypeSlackTemplateKeyV2: _ = d.Set("template_version", "v2") default: _ = d.Set("template_version", "v1") diff --git a/sysdig/resource_sysdig_secure_notification_channel_slack_test.go b/sysdig/resource_sysdig_secure_notification_channel_slack_test.go index d4044c462..9b6f0df0f 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_slack_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_slack_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_sns.go b/sysdig/resource_sysdig_secure_notification_channel_sns.go index e15672e97..460d0c4bc 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_sns.go +++ b/sysdig/resource_sysdig_secure_notification_channel_sns.go @@ -41,7 +41,7 @@ func resourceSysdigSecureNotificationChannelSNS() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelSNSCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSNSCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -67,16 +67,16 @@ func resourceSysdigSecureNotificationChannelSNSCreate(ctx context.Context, d *sc return resourceSysdigSecureNotificationChannelSNSRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSNSRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -91,7 +91,7 @@ func resourceSysdigSecureNotificationChannelSNSRead(ctx context.Context, d *sche return nil } -func resourceSysdigSecureNotificationChannelSNSUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSNSUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -118,7 +118,7 @@ func resourceSysdigSecureNotificationChannelSNSUpdate(ctx context.Context, d *sc return nil } -func resourceSysdigSecureNotificationChannelSNSDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelSNSDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -140,7 +140,7 @@ func secureNotificationChannelSNSFromResourceData(d *schema.ResourceData, teamID return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_AMAZON_SNS + nc.Type = notificationChannelTypeAmazonSNS nc.Options.SnsTopicARNs = cast.ToStringSlice(d.Get("topics").(*schema.Set).List()) return } diff --git a/sysdig/resource_sysdig_secure_notification_channel_sns_test.go b/sysdig/resource_sysdig_secure_notification_channel_sns_test.go index 62fb64863..8f97d26eb 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_sns_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_sns_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_team_email.go b/sysdig/resource_sysdig_secure_notification_channel_team_email.go index 39fe39c88..dbc442b94 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_team_email.go +++ b/sysdig/resource_sysdig_secure_notification_channel_team_email.go @@ -40,7 +40,7 @@ func resourceSysdigSecureNotificationChannelTeamEmail() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelTeamEmailCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelTeamEmailCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -66,16 +66,16 @@ func resourceSysdigSecureNotificationChannelTeamEmailCreate(ctx context.Context, return resourceSysdigSecureNotificationChannelTeamEmailRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelTeamEmailRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -90,7 +90,7 @@ func resourceSysdigSecureNotificationChannelTeamEmailRead(ctx context.Context, d return nil } -func resourceSysdigSecureNotificationChannelTeamEmailUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelTeamEmailUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -117,7 +117,7 @@ func resourceSysdigSecureNotificationChannelTeamEmailUpdate(ctx context.Context, return nil } -func resourceSysdigSecureNotificationChannelTeamEmailDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelTeamEmailDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -139,8 +139,8 @@ func secureNotificationChannelTeamEmailFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_TEAM_EMAIL - nc.Options.TeamId = d.Get("team_id").(int) + nc.Type = notificationChannelTypeTeamEmail + nc.Options.TeamID = d.Get("team_id").(int) return } @@ -150,7 +150,7 @@ func secureNotificationChannelTeamEmailToResourceData(nc *v2.NotificationChannel return } - _ = d.Set("team_id", nc.Options.TeamId) + _ = d.Set("team_id", nc.Options.TeamID) return } diff --git a/sysdig/resource_sysdig_secure_notification_channel_team_email_test.go b/sysdig/resource_sysdig_secure_notification_channel_team_email_test.go index 2e767b4d0..b99557f1c 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_team_email_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_team_email_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_victorops.go b/sysdig/resource_sysdig_secure_notification_channel_victorops.go index db96f76ba..f71acd195 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_victorops.go +++ b/sysdig/resource_sysdig_secure_notification_channel_victorops.go @@ -43,7 +43,7 @@ func resourceSysdigSecureNotificationChannelVictorOps() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelVictorOpsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelVictorOpsCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -69,16 +69,16 @@ func resourceSysdigSecureNotificationChannelVictorOpsCreate(ctx context.Context, return resourceSysdigSecureNotificationChannelVictorOpsRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelVictorOpsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -93,7 +93,7 @@ func resourceSysdigSecureNotificationChannelVictorOpsRead(ctx context.Context, d return nil } -func resourceSysdigSecureNotificationChannelVictorOpsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelVictorOpsUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -120,7 +120,7 @@ func resourceSysdigSecureNotificationChannelVictorOpsUpdate(ctx context.Context, return nil } -func resourceSysdigSecureNotificationChannelVictorOpsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelVictorOpsDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -141,7 +141,7 @@ func secureNotificationChannelVictorOpsFromResourceData(d *schema.ResourceData, return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_VICTOROPS + nc.Type = notificationChannelTypeVictorOps nc.Options.APIKey = d.Get("api_key").(string) nc.Options.RoutingKey = d.Get("routing_key").(string) return diff --git a/sysdig/resource_sysdig_secure_notification_channel_victorops_test.go b/sysdig/resource_sysdig_secure_notification_channel_victorops_test.go index 5c7f820a3..b1f6556e0 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_victorops_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_victorops_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_notification_channel_webhook.go b/sysdig/resource_sysdig_secure_notification_channel_webhook.go index 981e83cd1..a59a83268 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_webhook.go +++ b/sysdig/resource_sysdig_secure_notification_channel_webhook.go @@ -53,7 +53,7 @@ func resourceSysdigSecureNotificationChannelWebhook() *schema.Resource { } } -func resourceSysdigSecureNotificationChannelWebhookCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelWebhookCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -79,16 +79,16 @@ func resourceSysdigSecureNotificationChannelWebhookCreate(ctx context.Context, d return resourceSysdigSecureNotificationChannelWebhookRead(ctx, d, meta) } -func resourceSysdigSecureNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelWebhookRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - nc, err := client.GetNotificationChannelById(ctx, id) + nc, err := client.GetNotificationChannelByID(ctx, id) if err != nil { - if err == v2.NotificationChannelNotFound { + if err == v2.ErrNotificationChannelNotFound { d.SetId("") return nil } @@ -103,7 +103,7 @@ func resourceSysdigSecureNotificationChannelWebhookRead(ctx context.Context, d * return nil } -func resourceSysdigSecureNotificationChannelWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelWebhookUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -130,7 +130,7 @@ func resourceSysdigSecureNotificationChannelWebhookUpdate(ctx context.Context, d return nil } -func resourceSysdigSecureNotificationChannelWebhookDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureNotificationChannelWebhookDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -152,10 +152,10 @@ func secureNotificationChannelWebhookFromResourceData(d *schema.ResourceData, te return } - nc.Type = NOTIFICATION_CHANNEL_TYPE_WEBHOOK - nc.Options.Url = d.Get("url").(string) - nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]interface{}) - nc.Options.CustomData = d.Get("custom_data").(map[string]interface{}) + nc.Type = notificationChannelTypeWebhook + nc.Options.URL = d.Get("url").(string) + nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) + nc.Options.CustomData = d.Get("custom_data").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections return @@ -167,7 +167,7 @@ func secureNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, return } - _ = d.Set("url", nc.Options.Url) + _ = d.Set("url", nc.Options.URL) _ = d.Set("additional_headers", nc.Options.AdditionalHeaders) _ = d.Set("custom_data", nc.Options.CustomData) if nc.Options.AllowInsecureConnections != nil { diff --git a/sysdig/resource_sysdig_secure_notification_channel_webhook_test.go b/sysdig/resource_sysdig_secure_notification_channel_webhook_test.go index f87d8eda5..3a59e0b66 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_webhook_test.go +++ b/sysdig/resource_sysdig_secure_notification_channel_webhook_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_organization.go b/sysdig/resource_sysdig_secure_organization.go index f1ef3150a..71f4ef8de 100644 --- a/sysdig/resource_sysdig_secure_organization.go +++ b/sysdig/resource_sysdig_secure_organization.go @@ -34,7 +34,7 @@ func resourceSysdigSecureOrganization() *schema.Resource { Optional: true, Computed: true, }, - SchemaManagementAccountId: { + SchemaManagementAccountID: { Type: schema.TypeString, Required: true, }, @@ -91,7 +91,7 @@ func getSecureOrganizationClient(c SysdigClients) (v2.OrganizationSecureInterfac return c.sysdigSecureClientV2() } -func resourceSysdigSecureOrganizationCreate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigSecureOrganizationCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getSecureOrganizationClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -109,7 +109,7 @@ func resourceSysdigSecureOrganizationCreate(ctx context.Context, data *schema.Re return nil } -func resourceSysdigSecureOrganizationDelete(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigSecureOrganizationDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getSecureOrganizationClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -126,7 +126,7 @@ func resourceSysdigSecureOrganizationDelete(ctx context.Context, data *schema.Re return nil } -func resourceSysdigSecureOrganizationRead(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigSecureOrganizationRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getSecureOrganizationClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -148,7 +148,7 @@ func resourceSysdigSecureOrganizationRead(ctx context.Context, data *schema.Reso return nil } -func resourceSysdigSecureOrganizationUpdate(ctx context.Context, data *schema.ResourceData, i interface{}) diag.Diagnostics { +func resourceSysdigSecureOrganizationUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { client, err := getSecureOrganizationClient(i.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -169,45 +169,45 @@ func resourceSysdigSecureOrganizationUpdate(ctx context.Context, data *schema.Re func secureOrganizationFromResourceData(data *schema.ResourceData) *v2.OrganizationSecure { secureOrganization := &v2.OrganizationSecure{CloudOrganization: cloudauth.CloudOrganization{}} - secureOrganization.CloudOrganization.ManagementAccountId = data.Get(SchemaManagementAccountId).(string) - secureOrganization.CloudOrganization.OrganizationRootId = data.Get(SchemaOrganizationRootID).(string) - secureOrganization.CloudOrganization.AutomaticOnboarding = data.Get(SchemaAutomaticOnboarding).(bool) - organizationalUnitIdsData := data.Get(SchemaOrganizationalUnitIds).([]interface{}) - for _, organizationalUnitIdData := range organizationalUnitIdsData { - secureOrganization.CloudOrganization.OrganizationalUnitIds = append( - secureOrganization.CloudOrganization.OrganizationalUnitIds, - organizationalUnitIdData.(string), + secureOrganization.ManagementAccountId = data.Get(SchemaManagementAccountID).(string) + secureOrganization.OrganizationRootId = data.Get(SchemaOrganizationRootID).(string) + secureOrganization.AutomaticOnboarding = data.Get(SchemaAutomaticOnboarding).(bool) + organizationalUnitIdsData := data.Get(SchemaOrganizationalUnitIds).([]any) + for _, organizationalUnitIDData := range organizationalUnitIdsData { + secureOrganization.OrganizationalUnitIds = append( + secureOrganization.OrganizationalUnitIds, + organizationalUnitIDData.(string), ) } - includedOrganizationalGroups := data.Get(SchemaIncludedOrganizationalGroups).([]interface{}) + includedOrganizationalGroups := data.Get(SchemaIncludedOrganizationalGroups).([]any) for _, includedOrganizationalGroup := range includedOrganizationalGroups { - secureOrganization.CloudOrganization.IncludedOrganizationalGroups = append( - secureOrganization.CloudOrganization.IncludedOrganizationalGroups, + secureOrganization.IncludedOrganizationalGroups = append( + secureOrganization.IncludedOrganizationalGroups, includedOrganizationalGroup.(string), ) } - excludedOrganizationalGroups := data.Get(SchemaExcludedOrganizationalGroups).([]interface{}) + excludedOrganizationalGroups := data.Get(SchemaExcludedOrganizationalGroups).([]any) for _, excludedOrganizationalGroup := range excludedOrganizationalGroups { - secureOrganization.CloudOrganization.ExcludedOrganizationalGroups = append( - secureOrganization.CloudOrganization.ExcludedOrganizationalGroups, + secureOrganization.ExcludedOrganizationalGroups = append( + secureOrganization.ExcludedOrganizationalGroups, excludedOrganizationalGroup.(string), ) } - includedCloudAccounts := data.Get(SchemaIncludedCloudAccounts).([]interface{}) + includedCloudAccounts := data.Get(SchemaIncludedCloudAccounts).([]any) for _, includedCloudAccount := range includedCloudAccounts { - secureOrganization.CloudOrganization.IncludedCloudAccounts = append( - secureOrganization.CloudOrganization.IncludedCloudAccounts, + secureOrganization.IncludedCloudAccounts = append( + secureOrganization.IncludedCloudAccounts, includedCloudAccount.(string), ) } - excludedCloudAccounts := data.Get(SchemaExcludedCloudAccounts).([]interface{}) + excludedCloudAccounts := data.Get(SchemaExcludedCloudAccounts).([]any) for _, excludedCloudAccount := range excludedCloudAccounts { - secureOrganization.CloudOrganization.ExcludedCloudAccounts = append( - secureOrganization.CloudOrganization.ExcludedCloudAccounts, + secureOrganization.ExcludedCloudAccounts = append( + secureOrganization.ExcludedCloudAccounts, excludedCloudAccount.(string), ) } @@ -215,7 +215,7 @@ func secureOrganizationFromResourceData(data *schema.ResourceData) *v2.Organizat } func secureOrganizationToResourceData(data *schema.ResourceData, org *v2.OrganizationSecure) error { - err := data.Set(SchemaManagementAccountId, org.ManagementAccountId) + err := data.Set(SchemaManagementAccountID, org.ManagementAccountId) if err != nil { return err } diff --git a/sysdig/resource_sysdig_secure_organization_test.go b/sysdig/resource_sysdig_secure_organization_test.go index 597a45891..f436c8e17 100644 --- a/sysdig/resource_sysdig_secure_organization_test.go +++ b/sysdig/resource_sysdig_secure_organization_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common - package sysdig_test import ( @@ -128,8 +126,7 @@ resource "sysdig_secure_organization" "sample-org" { } func getEncodedGCPServiceAccountKeyForOrg(resourceName string, accountID string) string { - - test_service_account_key_bytes, err := json.Marshal(map[string]interface{}{ + test_service_account_key_bytes, err := json.Marshal(map[string]any{ "type": "service_account", "project_id": fmt.Sprintf("%s-%s", resourceName, accountID), "private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", diff --git a/sysdig/resource_sysdig_secure_policy.go b/sysdig/resource_sysdig_secure_policy.go index d7ff28743..7586d11a7 100644 --- a/sysdig/resource_sysdig_secure_policy.go +++ b/sysdig/resource_sysdig_secure_policy.go @@ -90,7 +90,7 @@ func getSecurePolicyClient(c SysdigClients) (v2.PolicyInterface, error) { return c.sysdigSecureClientV2() } -func resourceSysdigPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -121,10 +121,11 @@ func commonPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { _ = d.Set("version", policy.Version) _ = d.Set("runbook", policy.Runbook) - actions := []map[string]interface{}{{}} + actions := []map[string]any{{}} for _, action := range policy.Actions { - if action.Type == "POLICY_ACTION_CAPTURE" { - actions[0]["capture"] = []map[string]interface{}{{ + switch action.Type { + case "POLICY_ACTION_CAPTURE": + actions[0]["capture"] = []map[string]any{{ "seconds_after_event": action.AfterEventNs / 1000000000, "seconds_before_event": action.BeforeEventNs / 1000000000, "name": action.Name, @@ -133,16 +134,16 @@ func commonPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { "folder": action.Folder, }} - } else if action.Type == "POLICY_ACTION_KILL_PROCESS" { + case "POLICY_ACTION_KILL_PROCESS": actions[0]["kill_process"] = true - } else { + default: action := strings.Replace(action.Type, "POLICY_ACTION_", "", 1) actions[0]["container"] = strings.ToLower(action) } } currentContainerAction := d.Get("actions.0.container").(string) - currentCaptureAction := d.Get("actions.0.capture").([]interface{}) + currentCaptureAction := d.Get("actions.0.capture").([]any) // If the policy retrieved from service has no actions and the current state is default values, // then do not set the "actions" key as it may cause terraform to think there has been a state change if len(policy.Actions) > 0 || currentContainerAction != "" || len(currentCaptureAction) > 0 { @@ -175,8 +176,8 @@ func commonPolicyFromResourceData(policy *v2.Policy, d *schema.ResourceData) { addActionsToPolicy(d, policy) policy.NotificationChannelIds = []int{} - notificationChannelIdSet := d.Get("notification_channels").(*schema.Set) - for _, id := range notificationChannelIdSet.List() { + notificationChannelIDSet := d.Get("notification_channels").(*schema.Set) + for _, id := range notificationChannelIDSet.List() { policy.NotificationChannelIds = append(policy.NotificationChannelIds, id.(int)) } } @@ -190,11 +191,11 @@ func policyFromResourceData(d *schema.ResourceData) v2.Policy { policy.Type = d.Get("type").(string) policy.RuleNames = []string{} - rule_names := d.Get("rule_names").(*schema.Set) - for _, name := range rule_names.List() { - if rule_name, ok := name.(string); ok { - rule_name = strings.TrimSpace(rule_name) - policy.RuleNames = append(policy.RuleNames, rule_name) + ruleNames := d.Get("rule_names").(*schema.Set) + for _, name := range ruleNames.List() { + if ruleName, ok := name.(string); ok { + ruleName = strings.TrimSpace(ruleName) + policy.RuleNames = append(policy.RuleNames, ruleName) } } @@ -203,7 +204,7 @@ func policyFromResourceData(d *schema.ResourceData) v2.Policy { func addActionsToPolicy(d *schema.ResourceData, policy *v2.Policy) { policy.Actions = []v2.Action{} - actions := d.Get("actions").([]interface{}) + actions := d.Get("actions").([]any) if len(actions) == 0 { return } @@ -230,7 +231,7 @@ func addActionsToPolicy(d *schema.ResourceData, policy *v2.Policy) { policy.Actions = append(policy.Actions, v2.Action{Type: containerAction}) } - if captureAction := d.Get("actions.0.capture").([]interface{}); len(captureAction) > 0 { + if captureAction := d.Get("actions.0.capture").([]any); len(captureAction) > 0 { afterEventNs := d.Get("actions.0.capture.0.seconds_after_event").(int) * 1000000000 beforeEventNs := d.Get("actions.0.capture.0.seconds_before_event").(int) * 1000000000 name := d.Get("actions.0.capture.0.name").(string) @@ -251,7 +252,7 @@ func addActionsToPolicy(d *schema.ResourceData, policy *v2.Policy) { } } -func resourceSysdigPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecurePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -272,7 +273,7 @@ func resourceSysdigPolicyRead(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { @@ -290,7 +291,7 @@ func resourceSysdigPolicyDelete(ctx context.Context, d *schema.ResourceData, met return nil } -func resourceSysdigPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecurePolicyClient(sysdigClients) if err != nil { diff --git a/sysdig/resource_sysdig_secure_policy_test.go b/sysdig/resource_sysdig_secure_policy_test.go index a0682eb96..5a2d6e4a1 100644 --- a/sysdig/resource_sysdig_secure_policy_test.go +++ b/sysdig/resource_sysdig_secure_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_posture_control.go b/sysdig/resource_sysdig_secure_posture_control.go index a43046958..4a0fc6e0b 100644 --- a/sysdig/resource_sysdig_secure_posture_control.go +++ b/sysdig/resource_sysdig_secure_posture_control.go @@ -59,7 +59,7 @@ func resourceSysdigSecurePostureControl() *schema.Resource { } } -func resourceSysdigSecurePostureControlCreateOrUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePostureControlCreateOrUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Extract 'group' field from Terraform configuration client, err := getPostureControlClient(meta.(SysdigClients)) if err != nil { @@ -86,7 +86,7 @@ func resourceSysdigSecurePostureControlCreateOrUpdate(ctx context.Context, d *sc return nil } -func resourceSysdigSecurePostureContorlRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePostureContorlRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureControlClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -97,7 +97,7 @@ func resourceSysdigSecurePostureContorlRead(ctx context.Context, d *schema.Resou return diag.FromErr(err) } - control, err := client.GetPostureControl(ctx, id) + control, err := client.GetPostureControlByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -139,7 +139,7 @@ func resourceSysdigSecurePostureContorlRead(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigSecurePostureControlDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePostureControlDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureControlClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -150,7 +150,7 @@ func resourceSysdigSecurePostureControlDelete(ctx context.Context, d *schema.Res return diag.FromErr(err) } - err = client.DeletePostureControl(ctx, id) + err = client.DeletePostureControlByID(ctx, id) if err != nil { return diag.FromErr(err) } diff --git a/sysdig/resource_sysdig_secure_posture_control_test.go b/sysdig/resource_sysdig_secure_posture_control_test.go index a34153653..b52cdf4d6 100644 --- a/sysdig/resource_sysdig_secure_posture_control_test.go +++ b/sysdig/resource_sysdig_secure_posture_control_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_posture_policy.go b/sysdig/resource_sysdig_secure_posture_policy.go index aa5a326a0..487e282cc 100644 --- a/sysdig/resource_sysdig_secure_posture_policy.go +++ b/sysdig/resource_sysdig_secure_posture_policy.go @@ -209,7 +209,7 @@ func resourceSysdigSecurePosturePolicy() *schema.Resource { } } -func resourceSysdigSecurePosturePolicyCreateOrUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePosturePolicyCreateOrUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Extract 'group' field from Terraform configuration client, err := getPosturePolicyClient(meta.(SysdigClients)) if err != nil { @@ -232,7 +232,6 @@ func resourceSysdigSecurePosturePolicyCreateOrUpdate(ctx context.Context, d *sch } new, errStatus, err := client.CreateOrUpdatePosturePolicy(ctx, req) - if err != nil { return diag.Errorf("Error creating new policy with groups. error status: %s err: %s", errStatus, err) } @@ -242,7 +241,7 @@ func resourceSysdigSecurePosturePolicyCreateOrUpdate(ctx context.Context, d *sch return nil } -func resourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPosturePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -253,7 +252,7 @@ func resourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - policy, err := client.GetPosturePolicy(ctx, id) + policy, err := client.GetPosturePolicyByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -303,7 +302,6 @@ func resourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.Resour } err = setVersionConstraints(d, SchemaTargetKey, policy.VersionConstraints) - if err != nil { return diag.FromErr(err) } @@ -321,7 +319,7 @@ func resourceSysdigSecurePosturePolicyRead(ctx context.Context, d *schema.Resour return nil } -func resourceSysdigSecurePosturePolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePosturePolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPosturePolicyClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -340,10 +338,10 @@ func resourceSysdigSecurePosturePolicyDelete(ctx context.Context, d *schema.Reso return nil } -func setGroups(d *schema.ResourceData, groups []v2.RequirementsGroup) ([]interface{}, error) { - var groupsData []interface{} +func setGroups(d *schema.ResourceData, groups []v2.RequirementsGroup) ([]any, error) { + var groupsData []any for _, group := range groups { - groupData := map[string]interface{}{ + groupData := map[string]any{ "id": group.ID, "name": group.Name, "description": group.Description, @@ -366,10 +364,10 @@ func setGroups(d *schema.ResourceData, groups []v2.RequirementsGroup) ([]interfa return groupsData, nil } -func setRequirements(requirements []v2.Requirement) []interface{} { - var requirementsData []interface{} +func setRequirements(requirements []v2.Requirement) []any { + var requirementsData []any for _, req := range requirements { - reqData := map[string]interface{}{ + reqData := map[string]any{ "id": req.ID, "name": req.Name, "description": req.Description, @@ -386,10 +384,10 @@ func setRequirements(requirements []v2.Requirement) []interface{} { return requirementsData } -func setControls(controls []v2.Control) []interface{} { - var controlsData []interface{} +func setControls(controls []v2.Control) []any { + var controlsData []any for _, ctrl := range controls { - ctrlData := map[string]interface{}{ + ctrlData := map[string]any{ "name": ctrl.Name, "enabled": ctrl.Status, } @@ -409,12 +407,12 @@ func getStringValue(d *schema.ResourceData, key string) string { // Helper function to retrieve version constraints value from ResourceData and handle nil case func getVersionConstraintsValue(d *schema.ResourceData, key string) []v2.VersionConstraint { pvc := []v2.VersionConstraint{} - versionContraintsMap, ok := d.Get(key).([]interface{}) + versionContraintsMap, ok := d.Get(key).([]any) if !ok { return nil } for _, vc := range versionContraintsMap { - vcMap := vc.(map[string]interface{}) + vcMap := vc.(map[string]any) minVersion := 0.0 maxVersion := 0.0 if vcMap["min_version"] != nil { @@ -449,15 +447,15 @@ func getBoolValue(d *schema.ResourceData, key string) bool { return false } -func extractGroupsRecursive(data interface{}) []v2.CreateRequirementsGroup { +func extractGroupsRecursive(data any) []v2.CreateRequirementsGroup { var groups []v2.CreateRequirementsGroup switch d := data.(type) { - case []interface{}: + case []any: for _, item := range d { groups = append(groups, extractGroupsRecursive(item)...) } - case map[string]interface{}: + case map[string]any: group := v2.CreateRequirementsGroup{ ID: d["id"].(string), Name: d["name"].(string), @@ -466,7 +464,7 @@ func extractGroupsRecursive(data interface{}) []v2.CreateRequirementsGroup { if reqs, ok := d["requirement"].(*schema.Set); ok { for _, reqData := range reqs.List() { - reqMap := reqData.(map[string]interface{}) + reqMap := reqData.(map[string]any) requirement := v2.CreateRequirement{ ID: reqMap["id"].(string), Name: reqMap["name"].(string), @@ -475,7 +473,7 @@ func extractGroupsRecursive(data interface{}) []v2.CreateRequirementsGroup { if controlsData, ok := reqMap["control"].(*schema.Set); ok { for _, controlData := range controlsData.List() { - controlMap := controlData.(map[string]interface{}) + controlMap := controlData.(map[string]any) control := v2.CreateRequirementControl{ Name: controlMap["name"].(string), Enabled: controlMap["enabled"].(bool), @@ -500,9 +498,9 @@ func extractGroupsRecursive(data interface{}) []v2.CreateRequirementsGroup { // Helper function to set version constraints in the Terraform schema func setVersionConstraints(d *schema.ResourceData, key string, constraints []v2.VersionConstraint) error { - var constraintsData []interface{} + var constraintsData []any for _, vc := range constraints { - constraint := map[string]interface{}{ + constraint := map[string]any{ "min_version": vc.MinVersion, "max_version": vc.MaxVersion, "platform": vc.Platform, diff --git a/sysdig/resource_sysdig_secure_posture_policy_test.go b/sysdig/resource_sysdig_secure_posture_policy_test.go index 96ef1bc3a..a559da944 100644 --- a/sysdig/resource_sysdig_secure_posture_policy_test.go +++ b/sysdig/resource_sysdig_secure_posture_policy_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure - package sysdig_test import ( @@ -29,6 +27,7 @@ func TestSecurePosturePolicy(t *testing.T) { }, }) } + func createPolicyResource(name string) string { return fmt.Sprintf(`resource "sysdig_secure_posture_policy" "sample" { name = "policy-test-%s" diff --git a/sysdig/resource_sysdig_secure_posture_zone.go b/sysdig/resource_sysdig_secure_posture_zone.go index dd4f3d6b0..450361085 100644 --- a/sysdig/resource_sysdig_secure_posture_zone.go +++ b/sysdig/resource_sysdig_secure_posture_zone.go @@ -105,7 +105,7 @@ func getPostureZoneClient(c SysdigClients) (v2.PostureZoneInterface, error) { return client, nil } -func resourceCreateOrUpdatePostureZone(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceCreateOrUpdatePostureZone(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { policiesData := d.Get(SchemaPolicyIDsKey).(*schema.Set).List() policies := make([]string, len(policiesData)) for i, p := range policiesData { @@ -115,9 +115,9 @@ func resourceCreateOrUpdatePostureZone(ctx context.Context, d *schema.ResourceDa scopesList := d.Get(SchemaScopesKey).(*schema.Set).List() scopes := make([]v2.PostureZoneScope, 0) if len(scopesList) > 0 { - scopeList := scopesList[0].(map[string]interface{})[SchemaScopeKey].(*schema.Set).List() + scopeList := scopesList[0].(map[string]any)[SchemaScopeKey].(*schema.Set).List() for _, attr := range scopeList { - s := attr.(map[string]interface{}) + s := attr.(map[string]any) scopes = append(scopes, v2.PostureZoneScope{ TargetType: s[SchemaTargetTypeKey].(string), Rules: s[SchemaRulesKey].(string), @@ -149,7 +149,7 @@ func resourceCreateOrUpdatePostureZone(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureZoneClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -160,7 +160,7 @@ func resourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.Resource return diag.FromErr(err) } - zone, err := client.GetPostureZone(ctx, id) + zone, err := client.GetPostureZoneByID(ctx, id) if err != nil { return diag.FromErr(err) } @@ -203,16 +203,16 @@ func resourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.Resource return diag.FromErr(err) } - scopes := make([]map[string]interface{}, len(zone.Scopes)) + scopes := make([]map[string]any, len(zone.Scopes)) for i, s := range zone.Scopes { - scopes[i] = map[string]interface{}{ + scopes[i] = map[string]any{ SchemaTargetTypeKey: s.TargetType, SchemaRulesKey: s.Rules, } } if len(scopes) > 0 { - err = d.Set(SchemaScopesKey, []interface{}{ - map[string]interface{}{ + err = d.Set(SchemaScopesKey, []any{ + map[string]any{ SchemaScopeKey: scopes, }, }) @@ -224,7 +224,7 @@ func resourceSysdigSecurePostureZoneRead(ctx context.Context, d *schema.Resource return nil } -func resourceSysdigSecurePostureZoneDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecurePostureZoneDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getPostureZoneClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_secure_posture_zone_test.go b/sysdig/resource_sysdig_secure_posture_zone_test.go index f504da9d8..6268b817c 100644 --- a/sysdig/resource_sysdig_secure_posture_zone_test.go +++ b/sysdig/resource_sysdig_secure_posture_zone_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_ibm_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_rule.go b/sysdig/resource_sysdig_secure_rule.go index bc51c04e5..4e06ddf20 100644 --- a/sysdig/resource_sysdig_secure_rule.go +++ b/sysdig/resource_sysdig_secure_rule.go @@ -72,7 +72,7 @@ func updateResourceDataForRule(d *schema.ResourceData, rule v2.Rule) { func getTagsFromResourceData(d *schema.ResourceData) []string { result := []string{} - if tags, ok := d.Get("tags").([]interface{}); ok { + if tags, ok := d.Get("tags").([]any); ok { for _, rawTag := range tags { if tag, ok := rawTag.(string); ok { result = append(result, tag) diff --git a/sysdig/resource_sysdig_secure_rule_container.go b/sysdig/resource_sysdig_secure_rule_container.go index 693220196..b5c33ed56 100644 --- a/sysdig/resource_sysdig_secure_rule_container.go +++ b/sysdig/resource_sysdig_secure_rule_container.go @@ -49,7 +49,7 @@ func resourceSysdigSecureRuleContainer() *schema.Resource { } } -func resourceSysdigRuleContainerCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleContainerCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -71,7 +71,7 @@ func resourceSysdigRuleContainerCreate(ctx context.Context, d *schema.ResourceDa } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -83,7 +83,6 @@ func resourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData } rule, statusCode, err := client.GetRuleByID(ctx, id) - if err != nil { if statusCode == http.StatusNotFound { d.SetId("") @@ -103,7 +102,7 @@ func resourceSysdigRuleContainerRead(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigRuleContainerUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleContainerUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -124,7 +123,7 @@ func resourceSysdigRuleContainerUpdate(ctx context.Context, d *schema.ResourceDa return nil } -func resourceSysdigRuleContainerDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleContainerDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -152,7 +151,7 @@ func resourceSysdigRuleContainerFromResourceData(d *schema.ResourceData) v2.Rule rule.Details.Containers = &v2.Containers{} rule.Details.Containers.MatchItems = d.Get("matching").(bool) rule.Details.Containers.Items = []string{} - if containers, ok := d.Get("containers").([]interface{}); ok { + if containers, ok := d.Get("containers").([]any); ok { for _, rawContainer := range containers { if container, ok := rawContainer.(string); ok { rule.Details.Containers.Items = append(rule.Details.Containers.Items, container) diff --git a/sysdig/resource_sysdig_secure_rule_container_test.go b/sysdig/resource_sysdig_secure_rule_container_test.go index bddc9030a..577f1c618 100644 --- a/sysdig/resource_sysdig_secure_rule_container_test.go +++ b/sysdig/resource_sysdig_secure_rule_container_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_rule_falco.go b/sysdig/resource_sysdig_secure_rule_falco.go index 197a9d3ef..ea6e7c63f 100644 --- a/sysdig/resource_sysdig_secure_rule_falco.go +++ b/sysdig/resource_sysdig_secure_rule_falco.go @@ -100,7 +100,7 @@ func resourceSysdigSecureRuleFalco() *schema.Resource { } } -func resourceSysdigRuleFalcoCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFalcoCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -125,7 +125,7 @@ func resourceSysdigRuleFalcoCreate(ctx context.Context, d *schema.ResourceData, } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleFalcoRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFalcoRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -204,7 +204,7 @@ func updateResourceDataExceptions(d *schema.ResourceData, ruleExceptions []*v2.E func fieldOrCompsToStringSlice(fields any) ([]string, error) { elements := []string{} switch t := fields.(type) { - case []interface{}: + case []any: for _, field := range t { elements = append(elements, field.(string)) } @@ -218,7 +218,7 @@ func fieldOrCompsToStringSlice(fields any) ([]string, error) { return elements, nil } -func resourceSysdigRuleFalcoUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFalcoUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -242,7 +242,7 @@ func resourceSysdigRuleFalcoUpdate(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigRuleFalcoDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFalcoDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -299,13 +299,13 @@ func resourceSysdigRuleFalcoFromResourceData(d *schema.ResourceData) (v2.Rule, e rule.Details.Condition = &v2.Condition{ Condition: d.Get("condition").(string), - Components: []interface{}{}, + Components: []any{}, } if exceptionsField, ok := d.GetOk("exceptions"); ok { falcoExceptions := []*v2.Exception{} - for _, exception := range exceptionsField.([]interface{}) { - exceptionMap := exception.(map[string]interface{}) + for _, exception := range exceptionsField.([]any) { + exceptionMap := exception.(map[string]any) newFalcoException := &v2.Exception{ Name: exceptionMap["name"].(string), } diff --git a/sysdig/resource_sysdig_secure_rule_falco_test.go b/sysdig/resource_sysdig_secure_rule_falco_test.go index 0779d7c84..54ed25cdc 100644 --- a/sysdig/resource_sysdig_secure_rule_falco_test.go +++ b/sysdig/resource_sysdig_secure_rule_falco_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( @@ -174,7 +172,6 @@ func TestRuleFalcoAzureAuditlog(t *testing.T) { } func TestRuleFalcoKubeAudit(t *testing.T) { - steps := []resource.TestStep{ { Config: ruleFalcoKubeAudit(randomString()), @@ -319,7 +316,6 @@ func runTest(steps []resource.TestStep, t *testing.T) { }, Steps: steps, }) - } func ruleFalcoTerminalShell(name string) string { diff --git a/sysdig/resource_sysdig_secure_rule_filesystem.go b/sysdig/resource_sysdig_secure_rule_filesystem.go index 9044b91bd..3d609b1ea 100644 --- a/sysdig/resource_sysdig_secure_rule_filesystem.go +++ b/sysdig/resource_sysdig_secure_rule_filesystem.go @@ -77,7 +77,7 @@ func resourceSysdigSecureRuleFilesystem() *schema.Resource { } } -func resourceSysdigRuleFilesystemCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFilesystemCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -102,7 +102,7 @@ func resourceSysdigRuleFilesystemCreate(ctx context.Context, d *schema.ResourceD } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -133,13 +133,13 @@ func resourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceDat } if len(rule.Details.ReadPaths.Items) > 0 { - _ = d.Set("read_only", []map[string]interface{}{{ + _ = d.Set("read_only", []map[string]any{{ "matching": rule.Details.ReadPaths.MatchItems, "paths": rule.Details.ReadPaths.Items, }}) } if len(rule.Details.ReadWritePaths.Items) > 0 { - _ = d.Set("read_write", []map[string]interface{}{{ + _ = d.Set("read_write", []map[string]any{{ "matching": rule.Details.ReadWritePaths.MatchItems, "paths": rule.Details.ReadWritePaths.Items, }}) @@ -148,7 +148,7 @@ func resourceSysdigRuleFilesystemRead(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigRuleFilesystemUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFilesystemUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -172,7 +172,7 @@ func resourceSysdigRuleFilesystemUpdate(ctx context.Context, d *schema.ResourceD return nil } -func resourceSysdigRuleFilesystemDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleFilesystemDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -206,9 +206,9 @@ func resourceSysdigRuleFilesystemFromResourceData(d *schema.ResourceData) (rule Items: []string{}, } - if readOnlyRules, ok := d.Get("read_only").([]interface{}); ok && len(readOnlyRules) > 0 { + if readOnlyRules, ok := d.Get("read_only").([]any); ok && len(readOnlyRules) > 0 { rule.Details.ReadPaths.MatchItems = d.Get("read_only.0.matching").(bool) - for _, path := range d.Get("read_only.0.paths").([]interface{}) { + for _, path := range d.Get("read_only.0.paths").([]any) { if pathStr, ok := path.(string); ok { rule.Details.ReadPaths.Items = append(rule.Details.ReadPaths.Items, pathStr) } @@ -216,9 +216,9 @@ func resourceSysdigRuleFilesystemFromResourceData(d *schema.ResourceData) (rule } - if readWriteRules, ok := d.Get("read_write").([]interface{}); ok && len(readWriteRules) > 0 { + if readWriteRules, ok := d.Get("read_write").([]any); ok && len(readWriteRules) > 0 { rule.Details.ReadWritePaths.MatchItems = d.Get("read_write.0.matching").(bool) - for _, path := range d.Get("read_write.0.paths").([]interface{}) { + for _, path := range d.Get("read_write.0.paths").([]any) { if pathStr, ok := path.(string); ok { rule.Details.ReadWritePaths.Items = append(rule.Details.ReadWritePaths.Items, pathStr) } diff --git a/sysdig/resource_sysdig_secure_rule_filesystem_test.go b/sysdig/resource_sysdig_secure_rule_filesystem_test.go index c00aecda3..026d22936 100644 --- a/sysdig/resource_sysdig_secure_rule_filesystem_test.go +++ b/sysdig/resource_sysdig_secure_rule_filesystem_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_rule_network.go b/sysdig/resource_sysdig_secure_rule_network.go index 8987637d4..60c9f4223 100644 --- a/sysdig/resource_sysdig_secure_rule_network.go +++ b/sysdig/resource_sysdig_secure_rule_network.go @@ -85,7 +85,7 @@ func resourceSysdigSecureRuleNetwork() *schema.Resource { } } -func resourceSysdigRuleNetworkCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleNetworkCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -110,7 +110,7 @@ func resourceSysdigRuleNetworkCreate(ctx context.Context, d *schema.ResourceData } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -122,7 +122,6 @@ func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, } rule, statusCode, err := client.GetRuleByID(ctx, id) - if err != nil { if statusCode == http.StatusNotFound { d.SetId("") @@ -152,7 +151,7 @@ func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, } tcpPorts = append(tcpPorts, intPort) } - _ = d.Set("tcp", []map[string]interface{}{{ + _ = d.Set("tcp", []map[string]any{{ "matching": rule.Details.TCPListenPorts.MatchItems, "ports": tcpPorts, }}) @@ -166,7 +165,7 @@ func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, } udpPorts = append(udpPorts, intPort) } - _ = d.Set("udp", []map[string]interface{}{{ + _ = d.Set("udp", []map[string]any{{ "matching": rule.Details.UDPListenPorts.MatchItems, "ports": udpPorts, }}) @@ -175,7 +174,7 @@ func resourceSysdigRuleNetworkRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigRuleNetworkUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleNetworkUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -199,7 +198,7 @@ func resourceSysdigRuleNetworkUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigRuleNetworkDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleNetworkDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -231,7 +230,7 @@ func resourceSysdigRuleNetworkFromResourceData(d *schema.ResourceData) (rule v2. rule.Details.AllOutbound = !d.Get("block_outbound").(bool) rule.Details.TCPListenPorts.Items = []string{} - if tcpRules := d.Get("tcp").([]interface{}); len(tcpRules) > 0 { + if tcpRules := d.Get("tcp").([]any); len(tcpRules) > 0 { rule.Details.TCPListenPorts.MatchItems = d.Get("tcp.0.matching").(bool) for _, port := range d.Get("tcp.0.ports").(*schema.Set).List() { portStr := port.(int) @@ -240,7 +239,7 @@ func resourceSysdigRuleNetworkFromResourceData(d *schema.ResourceData) (rule v2. } rule.Details.UDPListenPorts.Items = []string{} - if udpRules, ok := d.Get("udp").([]interface{}); ok && len(udpRules) > 0 { + if udpRules, ok := d.Get("udp").([]any); ok && len(udpRules) > 0 { rule.Details.UDPListenPorts.MatchItems = d.Get("udp.0.matching").(bool) for _, port := range d.Get("udp.0.ports").(*schema.Set).List() { portStr := port.(int) diff --git a/sysdig/resource_sysdig_secure_rule_network_test.go b/sysdig/resource_sysdig_secure_rule_network_test.go index 40d14af71..fbb54d94c 100644 --- a/sysdig/resource_sysdig_secure_rule_network_test.go +++ b/sysdig/resource_sysdig_secure_rule_network_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_rule_process.go b/sysdig/resource_sysdig_secure_rule_process.go index 2573ea59d..80c327bd3 100644 --- a/sysdig/resource_sysdig_secure_rule_process.go +++ b/sysdig/resource_sysdig_secure_rule_process.go @@ -49,7 +49,7 @@ func resourceSysdigSecureRuleProcess() *schema.Resource { } } -func resourceSysdigRuleProcessCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleProcessCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -71,7 +71,7 @@ func resourceSysdigRuleProcessCreate(ctx context.Context, d *schema.ResourceData } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -83,7 +83,6 @@ func resourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, } rule, statusCode, err := client.GetRuleByID(ctx, id) - if err != nil { if statusCode == http.StatusNotFound { d.SetId("") @@ -103,7 +102,7 @@ func resourceSysdigRuleProcessRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigRuleProcessUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleProcessUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -124,7 +123,7 @@ func resourceSysdigRuleProcessUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigRuleProcessDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleProcessDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -152,7 +151,7 @@ func resourceSysdigRuleProcessFromResourceData(d *schema.ResourceData) v2.Rule { rule.Details.Processes = &v2.Processes{} rule.Details.Processes.MatchItems = d.Get("matching").(bool) rule.Details.Processes.Items = []string{} - if processes, ok := d.Get("processes").([]interface{}); ok { + if processes, ok := d.Get("processes").([]any); ok { for _, rawProcess := range processes { if process, ok := rawProcess.(string); ok { rule.Details.Processes.Items = append(rule.Details.Processes.Items, process) diff --git a/sysdig/resource_sysdig_secure_rule_process_test.go b/sysdig/resource_sysdig_secure_rule_process_test.go index 8e595386b..74bd0404a 100644 --- a/sysdig/resource_sysdig_secure_rule_process_test.go +++ b/sysdig/resource_sysdig_secure_rule_process_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_rule_stateful.go b/sysdig/resource_sysdig_secure_rule_stateful.go index 522fd363a..b1265c480 100644 --- a/sysdig/resource_sysdig_secure_rule_stateful.go +++ b/sysdig/resource_sysdig_secure_rule_stateful.go @@ -87,7 +87,7 @@ func resourceSysdigSecureStatefulRule() *schema.Resource { } } -func resourceSysdigRuleStatefulCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleStatefulCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -110,7 +110,7 @@ func resourceSysdigRuleStatefulCreate(ctx context.Context, d *schema.ResourceDat } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleStatefulRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleStatefulRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -183,7 +183,7 @@ func resourceSysdigRuleStatefulRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigRuleStatefulUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleStatefulUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -215,7 +215,7 @@ func resourceSysdigRuleStatefulUpdate(ctx context.Context, d *schema.ResourceDat return nil } -func resourceSysdigRuleStatefulDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleStatefulDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -257,8 +257,8 @@ func resourceSysdigRuleStatefulFromResourceData(d *schema.ResourceData) (v2.Rule if exceptionsField, ok := d.GetOk("exceptions"); ok { StatefulExceptions := []*v2.Exception{} - for _, exception := range exceptionsField.([]interface{}) { - exceptionMap := exception.(map[string]interface{}) + for _, exception := range exceptionsField.([]any) { + exceptionMap := exception.(map[string]any) newStatefulException := &v2.Exception{ Name: exceptionMap["name"].(string), } diff --git a/sysdig/resource_sysdig_secure_rule_stateful_test.go b/sysdig/resource_sysdig_secure_rule_stateful_test.go index c8ba776a5..296980304 100644 --- a/sysdig/resource_sysdig_secure_rule_stateful_test.go +++ b/sysdig/resource_sysdig_secure_rule_stateful_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( @@ -53,5 +51,4 @@ func runStatefulTest(steps []resource.TestStep, t *testing.T) { }, Steps: steps, }) - } diff --git a/sysdig/resource_sysdig_secure_rule_syscall.go b/sysdig/resource_sysdig_secure_rule_syscall.go index ad7facf87..94a71831d 100644 --- a/sysdig/resource_sysdig_secure_rule_syscall.go +++ b/sysdig/resource_sysdig_secure_rule_syscall.go @@ -48,7 +48,7 @@ func resourceSysdigSecureRuleSyscall() *schema.Resource { } } -func resourceSysdigRuleSyscallCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleSyscallCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -70,7 +70,7 @@ func resourceSysdigRuleSyscallCreate(ctx context.Context, d *schema.ResourceData } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureRuleClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -82,7 +82,6 @@ func resourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, } rule, statusCode, err := client.GetRuleByID(ctx, id) - if err != nil { if statusCode == http.StatusNotFound { d.SetId("") @@ -102,7 +101,7 @@ func resourceSysdigRuleSyscallRead(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigRuleSyscallUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleSyscallUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -123,7 +122,7 @@ func resourceSysdigRuleSyscallUpdate(ctx context.Context, d *schema.ResourceData return nil } -func resourceSysdigRuleSyscallDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigRuleSyscallDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { sysdigClients := meta.(SysdigClients) client, err := getSecureRuleClient(sysdigClients) if err != nil { @@ -151,7 +150,7 @@ func resourceSysdigRuleSyscallFromResourceData(d *schema.ResourceData) v2.Rule { rule.Details.Syscalls = &v2.Syscalls{} rule.Details.Syscalls.MatchItems = d.Get("matching").(bool) rule.Details.Syscalls.Items = []string{} - if syscalls, ok := d.Get("syscalls").([]interface{}); ok { + if syscalls, ok := d.Get("syscalls").([]any); ok { for _, rawSyscall := range syscalls { if syscall, ok := rawSyscall.(string); ok { rule.Details.Syscalls.Items = append(rule.Details.Syscalls.Items, syscall) diff --git a/sysdig/resource_sysdig_secure_rule_syscall_test.go b/sysdig/resource_sysdig_secure_rule_syscall_test.go index 67cd31643..ac9a292f2 100644 --- a/sysdig/resource_sysdig_secure_rule_syscall_test.go +++ b/sysdig/resource_sysdig_secure_rule_syscall_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_team.go b/sysdig/resource_sysdig_secure_team.go index 560605638..3580d6837 100644 --- a/sysdig/resource_sysdig_secure_team.go +++ b/sysdig/resource_sysdig_secure_team.go @@ -24,7 +24,7 @@ func resourceSysdigSecureTeam() *schema.Resource { Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, - CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error { + CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i any) error { plan := diff.GetRawPlan().AsValueMap() zoneIDsPlan := plan[SchemaZonesIDsKey] allZonesPlan := plan[SchemaAllZones] @@ -157,14 +157,14 @@ func getSecureTeamClient(c SysdigClients) (v2.TeamInterface, error) { return client, nil } -func resourceSysdigSecureTeamCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureTeamCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureTeamClient(clients) if err != nil { return diag.FromErr(err) } - team := secureTeamFromResourceData(d, clients.GetClientType()) + team := secureTeamFromResourceData(d) team.Products = []string{"SDS"} team, err = client.CreateTeam(ctx, team) @@ -180,7 +180,7 @@ func resourceSysdigSecureTeamCreate(ctx context.Context, d *schema.ResourceData, } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureTeamClient(clients) if err != nil { @@ -188,7 +188,7 @@ func resourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, m } id, _ := strconv.Atoi(d.Id()) - t, err := client.GetTeamById(ctx, id) + t, err := client.GetTeamByID(ctx, id) if err != nil { d.SetId("") return diag.FromErr(err) @@ -226,12 +226,12 @@ func resourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, m return nil } -func userSecureRolesToSet(userRoles []v2.UserRoles) (res []map[string]interface{}) { +func userSecureRolesToSet(userRoles []v2.UserRoles) (res []map[string]any) { for _, role := range userRoles { if role.Admin { continue // Admins are added by default, so skip them } - roleMap := map[string]interface{}{ + roleMap := map[string]any{ "email": role.Email, "role": role.Role, } @@ -240,14 +240,14 @@ func userSecureRolesToSet(userRoles []v2.UserRoles) (res []map[string]interface{ return } -func resourceSysdigSecureTeamUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureTeamUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { clients := meta.(SysdigClients) client, err := getSecureTeamClient(clients) if err != nil { return diag.FromErr(err) } - t := secureTeamFromResourceData(d, clients.GetClientType()) + t := secureTeamFromResourceData(d) t.Products = []string{"SDS"} t.Version = d.Get("version").(int) @@ -262,7 +262,7 @@ func resourceSysdigSecureTeamUpdate(ctx context.Context, d *schema.ResourceData, return nil } -func resourceSysdigSecureTeamDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigSecureTeamDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := getSecureTeamClient(meta.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -277,7 +277,7 @@ func resourceSysdigSecureTeamDelete(ctx context.Context, d *schema.ResourceData, return nil } -func secureTeamFromResourceData(d *schema.ResourceData, clientType ClientType) v2.Team { +func secureTeamFromResourceData(d *schema.ResourceData) v2.Team { canUseSysdigCapture := d.Get("use_sysdig_capture").(bool) canUseAgentCli := d.Get("can_use_agent_cli").(bool) canUseRapidResponse := d.Get("can_use_rapid_response").(bool) @@ -299,7 +299,7 @@ func secureTeamFromResourceData(d *schema.ResourceData, clientType ClientType) v userRoles := make([]v2.UserRoles, 0) for _, userRole := range d.Get("user_roles").(*schema.Set).List() { - ur := userRole.(map[string]interface{}) + ur := userRole.(map[string]any) userRoles = append(userRoles, v2.UserRoles{ Email: ur["email"].(string), Role: ur["role"].(string), @@ -307,7 +307,7 @@ func secureTeamFromResourceData(d *schema.ResourceData, clientType ClientType) v } t.UserRoles = userRoles - zonesData := d.Get("zone_ids").([]interface{}) + zonesData := d.Get("zone_ids").([]any) t.ZoneIDs = make([]int, len(zonesData)) for i, z := range zonesData { t.ZoneIDs[i] = z.(int) diff --git a/sysdig/resource_sysdig_secure_team_test.go b/sysdig/resource_sysdig_secure_team_test.go index 68b078b83..2d2d7cfdf 100644 --- a/sysdig/resource_sysdig_secure_team_test.go +++ b/sysdig/resource_sysdig_secure_team_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_sysdig_common || tf_acc_ibm_secure || tf_acc_ibm_common || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_secure_zone.go b/sysdig/resource_sysdig_secure_zone.go index 44e608a34..6cfa9806a 100644 --- a/sysdig/resource_sysdig_secure_zone.go +++ b/sysdig/resource_sysdig_secure_zone.go @@ -71,7 +71,7 @@ func resourceSysdigSecureZone() *schema.Resource { } } -func resourceSysdigSecureZoneCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigSecureZoneCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := getZoneClient(m.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -88,7 +88,7 @@ func resourceSysdigSecureZoneCreate(ctx context.Context, d *schema.ResourceData, return resourceSysdigSecureZoneRead(ctx, d, m) } -func resourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := getZoneClient(m.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -96,7 +96,7 @@ func resourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m id, _ := strconv.Atoi(d.Id()) - zone, err := client.GetZoneById(ctx, id) + zone, err := client.GetZoneByID(ctx, id) if err != nil { d.SetId("") return diag.FromErr(err) @@ -116,7 +116,7 @@ func resourceSysdigSecureZoneRead(ctx context.Context, d *schema.ResourceData, m return nil } -func resourceSysdigSecureZoneUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigSecureZoneUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := getZoneClient(m.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -132,7 +132,7 @@ func resourceSysdigSecureZoneUpdate(ctx context.Context, d *schema.ResourceData, return resourceSysdigSecureZoneRead(ctx, d, m) } -func resourceSysdigSecureZoneDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigSecureZoneDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := getZoneClient(m.(SysdigClients)) if err != nil { return diag.FromErr(err) @@ -168,7 +168,7 @@ func zoneRequestFromResourceData(d *schema.ResourceData) *v2.ZoneRequest { func toZoneScopesRequest(scopes *schema.Set) []v2.ZoneScope { var zoneScopes []v2.ZoneScope for _, attr := range scopes.List() { - s := attr.(map[string]interface{}) + s := attr.(map[string]any) zoneScopes = append(zoneScopes, v2.ZoneScope{ ID: s[SchemaIDKey].(int), TargetType: s[SchemaTargetTypeKey].(string), @@ -178,10 +178,10 @@ func toZoneScopesRequest(scopes *schema.Set) []v2.ZoneScope { return zoneScopes } -func fromZoneScopesResponse(scopes []v2.ZoneScope) []interface{} { - var flattenedScopes []interface{} +func fromZoneScopesResponse(scopes []v2.ZoneScope) []any { + var flattenedScopes []any for _, scope := range scopes { - flattenedScopes = append(flattenedScopes, map[string]interface{}{ + flattenedScopes = append(flattenedScopes, map[string]any{ SchemaIDKey: scope.ID, SchemaTargetTypeKey: scope.TargetType, SchemaRulesKey: scope.Rules, diff --git a/sysdig/resource_sysdig_secure_zone_test.go b/sysdig/resource_sysdig_secure_zone_test.go index 0dfb1016c..64d9f3f58 100644 --- a/sysdig/resource_sysdig_secure_zone_test.go +++ b/sysdig/resource_sysdig_secure_zone_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_secure || tf_acc_onprem_secure || tf_acc_ibm_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_team_service_account.go b/sysdig/resource_sysdig_team_service_account.go index 4e27af6ba..dcae0839a 100644 --- a/sysdig/resource_sysdig_team_service_account.go +++ b/sysdig/resource_sysdig_team_service_account.go @@ -57,7 +57,7 @@ func resourceSysdigTeamServiceAccount() *schema.Resource { Type: schema.TypeInt, Computed: true, }, - SchemaApiKeyKey: { + SchemaAPIKeyKey: { Type: schema.TypeString, Computed: true, Sensitive: true, @@ -66,7 +66,7 @@ func resourceSysdigTeamServiceAccount() *schema.Resource { } } -func resourceSysdigTeamServiceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigTeamServiceAccountRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { diag.FromErr(err) @@ -79,7 +79,7 @@ func resourceSysdigTeamServiceAccountRead(ctx context.Context, d *schema.Resourc teamServiceAccount, err := client.GetTeamServiceAccountByID(ctx, id) if err != nil { - if err == v2.TeamServiceAccountNotFound { + if err == v2.ErrTeamServiceAccountNotFound { d.SetId("") return nil } @@ -94,7 +94,7 @@ func resourceSysdigTeamServiceAccountRead(ctx context.Context, d *schema.Resourc return nil } -func resourceSysdigTeamServiceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigTeamServiceAccountCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -109,7 +109,7 @@ func resourceSysdigTeamServiceAccountCreate(ctx context.Context, d *schema.Resou } d.SetId(strconv.Itoa(teamServiceAccount.ID)) - err = d.Set(SchemaApiKeyKey, teamServiceAccount.ApiKey) + err = d.Set(SchemaAPIKeyKey, teamServiceAccount.APIKey) if err != nil { return diag.FromErr(err) } @@ -119,7 +119,7 @@ func resourceSysdigTeamServiceAccountCreate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigTeamServiceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigTeamServiceAccountUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { var err error client, err := m.(SysdigClients).sysdigCommonClientV2() @@ -144,7 +144,7 @@ func resourceSysdigTeamServiceAccountUpdate(ctx context.Context, d *schema.Resou return nil } -func resourceSysdigTeamServiceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { +func resourceSysdigTeamServiceAccountDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics { client, err := m.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -167,9 +167,9 @@ func teamServiceAccountFromResourceData(d *schema.ResourceData) *v2.TeamServiceA Name: d.Get(SchemaNameKey).(string), TeamRole: d.Get(SchemaRoleKey).(string), ExpirationDate: int64(d.Get(SchemaExpirationDateKey).(int) * 1000), - TeamId: d.Get(SchemaTeamIDKey).(int), + TeamID: d.Get(SchemaTeamIDKey).(int), SystemRole: d.Get(SchemaSystemRoleKey).(string), - ApiKey: d.Get(SchemaApiKeyKey).(string), + APIKey: d.Get(SchemaAPIKeyKey).(string), } } @@ -186,7 +186,7 @@ func teamServiceAccountToResourceData(teamServiceAccount *v2.TeamServiceAccount, if err != nil { return err } - err = d.Set(SchemaTeamIDKey, teamServiceAccount.TeamId) + err = d.Set(SchemaTeamIDKey, teamServiceAccount.TeamID) if err != nil { return err } diff --git a/sysdig/resource_sysdig_team_service_account_test.go b/sysdig/resource_sysdig_team_service_account_test.go index 81d78c835..7b91bb4e2 100644 --- a/sysdig/resource_sysdig_team_service_account_test.go +++ b/sysdig/resource_sysdig_team_service_account_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/resource_sysdig_user.go b/sysdig/resource_sysdig_user.go index 3eadcf36c..768c5fdb8 100644 --- a/sysdig/resource_sysdig_user.go +++ b/sysdig/resource_sysdig_user.go @@ -53,7 +53,7 @@ func resourceSysdigUser() *schema.Resource { } } -func resourceSysdigUserCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigUserCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -73,14 +73,14 @@ func resourceSysdigUserCreate(ctx context.Context, d *schema.ResourceData, meta } // Retrieves the information of a resource form the file and loads it in Terraform -func resourceSysdigUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigUserRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) } id, _ := strconv.Atoi(d.Id()) - u, err := client.GetUserById(ctx, id) + u, err := client.GetUserByID(ctx, id) if err != nil { d.SetId("") return diag.FromErr(err) @@ -95,7 +95,7 @@ func resourceSysdigUserRead(ctx context.Context, d *schema.ResourceData, meta in return nil } -func resourceSysdigUserUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigUserUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) @@ -114,7 +114,7 @@ func resourceSysdigUserUpdate(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceSysdigUserDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceSysdigUserDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { client, err := meta.(SysdigClients).sysdigCommonClientV2() if err != nil { return diag.FromErr(err) diff --git a/sysdig/resource_sysdig_user_test.go b/sysdig/resource_sysdig_user_test.go index c73587319..c0e2c282c 100644 --- a/sysdig/resource_sysdig_user_test.go +++ b/sysdig/resource_sysdig_user_test.go @@ -1,5 +1,3 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_sysdig_secure || tf_acc_onprem_monitor || tf_acc_onprem_secure - package sysdig_test import ( diff --git a/sysdig/schema.go b/sysdig/schema.go index 51bf024f0..de31a66dc 100644 --- a/sysdig/schema.go +++ b/sysdig/schema.go @@ -1,6 +1,7 @@ package sysdig import ( + "maps" // "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -40,7 +41,7 @@ func BoolComputedSchema() *schema.Schema { } } -// Can be omitted for composite policies +// RuleNamesSchema can be omitted for composite policies func RuleNamesSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeSet, @@ -51,7 +52,7 @@ func RuleNamesSchema() *schema.Schema { } } -// Can be omitted for Composite policies +// RulesSchema can be omitted for Composite policies func RulesSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, @@ -325,8 +326,8 @@ func HashesComputedSchema() *schema.Schema { } } -// Tags are always set automatically by Sysdig func TagsSchema() *schema.Schema { + // Tags are always set automatically by Sysdig return &schema.Schema{ Type: schema.TypeSet, Computed: true, @@ -464,9 +465,7 @@ func createPolicySchema(original map[string]*schema.Schema) map[string]*schema.S }, } - for k, v := range original { - policySchema[k] = v - } + maps.Copy(policySchema, original) return policySchema } diff --git a/sysdig/sysdig_clients.go b/sysdig/sysdig_clients.go index 51aa8acb3..cdc4cd3e9 100644 --- a/sysdig/sysdig_clients.go +++ b/sysdig/sysdig_clients.go @@ -16,7 +16,7 @@ type SysdigClients interface { io.Closer GetClientType() ClientType GetSecureEndpoint() (string, error) - GetSecureApiToken() (string, error) + GetSecureAPIToken() (string, error) Configure(context.Context, *schema.ResourceData) AddCleanupHook(func(context.Context, SysdigClients) error) @@ -88,7 +88,7 @@ type ibmVariables struct { func getSysdigMonitorVariables(data *schema.ResourceData) (*sysdigVariables, error) { var ok bool - var apiURL, token interface{} + var apiURL, token any if apiURL, ok = data.GetOk("sysdig_monitor_url"); !ok { return nil, errors.New("missing sysdig monitor URL") @@ -110,7 +110,7 @@ func getSysdigMonitorVariables(data *schema.ResourceData) (*sysdigVariables, err func getSysdigSecureVariables(data *schema.ResourceData) (*sysdigSecureVariables, error) { var ok bool - var apiURL, token interface{} + var apiURL, token any if apiURL, ok = data.GetOk("sysdig_secure_url"); !ok { return nil, errors.New("missing sysdig secure URL") @@ -140,7 +140,7 @@ func getSysdigSecureVariables(data *schema.ResourceData) (*sysdigSecureVariables func getIBMVariables(product string, data *schema.ResourceData) (*ibmVariables, error) { var ok bool - var apiURL, iamURL, instanceID, apiKey interface{} + var apiURL, iamURL, instanceID, apiKey any var teamID *int if apiURL, ok = data.GetOk(fmt.Sprintf("sysdig_%s_url", product)); !ok { @@ -214,7 +214,7 @@ func (c *sysdigClients) GetSecureEndpoint() (string, error) { return endpoint, nil } -func (c *sysdigClients) GetSecureApiToken() (string, error) { +func (c *sysdigClients) GetSecureAPIToken() (string, error) { secureAPIToken := c.d.Get("sysdig_secure_api_token").(string) if secureAPIToken == "" { return "", errors.New("GetSecureApiToken, sysdig secure token not provided") @@ -386,7 +386,7 @@ func (c *sysdigClients) GetClientType() ClientType { func getExtraHeaders(d *schema.ResourceData) map[string]string { if headers, ok := d.GetOk("extra_headers"); ok { - extraHeaders := headers.(map[string]interface{}) + extraHeaders := headers.(map[string]any) extraHeadersTransformed := map[string]string{} for key := range extraHeaders { extraHeadersTransformed[key] = extraHeaders[key].(string) diff --git a/sysdig/tfresource.go b/sysdig/tfresource.go index 06145fe2a..c9e975f20 100644 --- a/sysdig/tfresource.go +++ b/sysdig/tfresource.go @@ -54,7 +54,7 @@ func Reduce[T Target, S Source](target T, source S, reducers ...func(T, S) error return nil } -func schemaSetToList(values interface{}) []string { +func schemaSetToList(values any) []string { v := values.(*schema.Set).List() x := make([]string, len(v)) @@ -64,7 +64,7 @@ func schemaSetToList(values interface{}) []string { return x } -func toIntPtr(value interface{}) *int { +func toIntPtr(value any) *int { ptr := new(int) v, ok := value.(int) if ok { @@ -104,27 +104,27 @@ func setTFResourcePolicyType(policyType string) func(d *schema.ResourceData, pol func setTFResourcePolicyRulesMalware(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { if len(policy.Rules) == 0 { - return errors.New("The policy must have at least one rule attached to it") + return errors.New("the policy must have at least one rule attached to it") } - rules := []map[string]interface{}{} + rules := []map[string]any{} for _, rule := range policy.Rules { - additionalHashes := []map[string]interface{}{} + additionalHashes := []map[string]any{} for k := range rule.Details.(*v2.MalwareRuleDetails).AdditionalHashes { - additionalHashes = append(additionalHashes, map[string]interface{}{ + additionalHashes = append(additionalHashes, map[string]any{ "hash": k, }) } - ignoreHashes := []map[string]interface{}{} + ignoreHashes := []map[string]any{} for k := range rule.Details.(*v2.MalwareRuleDetails).IgnoreHashes { - ignoreHashes = append(ignoreHashes, map[string]interface{}{ + ignoreHashes = append(ignoreHashes, map[string]any{ "hash": k, }) } - rules = append(rules, map[string]interface{}{ - "id": rule.Id, + rules = append(rules, map[string]any{ + "id": rule.ID, "name": rule.Name, "description": rule.Description, "version": rule.Version, @@ -142,10 +142,10 @@ func setTFResourcePolicyRulesMalware(d *schema.ResourceData, policy v2.PolicyRul func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { if len(policy.Rules) == 0 { - return errors.New("The policy must have at least one rule attached to it") + return errors.New("the policy must have at least one rule attached to it") } - var rules []map[string]interface{} + var rules []map[string]any for _, rule := range policy.Rules { driftDetails, ok := rule.Details.(*v2.DriftRuleDetails) if !ok { @@ -156,9 +156,9 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules exceptionsItems := driftDetails.Exceptions.Items exceptionsMatchItems := driftDetails.Exceptions.MatchItems - var exceptionsBlock []map[string]interface{} + var exceptionsBlock []map[string]any if len(exceptionsItems) > 0 || exceptionsMatchItems { - exceptionsBlock = []map[string]interface{}{ + exceptionsBlock = []map[string]any{ { "items": exceptionsItems, "match_items": exceptionsMatchItems, @@ -169,9 +169,9 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules prohibitedItems := driftDetails.ProhibitedBinaries.Items prohibitedMatchItems := driftDetails.ProhibitedBinaries.MatchItems - var prohibitedBinariesBlock []map[string]interface{} + var prohibitedBinariesBlock []map[string]any if len(prohibitedItems) > 0 || prohibitedMatchItems { - prohibitedBinariesBlock = []map[string]interface{}{ + prohibitedBinariesBlock = []map[string]any{ { "items": prohibitedItems, "match_items": prohibitedMatchItems, @@ -182,9 +182,9 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules processBasedExceptionsItems := driftDetails.ProcessBasedExceptions.Items processBasedExceptionMatchItems := driftDetails.ProcessBasedExceptions.MatchItems - var processBasedExceptionsBlock []map[string]interface{} + var processBasedExceptionsBlock []map[string]any if len(processBasedExceptionsItems) > 0 || processBasedExceptionMatchItems { - processBasedExceptionsBlock = []map[string]interface{}{ + processBasedExceptionsBlock = []map[string]any{ { "items": processBasedExceptionsItems, "match_items": processBasedExceptionMatchItems, @@ -195,9 +195,9 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules processBasedProhibitedBinariesItems := driftDetails.ProcessBasedDenylist.Items processBasedProhibitedBinariesMatchItems := driftDetails.ProcessBasedDenylist.MatchItems - var processBasedProhibitedBinariesBlock []map[string]interface{} + var processBasedProhibitedBinariesBlock []map[string]any if len(processBasedProhibitedBinariesItems) > 0 || processBasedProhibitedBinariesMatchItems { - processBasedProhibitedBinariesBlock = []map[string]interface{}{ + processBasedProhibitedBinariesBlock = []map[string]any{ { "items": processBasedProhibitedBinariesItems, "match_items": processBasedProhibitedBinariesMatchItems, @@ -208,8 +208,8 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules mode := driftDetails.Mode enabled := (mode != "disabled") - ruleMap := map[string]interface{}{ - "id": rule.Id, + ruleMap := map[string]any{ + "id": rule.ID, "name": rule.Name, "description": rule.Description, "version": rule.Version, @@ -243,25 +243,25 @@ func setTFResourcePolicyRulesDrift(d *schema.ResourceData, policy v2.PolicyRules func setTFResourcePolicyRulesML(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { if len(policy.Rules) == 0 { - return errors.New("The policy must have at least one rule attached to it") + return errors.New("the policy must have at least one rule attached to it") } - rules := []map[string]interface{}{} + rules := []map[string]any{} for _, rule := range policy.Rules { // Only a single block of anomaly detection trigger and cryptomining trigger is allowed - // anomalyDetectionTrigger := []map[string]interface{}{{ + // anomalyDetectionTrigger := []map[string]any{{ // "enabled": rule.Details.(*v2.MLRuleDetails).AnomalyDetectionTrigger.Enabled, // "threshold": rule.Details.(*v2.MLRuleDetails).AnomalyDetectionTrigger.Threshold, // "severity": rule.Details.(*v2.MLRuleDetails).AnomalyDetectionTrigger.Severity, // }} - cryptominingTrigger := []map[string]interface{}{{ + cryptominingTrigger := []map[string]any{{ "enabled": rule.Details.(*v2.MLRuleDetails).CryptominingTrigger.Enabled, "threshold": rule.Details.(*v2.MLRuleDetails).CryptominingTrigger.Threshold, }} - rules = append(rules, map[string]interface{}{ - "id": rule.Id, + rules = append(rules, map[string]any{ + "id": rule.ID, "name": rule.Name, "description": rule.Description, "version": rule.Version, @@ -277,18 +277,18 @@ func setTFResourcePolicyRulesML(d *schema.ResourceData, policy v2.PolicyRulesCom func setTFResourcePolicyRulesAWSML(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { if len(policy.Rules) == 0 { - return errors.New("The policy must have at least one rule attached to it") + return errors.New("the policy must have at least one rule attached to it") } - rules := []map[string]interface{}{} + rules := []map[string]any{} for _, rule := range policy.Rules { - anomalousConsoleLogin := []map[string]interface{}{{ + anomalousConsoleLogin := []map[string]any{{ "enabled": rule.Details.(*v2.AWSMLRuleDetails).AnomalousConsoleLogin.Enabled, "threshold": rule.Details.(*v2.AWSMLRuleDetails).AnomalousConsoleLogin.Threshold, }} - rules = append(rules, map[string]interface{}{ - "id": rule.Id, + rules = append(rules, map[string]any{ + "id": rule.ID, "name": rule.Name, "description": rule.Description, "version": rule.Version, @@ -305,17 +305,18 @@ func setTFResourcePolicyRulesAWSML(d *schema.ResourceData, policy v2.PolicyRules // TODO: Split this func into smaller composable functions func setTFResourcePolicyActions(key string) func(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { return func(d *schema.ResourceData, policy v2.PolicyRulesComposite) error { - actions := []map[string]interface{}{{}} + actions := []map[string]any{{}} prevent := false for _, action := range policy.Policy.Actions { - if action.Type == "POLICY_ACTION_PREVENT_MALWARE" || action.Type == "POLICY_ACTION_PREVENT_DRIFT" { + switch action.Type { + case "POLICY_ACTION_PREVENT_MALWARE", "POLICY_ACTION_PREVENT_DRIFT": actions[0][key] = true prevent = true - } else if action.Type == "POLICY_ACTION_PAUSE" || action.Type == "POLICY_ACTION_STOP" || action.Type == "POLICY_ACTION_KILL" { // TODO: Refactor + case "POLICY_ACTION_PAUSE", "POLICY_ACTION_STOP", "POLICY_ACTION_KILL": // TODO: Refactor action := strings.Replace(action.Type, "POLICY_ACTION_", "", 1) actions[0]["container"] = strings.ToLower(action) - } else { - actions[0]["capture"] = []map[string]interface{}{{ + default: + actions[0]["capture"] = []map[string]any{{ "seconds_after_event": action.AfterEventNs / 1000000000, "seconds_before_event": action.BeforeEventNs / 1000000000, "name": action.Name, @@ -332,7 +333,7 @@ func setTFResourcePolicyActions(key string) func(d *schema.ResourceData, policy } currentContainerAction := d.Get("actions.0.container").(string) - currentCaptureAction := d.Get("actions.0.capture").([]interface{}) + currentCaptureAction := d.Get("actions.0.capture").([]any) // If the policy retrieved from service has no actions and the current state is default values, // then do not set the "actions" key as it may cause terraform to think there has been a state change if len(policy.Policy.Actions) > 0 || currentContainerAction != "" || len(currentCaptureAction) > 0 { @@ -394,8 +395,8 @@ func setPolicyBaseAttrs(policyType string) func(policy *v2.PolicyRulesComposite, policy.Policy.Scope = d.Get("scope").(string) policy.Policy.NotificationChannelIds = []int{} - notificationChannelIdSet := d.Get("notification_channels").(*schema.Set) - for _, id := range notificationChannelIdSet.List() { + notificationChannelIDSet := d.Get("notification_channels").(*schema.Set) + for _, id := range notificationChannelIDSet.List() { policy.Policy.NotificationChannelIds = append(policy.Policy.NotificationChannelIds, id.(int)) } @@ -417,8 +418,8 @@ func setPolicyRulesMalware(policy *v2.PolicyRulesComposite, d *schema.ResourceDa additionalHashes := map[string][]string{} if items, ok := d.GetOk("rule.0.additional_hashes"); ok { // TODO: Do not hardcode the indexes - for _, item := range items.([]interface{}) { - item := item.(map[string]interface{}) + for _, item := range items.([]any) { + item := item.(map[string]any) k := item["hash"].(string) additionalHashes[k] = []string{} } @@ -427,8 +428,8 @@ func setPolicyRulesMalware(policy *v2.PolicyRulesComposite, d *schema.ResourceDa // TODO: Extract into a function ignoreHashes := map[string][]string{} if items, ok := d.GetOk("rule.0.ignore_hashes"); ok { // TODO: Do not hardcode the indexes - for _, item := range items.([]interface{}) { - item := item.(map[string]interface{}) + for _, item := range items.([]any) { + item := item.(map[string]any) k := item["hash"].(string) ignoreHashes[k] = []string{} } @@ -455,7 +456,7 @@ func setPolicyRulesMalware(policy *v2.PolicyRulesComposite, d *schema.ResourceDa id := v2.FlexInt(d.Get("rule.0.id").(int)) if int(id) != 0 { - rule.Id = &id + rule.ID = &id } v := toIntPtr(d.Get("rule.0.version")) @@ -516,7 +517,7 @@ func setPolicyRulesDrift(policy *v2.PolicyRulesComposite, d *schema.ResourceData id := v2.FlexInt(d.Get("rule.0.id").(int)) if int(id) != 0 { - rule.Id = &id + rule.ID = &id } v := toIntPtr(d.Get("rule.0.version")) @@ -583,7 +584,7 @@ func setPolicyRulesML(policy *v2.PolicyRulesComposite, d *schema.ResourceData) e id := v2.FlexInt(d.Get("rule.0.id").(int)) if int(id) != 0 { - rule.Id = &id + rule.ID = &id } v := toIntPtr(d.Get("rule.0.version")) @@ -631,7 +632,7 @@ func setPolicyRulesAWSML(policy *v2.PolicyRulesComposite, d *schema.ResourceData id := v2.FlexInt(d.Get("rule.0.id").(int)) if int(id) != 0 { - rule.Id = &id + rule.ID = &id } v := toIntPtr(d.Get("rule.0.version"))