From d174734f864a2f81d51597d30ef22d7e63802905 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:22:18 +0200 Subject: [PATCH 01/25] refactor!: remove deprecated secure scanning policies resource --- GNUmakefile | 2 +- ...resource_sysdig_secure_scanningpolicies.go | 253 --------------- ...rce_sysdig_secure_scanningpolicies_test.go | 64 ---- ...sdig_secure_scanningpoliciesassignments.go | 293 ------------------ ...secure_scanningpoliciesassignments_test.go | 67 ---- .../client/v2/deprecated_scanning_policies.go | 186 ----------- sysdig/internal/client/v2/sysdig.go | 2 - sysdig/provider.go | 2 - website/docs/r/secure_scanning_policy.md | 92 ------ .../r/secure_scanning_policy_assignment.md | 99 ------ 10 files changed, 1 insertion(+), 1059 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go delete mode 100644 sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go delete mode 100644 sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go delete mode 100644 sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go delete mode 100644 sysdig/internal/client/v2/deprecated_scanning_policies.go delete mode 100644 website/docs/r/secure_scanning_policy.md delete mode 100644 website/docs/r/secure_scanning_policy_assignment.md diff --git a/GNUmakefile b/GNUmakefile index fcbb6a5b3..516cade65 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -64,7 +64,7 @@ fmtcheck: @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" lint: - golangci-lint run --timeout 1h ./... + golangci-lint run --build-tags "$(TEST_SUITE)" --timeout 1h ./... errcheck: @sh -c "'$(CURDIR)/scripts/errcheck.sh'" diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go deleted file mode 100644 index 2bac9c0c0..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies.go +++ /dev/null @@ -1,253 +0,0 @@ -package sysdig - -import ( - "context" - "time" - - 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" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -func deprecatedResourceSysdigSecureScanningPolicy() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "The legacy scanning engine has been deprecated. This resource will be removed in future releases.", - CreateContext: deprecatedResourceSysdigScanningPolicyCreate, - ReadContext: deprecatedResourceSysdigScanningPolicyRead, - UpdateContext: deprecatedResourceSysdigScanningPolicyUpdate, - DeleteContext: deprecatedResourceSysdigScanningPolicyDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - }, - - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Required: true, - }, - "comment": { - Type: schema.TypeString, - Required: true, - }, - "isdefault": { - Type: schema.TypeBool, - Computed: true, - }, - "version": { - Type: schema.TypeString, - Optional: true, - Default: "1_0", - }, - "policy_bundle_id": { - Type: schema.TypeString, - Optional: true, - Default: "default", - }, - "rules": { - Type: schema.TypeSet, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "gate": { - Type: schema.TypeString, - Required: true, - ValidateDiagFunc: validateDiagFunc(validation.StringInSlice([]string{"always", "dockerfile", "files", "licenses", "metadata", "npms", "packages", "passwd_file", "retrieved_files", "vulnerabilities", "secret_scans", "ruby_gems"}, false)), - }, - "trigger": { - Type: schema.TypeString, - Required: true, - // ValidateDiagFunc: TODO: create inline func to validate each trigger options depending on gate https://developer.hashicorp.com/terraform/plugin/sdkv2/schemas/schema-behaviors - }, - "action": { - Type: schema.TypeString, - Required: true, - ValidateDiagFunc: validateDiagFunc(validation.StringInSlice([]string{"WARN", "STOP"}, false)), - }, - "params": { - Type: schema.TypeSet, - Required: true, - // ValidateDiagFunc: TODO: function to validate name is valid for the given trigger, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "value": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func getDeprecatedSecureScanningPolicyClient(c SysdigClients) (v2.DeprecatedScanningPolicyInterface, error) { - return c.sysdigSecureClientV2() -} - -func deprecatedResourceSysdigScanningPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - scanningPolicy := deprecatedScanningPolicyFromResourceData(d) - scanningPolicy, err = client.CreateDeprecatedScanningPolicy(ctx, scanningPolicy) - if err != nil { - return diag.FromErr(err) - } - - deprecatedScanningPolicyToResourceData(&scanningPolicy, d) - - return nil -} - -func deprecatedResourceSysdigScanningPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - scanningPolicy := deprecatedScanningPolicyFromResourceData(d) - id := d.Get("id").(string) - scanningPolicy.ID = id - _, err = client.UpdateDeprecatedScanningPolicy(ctx, scanningPolicy) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigScanningPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id := d.Get("id").(string) - scanningPolicy, err := client.GetDeprecatedScanningPolicyByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - deprecatedScanningPolicyToResourceData(&scanningPolicy, d) - - return nil -} - -func deprecatedResourceSysdigScanningPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id := d.Get("id").(string) - err = client.DeleteDeprecatedScanningPolicyByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedScanningPolicyToResourceData(scanningPolicy *v2.DeprecatedScanningPolicy, d *schema.ResourceData) { - d.SetId(scanningPolicy.ID) - _ = d.Set("name", scanningPolicy.Name) - _ = d.Set("version", scanningPolicy.Version) - _ = d.Set("comment", scanningPolicy.Comment) - _ = d.Set("isdefault", scanningPolicy.IsDefault) - _ = d.Set("policy_bundle_id", scanningPolicy.PolicyBundleID) - - var rules []map[string]any - for _, rule := range scanningPolicy.Rules { - ruleInfo := deprecatedScanningPolicyRulesToResourceData(rule) - - rules = append(rules, ruleInfo) - } - - _ = d.Set("rules", rules) -} - -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]any - for _, param := range scanningPolicyRule.Params { - params = append(params, map[string]any{ - "name": param.Name, - "value": param.Value, - }) - } - rule["params"] = params - - return rule -} - -func deprecatedScanningPolicyFromResourceData(d *schema.ResourceData) v2.DeprecatedScanningPolicy { - scanningPolicy := v2.DeprecatedScanningPolicy{ - Name: d.Get("name").(string), - ID: d.Get("id").(string), - Comment: d.Get("comment").(string), - Version: d.Get("version").(string), - IsDefault: d.Get("isdefault").(bool), - PolicyBundleID: d.Get("policy_bundle_id").(string), - } - scanningPolicy.Rules = deprecatedScanningPolicyRulesFromResourceData(d) - - return scanningPolicy -} - -func deprecatedScanningPolicyRulesFromResourceData(d *schema.ResourceData) (rules []v2.DeprecatedScanningGate) { - for _, ruleItr := range d.Get("rules").(*schema.Set).List() { - ruleInfo := ruleItr.(map[string]any) - rule := v2.DeprecatedScanningGate{ - Gate: ruleInfo["gate"].(string), - ID: ruleInfo["id"].(string), - Trigger: ruleInfo["trigger"].(string), - Action: ruleInfo["action"].(string), - } - var params []v2.DeprecatedScanningGateParam - for _, paramsItr := range ruleInfo["params"].(*schema.Set).List() { - paramsInfo := paramsItr.(map[string]any) - param := v2.DeprecatedScanningGateParam{ - Name: paramsInfo["name"].(string), - Value: paramsInfo["value"].(string), - } - params = append(params, param) - } - rule.Params = params - rules = append(rules, rule) - } - return rules -} diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go b/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go deleted file mode 100644 index 3bb98b3f9..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpolicies_test.go +++ /dev/null @@ -1,64 +0,0 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - -package sysdig_test - -import ( - "fmt" - "os" - "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/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func TestAccDeprecatedScanningPolicy(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - if v := os.Getenv("SYSDIG_SECURE_API_TOKEN"); v == "" { - t.Fatal("SYSDIG_SECURE_API_TOKEN must be set for acceptance tests") - } - }, - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: deprecatedScanningPolicyWithName(rText()), - }, - { - ResourceName: "sysdig_secure_scanning_policy.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func deprecatedScanningPolicyWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_scanning_policy" "sample" { - name = "TERRAFORM TEST 1 %s" - comment = "TERRAFORM TEST %s" - - rules { - gate = "dockerfile" - trigger = "effective_user" - action = "WARN" - params { - name = "users" - value = "docker" - } - params { - name = "type" - value = "blacklist" - } - } -} -`, name, name) -} diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go deleted file mode 100644 index 5a1a81cea..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments.go +++ /dev/null @@ -1,293 +0,0 @@ -package sysdig - -import ( - "context" - "errors" - "time" - - 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" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -func deprecatedResourceSysdigSecureScanningPolicyAssignment() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "The legacy scanning engine has been deprecated. This resource will be removed in future releases.", - CreateContext: deprecatedResourceSysdigScanningPolicyAssignmentCreate, - ReadContext: deprecatedResourceSysdigScanningPolicyAssignmentRead, - UpdateContext: deprecatedResourceSysdigScanningPolicyAssignmentUpdate, - DeleteContext: deprecatedResourceSysdigScanningPolicyAssignmentDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - }, - - Schema: map[string]*schema.Schema{ - "items": { // todo: validate that at least there is one "default" with */*:* - Type: schema.TypeList, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Optional: true, - Default: "", - }, - "image": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Optional: true, - Default: "tag", - ValidateDiagFunc: validateDiagFunc(validation.StringInSlice([]string{"tag"}, false)), - }, - "value": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - "policy_ids": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "registry": { - Type: schema.TypeString, - Required: true, - }, - "repository": { - Type: schema.TypeString, - Required: true, - }, - "whitelist_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - "policy_bundle_id": { - Type: schema.TypeString, - Optional: true, - Default: "default", - }, - }, - } -} - -func getDeprecatedSecureScanningPolicyAssignmentClient(c SysdigClients) (v2.DeprecatedScanningPolicyAssignmentInterface, error) { - return c.sysdigSecureClientV2() -} - -func deprecatedResourceSysdigScanningPolicyAssignmentCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - scanningPolicyAssignmentList := deprecatedScanningPolicyAssignmentListFromResourceData(d) - - validation := deprecatedValidateScanningPolicyAssignment(scanningPolicyAssignmentList) - if validation != nil { - return validation - } - - scanningPolicyAssignmentList, err = client.CreateDeprecatedScanningPolicyAssignmentList(ctx, scanningPolicyAssignmentList) - if err != nil { - return diag.FromErr(err) - } - - deprecatedScanningPolicyAssignmentListToResourceData(&scanningPolicyAssignmentList, d) - - return nil -} - -func deprecatedResourceSysdigScanningPolicyAssignmentRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - scanningPolicyAssignmentList, err := client.GetDeprecatedScanningPolicyAssignmentList(ctx) - if err != nil { - return diag.FromErr(err) - } - - deprecatedScanningPolicyAssignmentListToResourceData(&scanningPolicyAssignmentList, d) - - return nil -} - -func deprecatedResourceSysdigScanningPolicyAssignmentUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - scanningPolicyAssignmentList := deprecatedScanningPolicyAssignmentListFromResourceData(d) - - validation := deprecatedValidateScanningPolicyAssignment(scanningPolicyAssignmentList) - if validation != nil { - return validation - } - - scanningPolicyAssignmentList, err = client.CreateDeprecatedScanningPolicyAssignmentList(ctx, scanningPolicyAssignmentList) // As policy assignments is a list, update is the same than create - if err != nil { - return diag.FromErr(err) - } - - deprecatedScanningPolicyAssignmentListToResourceData(&scanningPolicyAssignmentList, d) - - return nil -} - -// As Policy Assignments cannot be empty (default assignment cannot be deleted), pushing the default one -func deprecatedResourceSysdigScanningPolicyAssignmentDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureScanningPolicyAssignmentClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - defaultImage := v2.DeprecatedScanningPolicyAssignmentImage{ - Type: "tag", - Value: "*", - } - defaultItem := v2.DeprecatedScanningPolicyAssignment{ - Name: "default", - Registry: "*", - Repository: "*", - Image: defaultImage, - PolicyIDs: []string{"default"}, - WhitelistIDs: []string{}, - } - - scanningPolicyAssignmentList := v2.DeprecatedScanningPolicyAssignmentList{ - PolicyBundleID: "default", // this is forced because there is no other possible value - Items: []v2.DeprecatedScanningPolicyAssignment{defaultItem}, - } - - err = client.DeleteDeprecatedScanningPolicyAssignmentList(ctx, scanningPolicyAssignmentList) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedScanningPolicyAssignmentListToResourceData(scanningPolicyAssignmentList *v2.DeprecatedScanningPolicyAssignmentList, d *schema.ResourceData) { - d.SetId(scanningPolicyAssignmentList.PolicyBundleID) - _ = d.Set("policy_bundle_id", scanningPolicyAssignmentList.PolicyBundleID) - var items []map[string]any - - for _, item := range scanningPolicyAssignmentList.Items { - itemInfo := deprecatedScanningPolicyAssignmentToResourceData(item) - - items = append(items, itemInfo) - } - - _ = d.Set("items", items) -} - -func deprecatedScanningPolicyAssignmentToResourceData(scanningPolicyAssignment v2.DeprecatedScanningPolicyAssignment) map[string]any { - item := map[string]any{ - "id": scanningPolicyAssignment.ID, - "name": scanningPolicyAssignment.Name, - "registry": scanningPolicyAssignment.Registry, - "repository": scanningPolicyAssignment.Repository, - "policy_ids": scanningPolicyAssignment.PolicyIDs, - "whitelist_ids": scanningPolicyAssignment.WhitelistIDs, - } - - image := []map[string]any{{ - "type": scanningPolicyAssignment.Image.Type, - "value": scanningPolicyAssignment.Image.Value, - }} - - item["image"] = image - - return item -} - -func deprecatedScanningPolicyAssignmentListFromResourceData(d *schema.ResourceData) v2.DeprecatedScanningPolicyAssignmentList { - scanningPolicyAssignmentList := v2.DeprecatedScanningPolicyAssignmentList{ - PolicyBundleID: "default", // this is forced because there is no other possible value - } - - scanningPolicyAssignmentList.Items = deprecatedScanningPolicyAssignmentFromResourceData(d) - - return scanningPolicyAssignmentList -} - -func deprecatedScanningPolicyAssignmentFromResourceData(d *schema.ResourceData) (scanningPolicyAssignmentItems []v2.DeprecatedScanningPolicyAssignment) { - for _, item := range d.Get("items").([]any) { - assignmentInfo := item.(map[string]any) - assignment := v2.DeprecatedScanningPolicyAssignment{ - Name: assignmentInfo["name"].(string), - Registry: assignmentInfo["registry"].(string), - Repository: assignmentInfo["repository"].(string), - } - - assignment.PolicyIDs = []string{} - policyIDsSet := assignmentInfo["policy_ids"].([]any) - for _, policy := range policyIDsSet { - assignment.PolicyIDs = append(assignment.PolicyIDs, policy.(string)) - } - - assignment.WhitelistIDs = []string{} - whitelistIDsSet := assignmentInfo["whitelist_ids"].([]any) - for _, policy := range whitelistIDsSet { - assignment.WhitelistIDs = append(assignment.WhitelistIDs, policy.(string)) - } - imageSet := assignmentInfo["image"].([]any) - if len(imageSet) == 0 { - return - } - for _, image := range imageSet { - assignment.Image = v2.DeprecatedScanningPolicyAssignmentImage{ - Type: image.(map[string]any)["type"].(string), - Value: image.(map[string]any)["value"].(string), - } - } - - scanningPolicyAssignmentItems = append(scanningPolicyAssignmentItems, assignment) - } - return scanningPolicyAssignmentItems -} - -// Validate during creation as ValidateFunc is not supported in TypeList/TypeSet https://github.com/hashicorp/terraform-plugin-sdk/issues/156 -// This function validates the last Item from the assignment list applies to all (*/*:*) and the list of policies is not empty in any assignment -func deprecatedValidateScanningPolicyAssignment(scanningPolicyAssignmentList v2.DeprecatedScanningPolicyAssignmentList) diag.Diagnostics { - for _, item := range scanningPolicyAssignmentList.Items { - if len(item.PolicyIDs) == 0 { - return diag.FromErr(errors.New("'policy_ids' list can not be empty")) - } - } - - // 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 nil -} diff --git a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go b/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go deleted file mode 100644 index 0baf5250f..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_scanningpoliciesassignments_test.go +++ /dev/null @@ -1,67 +0,0 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - -package sysdig_test - -import ( - "fmt" - "os" - "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/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func TestAccDeprecatedScanningPolicyAssignment(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - if v := os.Getenv("SYSDIG_SECURE_API_TOKEN"); v == "" { - t.Fatal("SYSDIG_SECURE_API_TOKEN must be set for acceptance tests") - } - }, - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: deprecatedScanningPolicyAssignmentWithWhitelistIDs(rText()), - }, - }, - }) -} - -func deprecatedScanningPolicyAssignmentWithWhitelistIDs(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_scanning_policy_assignment" "sample" { - items { - name = "example %s" - image { - type = "tag" - value = "latest" - } - registry = "icr.io" - repository = "example" - - policy_ids = ["default"] - } - - items { - name = "" - image { - type = "tag" - value = "*" - } - registry = "*" - repository = "*" - - policy_ids = ["default"] - whitelist_ids = [] - } -} -`, name) -} diff --git a/sysdig/internal/client/v2/deprecated_scanning_policies.go b/sysdig/internal/client/v2/deprecated_scanning_policies.go deleted file mode 100644 index bec56d258..000000000 --- a/sysdig/internal/client/v2/deprecated_scanning_policies.go +++ /dev/null @@ -1,186 +0,0 @@ -package v2 - -import ( - "context" - "fmt" - "net/http" -) - -const ( - deprecatedScanningPoliciesPath = "%s/api/scanning/v1/policies" - deprecatedScanningPolicyPath = "%s/api/scanning/v1/policies/%s" - deprecatedScanningPolicyAssigmentPath = "%s/api/scanning/v1/mappings?bundleId=default" -) - -type DeprecatedScanningPolicyInterface interface { - Base - CreateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) - GetDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) (DeprecatedScanningPolicy, error) - UpdateDeprecatedScanningPolicy(ctx context.Context, scanningPolicy DeprecatedScanningPolicy) (DeprecatedScanningPolicy, error) - DeleteDeprecatedScanningPolicyByID(ctx context.Context, scanningPolicyID string) error -} - -type DeprecatedScanningPolicyAssignmentInterface interface { - Base - CreateDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentRequest DeprecatedScanningPolicyAssignmentList) (DeprecatedScanningPolicyAssignmentList, error) - DeleteDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) error - GetDeprecatedScanningPolicyAssignmentList(ctx context.Context) (DeprecatedScanningPolicyAssignmentList, 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 := c.requester.Request(ctx, http.MethodPost, c.deprecatedScanningPoliciesURL(), payload) - if err != nil { - return DeprecatedScanningPolicy{}, err - } - 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{}, c.ErrorFromResponse(response) - } - - return Unmarshal[DeprecatedScanningPolicy](response.Body) -} - -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 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{}, c.ErrorFromResponse(response) - } - - return Unmarshal[DeprecatedScanningPolicy](response.Body) -} - -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 := c.requester.Request(ctx, http.MethodPut, c.deprecatedScanningPolicyURL(scanningPolicy.ID), payload) - if err != nil { - return DeprecatedScanningPolicy{}, err - } - 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{}, c.ErrorFromResponse(response) - } - - return Unmarshal[DeprecatedScanningPolicy](response.Body) -} - -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 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 c.ErrorFromResponse(response) - } - - return err -} - -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 := c.requester.Request(ctx, http.MethodPut, c.scanningPolicyAssignmentURL(), payload) - if err != nil { - return DeprecatedScanningPolicyAssignmentList{}, err - } - 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{}, c.ErrorFromResponse(response) - } - - return Unmarshal[DeprecatedScanningPolicyAssignmentList](response.Body) -} - -func (c *Client) DeleteDeprecatedScanningPolicyAssignmentList(ctx context.Context, scanningPolicyAssignmentList DeprecatedScanningPolicyAssignmentList) (err error) { - payload, err := Marshal(scanningPolicyAssignmentList) - if err != nil { - return err - } - - response, err := c.requester.Request(ctx, http.MethodPut, c.scanningPolicyAssignmentURL(), payload) - if err != nil { - return err - } - 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 c.ErrorFromResponse(response) - } - - return err -} - -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 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{}, c.ErrorFromResponse(response) - } - - return Unmarshal[DeprecatedScanningPolicyAssignmentList](response.Body) -} - -func (c *Client) deprecatedScanningPoliciesURL() string { - return fmt.Sprintf(deprecatedScanningPoliciesPath, c.config.url) -} - -func (c *Client) deprecatedScanningPolicyURL(scanningPolicyID string) string { - return fmt.Sprintf(deprecatedScanningPolicyPath, c.config.url, scanningPolicyID) -} - -func (c *Client) scanningPolicyAssignmentURL() string { - return fmt.Sprintf(deprecatedScanningPolicyAssigmentPath, c.config.url) -} diff --git a/sysdig/internal/client/v2/sysdig.go b/sysdig/internal/client/v2/sysdig.go index d0fd5bdb7..70b96b530 100644 --- a/sysdig/internal/client/v2/sysdig.go +++ b/sysdig/internal/client/v2/sysdig.go @@ -44,8 +44,6 @@ type SysdigSecure interface { CloudauthAccountFeatureSecureInterface CloudauthAccountSecureInterface CompositePolicyInterface - DeprecatedScanningPolicyAssignmentInterface - DeprecatedScanningPolicyInterface DeprecatedVulnerabilityExceptionInterface DeprecatedVulnerabilityExceptionListInterface ListInterface diff --git a/sysdig/provider.go b/sysdig/provider.go index 8ef0ef4e4..6c73fc72b 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -131,8 +131,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), "sysdig_secure_policy": deprecatedResourceSysdigSecurePolicy(), - "sysdig_secure_scanning_policy": deprecatedResourceSysdigSecureScanningPolicy(), - "sysdig_secure_scanning_policy_assignment": deprecatedResourceSysdigSecureScanningPolicyAssignment(), "sysdig_secure_vulnerability_exception": deprecatedResourceSysdigSecureVulnerabilityException(), "sysdig_secure_vulnerability_exception_list": deprecatedResourceSysdigSecureVulnerabilityExceptionList(), diff --git a/website/docs/r/secure_scanning_policy.md b/website/docs/r/secure_scanning_policy.md deleted file mode 100644 index 4f52f8e4d..000000000 --- a/website/docs/r/secure_scanning_policy.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_scanning_policy" -description: |- - Creates a Sysdig Secure Scanning Policy for Legacy Scanning Engine. ---- - -# Resource: sysdig_secure_scanning_policy - -Creates a Sysdig Secure Policy (legacy scanning engine). - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_secure_scanning_policy" "scanning_policy_example" { - name = "Scanning Policy Name" - comment = "Scanning Policy Description" - - // Scanning Policy Rules (gates) and parameters for configuration - rules { - gate = "dockerfile" - trigger = "effective_user" - action = "WARN" - params { - name = "users" - value = "docker" - } - params { - name = "type" - value = "blacklist" - } - } - - rules { - gate = "files" - trigger = "attribute_match" - action = "WARN" - params { - name = "filename" - value = "/etc/passwd" - } - } - - rules { - gate = "vulnerabilities" - trigger = "package" - action = "WARN" - params { - name = "package_type" - value = "all" - } - params { - name = "severity" - value = "medium" - } - } -} -``` - -## Argument Reference - -* `name` - (Required) The name of the Secure policy. It must be unique. - -* `comment` - (Required) The description of Secure scanning policy. - -* `rules` - (Optional) Define all rules included in the Policy for scanning detection. - -- - - - -### Rules block - -* `gate` - (Required) Must be one of `always`, `dockerfile`, `files`, `licenses`, `metadata`, `npms`, `packages`, `passwd_file`, `retrieved_files`, `vulnerabilities`, `secret_scans`, `ruby_gems`. You can see the description of each gate in this [link](https://docs.sysdig.com/en/docs/sysdig-secure/scanning/manage-scanning-policies/scanning-policy-gates-and-triggers/). -* `trigger` - (Required) Each gate have different trigger options and parameters. Check possible triggers per gate in the previous link. -* `params` - (Required) Each gate and trigger options have different parameter configurations. Review the previous link to see all options. -* `action` - (Required) define the action to take if one gate triggers what would affect the policy results. Must be `WARN` or `STOP`. - -- - - - -## Attributes Reference - -No additional attributes are exported. - -## Import - -Secure scanning policies can be imported using the ID, e.g. - -``` -$ terraform import sysdig_secure_scanning_policy.example policy_123456 -``` diff --git a/website/docs/r/secure_scanning_policy_assignment.md b/website/docs/r/secure_scanning_policy_assignment.md deleted file mode 100644 index 82ebafda4..000000000 --- a/website/docs/r/secure_scanning_policy_assignment.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_scanning_policy_assignment" -description: |- - Creates a Sysdig Secure Scanning Policy Assignment for Legacy Scanning Engine. ---- - -# Resource: sysdig_secure_scanning_policy_assignment - -Creates a Sysdig Secure Policy Assignment (legacy scanning engine). - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_secure_scanning_policy_assignment" "assignment_example" { - items { - name = "myassignment1" - image { - type = "tag" - value = "latest" - } - registry = "docker.io" - repository = "example" - - policy_ids = ["default"] - } - - items { - name = "" - image { - type = "tag" - value = "latest" - } - registry = "*" - repository = "*" - - policy_ids = [sysdig_secure_scanning_policy.scanning_policy_example.id] - whitelist_ids = [] - } - - items { - name = "default" - image { - type = "tag" - value = "*" - } - registry = "*" - repository = "*" - - policy_ids = [sysdig_secure_scanning_policy.scanning_policy_example.id, "default"] - } - -} -``` - -## Argument Reference - -* `items` - (Required) List of scanning policy assignments. **Priority is defined from top to bottom with the order of the items**. - -* `policy_bundle_id` - (Optional) Bundle for the policy assignment. The only value accepted is "default". - -## Items block - -* `name` - (Optional) The name of the Secure scanning policy assignment. - -* `registry` - (Required) Any registry domain (e.g. quay.io). Wildcards are supported; an asterisk * specifies any registry. - -* `repository` - (Required) Any repository (typically = name of the image). Wildcards are supported; an asterisk * specifies any repository. - -* `image` - (Required) Block to define the image tag. - -* `policy_ids` - (Required) Scanning policy IDs assigned to the given Registry/Repository:tag. At least 1 required. - -* `whitelist_ids` - (Optional) List of vulnerability exception list associated with the assignment. - -- - - - -### Image block - -* `type` - equal always to "tag" - -* `value` - Image tag, any tag. Wildcards are supported; an asterisk * specifies any tag. - -- - - - -## Attributes Reference - -No additional attributes are exported. - -## Import - -Secure scanning policies can be imported using the ID, e.g. - -``` -$ terraform import sysdig_secure_scanning_policy_assignment.example default -``` From 08973ed2231e99a558cbfe292a40339338835b57 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:27:33 +0200 Subject: [PATCH 02/25] refactor!: remove deprecated sysdig_secure_vulnerability_exception resource --- ...e_sysdig_secure_vulnerability_exception.go | 189 ------------------ ...dig_secure_vulnerability_exception_test.go | 102 ---------- sysdig/provider.go | 1 - .../docs/r/secure_vulnerability_exception.md | 63 ------ 4 files changed, 355 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go delete mode 100644 sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go delete mode 100644 website/docs/r/secure_vulnerability_exception.md diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go deleted file mode 100644 index 211ff3406..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception.go +++ /dev/null @@ -1,189 +0,0 @@ -package sysdig - -import ( - "context" - "fmt" - "strings" - "time" - - 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" -) - -func deprecatedResourceSysdigSecureVulnerabilityException() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "The legacy scanning engine has been deprecated. This resource will be removed in future releases.", - CreateContext: deprecatedResourceSysdigVulnerabilityExceptionCreate, - ReadContext: deprecatedResourceSysdigVulnerabilityExceptionRead, - UpdateContext: deprecatedResourceSysdigVulnerabilityExceptionUpdate, - DeleteContext: deprecatedResourceSysdigVulnerabilityExceptionDelete, - Importer: &schema.ResourceImporter{ - 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()) - } - - _ = data.Set("list_id", parts[0]) - data.SetId(parts[1]) - - return []*schema.ResourceData{data}, nil - }, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - }, - - Schema: map[string]*schema.Schema{ - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - "list_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "cve": { - Type: schema.TypeString, - Required: true, - }, - "expiration_date": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "notes": { - Type: schema.TypeString, - Optional: true, - }, - }, - } -} - -func getDeprecatedSecureVulnerabilityExceptionClient(c SysdigClients) (v2.DeprecatedVulnerabilityExceptionInterface, error) { - return c.sysdigSecureClientV2() -} - -func deprecatedVulnerabilityExceptionFromResourceData(d *schema.ResourceData) (*v2.DeprecatedVulnerabilityException, error) { - exception := &v2.DeprecatedVulnerabilityException{ - Gate: "vulnerabilities", - Enabled: d.Get("enabled").(bool), - TriggerID: fmt.Sprintf("%s+*", d.Get("cve").(string)), - ExpirationDate: nil, - Notes: d.Get("notes").(string), - } - if id := d.Id(); id != "" { - exception.ID = id - } - - if expirationDate := d.Get("expiration_date").(int); expirationDate != 0 { - exception.ExpirationDate = &expirationDate - } - - return exception, nil -} - -func deprecatedVulnerabilityExceptionToResourceData(exception *v2.DeprecatedVulnerabilityException, d *schema.ResourceData) error { - if exception.ID != "" { - d.SetId(exception.ID) - } - - _ = d.Set("cve", strings.TrimRight(exception.TriggerID, "+*")) - _ = d.Set("enabled", exception.Enabled) - - if exception.ExpirationDate == nil { - _ = d.Set("expiration_date", 0) - } else { - _ = d.Set("expiration_date", *exception.ExpirationDate) - } - - if exception.Notes != "" { - _ = d.Set("notes", exception.Notes) - } - - return nil -} - -func deprecatedResourceSysdigVulnerabilityExceptionCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - exception, err := deprecatedVulnerabilityExceptionFromResourceData(d) - if err != nil { - return diag.FromErr(err) - } - - exception, err = client.CreateDeprecatedVulnerabilityException(ctx, d.Get("list_id").(string), exception) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(exception.ID) - - return nil -} - -func deprecatedResourceSysdigVulnerabilityExceptionRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - exception, err := client.GetDeprecatedVulnerabilityExceptionByID(ctx, d.Get("list_id").(string), d.Id()) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - err = deprecatedVulnerabilityExceptionToResourceData(exception, d) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigVulnerabilityExceptionDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteDeprecatedVulnerabilityException(ctx, d.Get("list_id").(string), d.Id()) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigVulnerabilityExceptionUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getDeprecatedSecureVulnerabilityExceptionClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - exception, err := deprecatedVulnerabilityExceptionFromResourceData(d) - if err != nil { - return diag.FromErr(err) - } - - _, err = client.UpdateDeprecatedVulnerabilityException(ctx, d.Get("list_id").(string), exception) - if err != nil { - return diag.FromErr(err) - } - - return nil -} diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go deleted file mode 100644 index da84a8141..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_test.go +++ /dev/null @@ -1,102 +0,0 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - -package sysdig_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccDeprecatedVulnerabilityException(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - if v := os.Getenv("SYSDIG_SECURE_API_TOKEN"); v == "" { - t.Fatal("SYSDIG_SECURE_API_TOKEN must be set for acceptance tests") - } - }, - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - ExternalProviders: map[string]resource.ExternalProvider{ - "time": {Source: "hashicorp/time", VersionConstraint: "0.6.0"}, - }, - Steps: []resource.TestStep{ - { - Config: deprecatedVulnerabilityException(rText()), - }, - { - ResourceName: "sysdig_secure_vulnerability_exception.sample", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importStateDeprecatedVulnerabilityException("sysdig_secure_vulnerability_exception.sample"), - }, - { - Config: deprecatedVulnerabilityExceptionMigrationToOtherList(rText()), - }, - }, - }) -} - -func importStateDeprecatedVulnerabilityException(name string) resource.ImportStateIdFunc { - return func(state *terraform.State) (string, error) { - rs, ok := state.RootModule().Resources[name] - if !ok { - return "", fmt.Errorf("Not found: %s", name) - } - return fmt.Sprintf("%s/%s", rs.Primary.Attributes["list_id"], rs.Primary.ID), nil - } -} - -func deprecatedVulnerabilityException(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_vulnerability_exception_list" "sample" { - name = "TERRAFORM TEST 1 %s" - description = "TERRAFORM TEST %s" -} - -resource "time_static" "example" { - rfc3339 = "2099-01-01T00:00:00Z" -} - -resource "sysdig_secure_vulnerability_exception" "sample" { - enabled = false - list_id = sysdig_secure_vulnerability_exception_list.sample.id - cve = "CVE-1234-1234" - expiration_date = time_static.example.unix - notes = "Example notes on why this exception is created" -} -`, name, name) -} - -func deprecatedVulnerabilityExceptionMigrationToOtherList(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_vulnerability_exception_list" "sample_2" { - name = "TERRAFORM TEST 2 %s" - description = "TERRAFORM TEST %s" -} - -resource "time_static" "example" { - rfc3339 = "2099-01-01T00:00:00Z" -} - -resource "sysdig_secure_vulnerability_exception" "sample" { - enabled = false - list_id = sysdig_secure_vulnerability_exception_list.sample_2.id - cve = "CVE-1234-1234" - expiration_date = time_static.example.unix - notes = "Example notes on why this exception is created" -} -`, name, name) -} diff --git a/sysdig/provider.go b/sysdig/provider.go index 6c73fc72b..f568b4a9d 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -131,7 +131,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), "sysdig_secure_policy": deprecatedResourceSysdigSecurePolicy(), - "sysdig_secure_vulnerability_exception": deprecatedResourceSysdigSecureVulnerabilityException(), "sysdig_secure_vulnerability_exception_list": deprecatedResourceSysdigSecureVulnerabilityExceptionList(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), diff --git a/website/docs/r/secure_vulnerability_exception.md b/website/docs/r/secure_vulnerability_exception.md deleted file mode 100644 index 974a3f80a..000000000 --- a/website/docs/r/secure_vulnerability_exception.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_vulnerability_exception" -description: |- - Creates a Sysdig Secure Vulnerability Exception. ---- - -# Resource: sysdig_secure_vulnerability_exception - -Creates a Sysdig Secure Vulnerability Exception (legacy scanning engine). - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_secure_vulnerability_exception_list" "sample" { - name = "TERRAFORM TEST 1 %s" - description = "TERRAFORM TEST %s" -} - -resource "time_static" "example" { - rfc3339 = "2025-01-01T00:00:00Z" -} - -resource "sysdig_secure_vulnerability_exception" "sample" { - cve = "CVE-1234-1234" - list_id = sysdig_secure_vulnerability_exception_list.sample.id - expiration_date = time_static.example.unix - notes = "Example notes on why this exception is created" - enabled = false -} - -``` - -## Argument Reference - -* `cve` - (Required) The CVE ID to make an exception to. - -* `list_id` - (Required) The ID of the Vulnerability exception list to assign this exception to. - -* `expiration_date` - (Optional) The expiration date of the exception, useful if you want to ignore - some vulnerability only for a period of time. The time specified is Unix timestamp, - and must reference a date at 00:00:00 AM. See the example where the referenced date - is the 1st of January 2025. Default: 0 (no expiration date). - -* `notes` - (Optional) Some context of why this vulnerability is being ignored. - -* `enabled` - (Optional) If this is false, the CVE exception will be ignored, use this if you don't want to delete - the exception. Default: true. - -## Attributes Reference - -No additional attributes are exported. - -## Import - -Vulnerability exception can be imported using the ID of the exception list, and the ID of the exception separated by `/`, e.g. - -``` -$ terraform import sysdig_secure_vulnerability_exception.example vulnexception_1iTWe5s3qFivOW4jcj5X8nnG3hn/vulnexceptionitem_1n1HL7la7LyJFAzr0DEc0hVbnFU -``` From d1f179ce9cc6bcb1aca12276fe4ee17268376db6 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:28:49 +0200 Subject: [PATCH 03/25] refactor!: remove deprecated sysdig_secure_vulnerability_exception_list resource --- ...dig_secure_vulnerability_exception_list.go | 150 ------------------ ...ecure_vulnerability_exception_list_test.go | 54 ------- sysdig/provider.go | 15 +- .../r/secure_vulnerability_exception_list.md | 40 ----- 4 files changed, 7 insertions(+), 252 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go delete mode 100644 sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go delete mode 100644 website/docs/r/secure_vulnerability_exception_list.md diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go deleted file mode 100644 index ca76aa932..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list.go +++ /dev/null @@ -1,150 +0,0 @@ -package sysdig - -import ( - "context" - "time" - - 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" -) - -func deprecatedResourceSysdigSecureVulnerabilityExceptionList() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "The legacy scanning engine has been deprecated. This resource will be removed in future releases.", - CreateContext: resourceSysdigVulnerabilityExceptionListCreate, - ReadContext: resourceSysdigVulnerabilityExceptionListRead, - UpdateContext: resourceSysdigVulnerabilityExceptionListUpdate, - DeleteContext: resourceSysdigVulnerabilityExceptionListDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "description": { - Type: schema.TypeString, - Optional: true, - }, - }, - } -} - -func getSecureSecureVulnerabilityExceptionListClient(c SysdigClients) (v2.DeprecatedVulnerabilityExceptionListInterface, error) { - return c.sysdigSecureClientV2() -} - -func resourceSysdigVulnerabilityExceptionListCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - list, err := vulnerabilityExceptionListFromResourceData(d) - if err != nil { - return diag.FromErr(err) - } - - list, err = client.CreateDeprecatedVulnerabilityExceptionList(ctx, list) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(list.ID) - - return nil -} - -func resourceSysdigVulnerabilityExceptionListRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - list, err := client.GetDeprectedVulnerabilityExceptionListByID(ctx, d.Id()) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - err = vulnerabilityExceptionListToResourceData(list, d) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func resourceSysdigVulnerabilityExceptionListDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteDeprecatedVulnerabilityExceptionList(ctx, d.Id()) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func resourceSysdigVulnerabilityExceptionListUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecureSecureVulnerabilityExceptionListClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - list, err := vulnerabilityExceptionListFromResourceData(d) - if err != nil { - return diag.FromErr(err) - } - - _, err = client.UpdateDeprecatedVulnerabilityExceptionList(ctx, list) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func vulnerabilityExceptionListFromResourceData(d *schema.ResourceData) (*v2.DeprecatedVulnerabilityExceptionList, error) { - list := &v2.DeprecatedVulnerabilityExceptionList{ - Version: "1_0", - Name: d.Get("name").(string), - } - if id := d.Id(); id != "" { - list.ID = id - } - if comment, ok := d.GetOk("description"); ok { - list.Comment = comment.(string) - } - - return list, nil -} - -func vulnerabilityExceptionListToResourceData(list *v2.DeprecatedVulnerabilityExceptionList, d *schema.ResourceData) error { - if list.ID != "" { - d.SetId(list.ID) - } - - _ = d.Set("name", list.Name) - if list.Comment != "" { - _ = d.Set("description", list.Comment) - } - - return nil -} diff --git a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go b/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go deleted file mode 100644 index b7cfb0ace..000000000 --- a/sysdig/deprecated_resource_sysdig_secure_vulnerability_exception_list_test.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build tf_acc_sysdig_secure || tf_acc_scanning_legacy - -package sysdig_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccDeprecatedVulnerabilityExceptionList(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - if v := os.Getenv("SYSDIG_SECURE_API_TOKEN"); v == "" { - t.Fatal("SYSDIG_SECURE_API_TOKEN must be set for acceptance tests") - } - }, - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: deprecatedVulnerabilityExceptionList(rText()), - }, - { - ResourceName: "sysdig_secure_vulnerability_exception_list.sample", - ImportState: true, - ImportStateVerify: true, - }, - { - Config: deprecatedVulnerabilityExceptionList(rText()), - }, - }, - }) -} - -func deprecatedVulnerabilityExceptionList(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_vulnerability_exception_list" "sample" { - name = "TERRAFORM TEST 1 %s" - description = "TERRAFORM TEST %s" -} -`, name, name) -} diff --git a/sysdig/provider.go b/sysdig/provider.go index f568b4a9d..c7a968c50 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -124,14 +124,13 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_team_service_account": resourceSysdigTeamServiceAccount(), "sysdig_user": resourceSysdigUser(), - "sysdig_monitor_alert_anomaly": deprecatedResourceSysdigMonitorAlertAnomaly(), - "sysdig_monitor_alert_downtime": deprecatedResourceSysdigMonitorAlertDowntime(), - "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), - "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), - "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), - "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), - "sysdig_secure_policy": deprecatedResourceSysdigSecurePolicy(), - "sysdig_secure_vulnerability_exception_list": deprecatedResourceSysdigSecureVulnerabilityExceptionList(), + "sysdig_monitor_alert_anomaly": deprecatedResourceSysdigMonitorAlertAnomaly(), + "sysdig_monitor_alert_downtime": deprecatedResourceSysdigMonitorAlertDowntime(), + "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), + "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), + "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), + "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), + "sysdig_secure_policy": deprecatedResourceSysdigSecurePolicy(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), "sysdig_monitor_alert_v2_downtime": resourceSysdigMonitorAlertV2Downtime(), diff --git a/website/docs/r/secure_vulnerability_exception_list.md b/website/docs/r/secure_vulnerability_exception_list.md deleted file mode 100644 index e04a813db..000000000 --- a/website/docs/r/secure_vulnerability_exception_list.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_vulnerability_exception_list" -description: |- - Creates a Sysdig Secure Vulnerability Exception list. ---- - -# Resource: sysdig_secure_vulnerability_exception_list - -Creates a Sysdig Secure Vulnerability Exception list that will hold all the vulnerability exceptions (legacy scanning engine). - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_secure_vulnerability_exception_list" "sample" { - name = "Linux vulns" - description = "Linux vulnerabilities exceptions" -} -``` - -## Argument Reference - -* `name` - (Required) The name of the Vulnerability Exception list. - -* `description` - (Required) The description of Vulnerability Exception list. - -## Attributes Reference - -No additional attributes are exported. - -## Import - -Vulnerability exception lists can be imported using the ID, e.g. - -``` -$ terraform import sysdig_secure_vulnerability_exception_list.example vulnexception_1iTWe5s3qFivOW4jcj5X8nnG3hn -``` From 105000ebb329255cc0a2ad8e68ed54cb57cc954e Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:33:23 +0200 Subject: [PATCH 04/25] refactor: remove unused deprecated model --- sysdig/internal/client/v2/deprecated_model.go | 60 ----- sysdig/internal/client/v2/sysdig.go | 2 - .../client/v2/vulnerability_exception.go | 233 ------------------ 3 files changed, 295 deletions(-) delete mode 100644 sysdig/internal/client/v2/deprecated_model.go delete mode 100644 sysdig/internal/client/v2/vulnerability_exception.go diff --git a/sysdig/internal/client/v2/deprecated_model.go b/sysdig/internal/client/v2/deprecated_model.go deleted file mode 100644 index e220a626f..000000000 --- a/sysdig/internal/client/v2/deprecated_model.go +++ /dev/null @@ -1,60 +0,0 @@ -package v2 - -type DeprecatedVulnerabilityExceptionList struct { - ID string `json:"id,omitempty"` - Version string `json:"version"` - Name string `json:"name"` - Comment string `json:"comment"` -} - -type DeprecatedVulnerabilityException struct { - ID string `json:"id"` - Gate string `json:"gate"` - TriggerID string `json:"trigger_id"` - Notes string `json:"notes"` - ExpirationDate *int `json:"expiration_date,omitempty"` - Enabled bool `json:"enabled"` -} - -type DeprecatedScanningPolicy struct { - ID string `json:"id,omitempty"` - Version string `json:"version,omitempty"` - Name string `json:"name"` - Comment string `json:"comment"` - IsDefault bool `json:"isDefault,omitempty"` - PolicyBundleID string `json:"policyBundleId,omitempty"` - Rules []DeprecatedScanningGate `json:"rules"` -} - -type DeprecatedScanningGate struct { - ID string `json:"id,omitempty"` - Gate string `json:"gate"` - Trigger string `json:"trigger"` - Action string `json:"action"` - Params []DeprecatedScanningGateParam `json:"params"` -} - -type DeprecatedScanningGateParam struct { - Name string `json:"name"` - Value string `json:"value"` -} - -type DeprecatedScanningPolicyAssignmentList struct { - Items []DeprecatedScanningPolicyAssignment `json:"items"` - PolicyBundleID string `json:"policyBundleId"` -} - -type DeprecatedScanningPolicyAssignment struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Registry string `json:"registry"` - Repository string `json:"repository"` - Image DeprecatedScanningPolicyAssignmentImage `json:"image"` - PolicyIDs []string `json:"policy_ids"` - WhitelistIDs []string `json:"whitelist_ids"` -} - -type DeprecatedScanningPolicyAssignmentImage struct { - Type string `json:"type"` - Value string `json:"value"` -} diff --git a/sysdig/internal/client/v2/sysdig.go b/sysdig/internal/client/v2/sysdig.go index 70b96b530..ef70018fe 100644 --- a/sysdig/internal/client/v2/sysdig.go +++ b/sysdig/internal/client/v2/sysdig.go @@ -44,8 +44,6 @@ type SysdigSecure interface { CloudauthAccountFeatureSecureInterface CloudauthAccountSecureInterface CompositePolicyInterface - DeprecatedVulnerabilityExceptionInterface - DeprecatedVulnerabilityExceptionListInterface ListInterface MacroInterface OnboardingSecureInterface diff --git a/sysdig/internal/client/v2/vulnerability_exception.go b/sysdig/internal/client/v2/vulnerability_exception.go deleted file mode 100644 index 857df9296..000000000 --- a/sysdig/internal/client/v2/vulnerability_exception.go +++ /dev/null @@ -1,233 +0,0 @@ -package v2 - -import ( - "context" - "fmt" - "net/http" -) - -const ( - createDeprecatedVulnerabilityExceptionListPath = "%s/api/scanning/v1/vulnexceptions" - getDeprecatedVulnerabilityExceptionListPath = "%s/api/scanning/v1/vulnexceptions/%s" - deleteDeprecatedVulnerabilityExceptionListPath = "%s/api/scanning/v1/vulnexceptions/%s" - updateDeprecatedVulnerabilityExceptionListPath = "%s/api/scanning/v1/vulnexceptions/%s" - - createDeprecatedVulnerabilityExceptionPath = "%s/api/scanning/v1/vulnexceptions/%s/vulnerabilities" - getDeprecatedVulnerabilityExceptionPath = "%s/api/scanning/v1/vulnexceptions/%s/vulnerabilities/%s/" - deleteDeprecatedVulnerabilityExceptionPath = "%s/api/scanning/v1/vulnexceptions/%s/vulnerabilities/%s/" - updateDeprecatedVulnerabilityExceptionPath = "%s/api/scanning/v1/vulnexceptions/%s/vulnerabilities/%s/" -) - -type DeprecatedVulnerabilityExceptionListInterface interface { - Base - CreateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (*DeprecatedVulnerabilityExceptionList, error) - GetDeprectedVulnerabilityExceptionListByID(ctx context.Context, id string) (*DeprecatedVulnerabilityExceptionList, error) - DeleteDeprecatedVulnerabilityExceptionList(ctx context.Context, id string) error - UpdateDeprecatedVulnerabilityExceptionList(ctx context.Context, list *DeprecatedVulnerabilityExceptionList) (*DeprecatedVulnerabilityExceptionList, error) -} - -type DeprecatedVulnerabilityExceptionInterface interface { - Base - CreateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (*DeprecatedVulnerabilityException, error) - GetDeprecatedVulnerabilityExceptionByID(ctx context.Context, listID string, exceptionID string) (*DeprecatedVulnerabilityException, error) - DeleteDeprecatedVulnerabilityException(ctx context.Context, listID string, exceptionID string) error - UpdateDeprecatedVulnerabilityException(ctx context.Context, listID string, exception *DeprecatedVulnerabilityException) (*DeprecatedVulnerabilityException, 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 := c.requester.Request(ctx, http.MethodPost, c.createDeprecatedVulnerabilityExceptionListURL(), payload) - if err != nil { - return nil, err - } - 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) -} - -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 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) -} - -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 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) - } - - return nil -} - -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 := c.requester.Request(ctx, http.MethodPut, c.updateDeprecatedVulnerabilityExceptionListURL(list.ID), payload) - if err != nil { - return nil, err - } - 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityExceptionList](response.Body) -} - -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 := c.requester.Request(ctx, http.MethodPost, c.createDeprecatedVulnerabilityExceptionURL(listID), payload) - if err != nil { - return nil, err - } - 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityException](response.Body) -} - -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 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityException](response.Body) -} - -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 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 c.ErrorFromResponse(response) - } - - return nil -} - -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 := c.requester.Request(ctx, http.MethodPut, c.updateDeprecatedVulnerabilityExceptionURL(listID, exception.ID), payload) - if err != nil { - return nil, err - } - 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, c.ErrorFromResponse(response) - } - - return Unmarshal[*DeprecatedVulnerabilityException](response.Body) -} - -func (c *Client) createDeprecatedVulnerabilityExceptionListURL() string { - return fmt.Sprintf(createDeprecatedVulnerabilityExceptionListPath, c.config.url) -} - -func (c *Client) getDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(getDeprecatedVulnerabilityExceptionListPath, c.config.url, id) -} - -func (c *Client) deleteDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionListPath, c.config.url, id) -} - -func (c *Client) updateDeprecatedVulnerabilityExceptionListURL(id string) string { - return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionListPath, c.config.url, id) -} - -func (c *Client) createDeprecatedVulnerabilityExceptionURL(listID string) string { - return fmt.Sprintf(createDeprecatedVulnerabilityExceptionPath, c.config.url, listID) -} - -func (c *Client) getDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(getDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) -} - -func (c *Client) deleteDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(deleteDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) -} - -func (c *Client) updateDeprecatedVulnerabilityExceptionURL(listID, ID string) string { - return fmt.Sprintf(updateDeprecatedVulnerabilityExceptionPath, c.config.url, listID, ID) -} From da6a0b6f08e63fa99ec7c92e9d9f466011a3c46c Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:41:22 +0200 Subject: [PATCH 05/25] docs: update docs to not use a deprecated resource --- docs/index.md | 20 ++++++++++++++------ website/docs/index.md | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/index.md b/docs/index.md index 07e083f88..a4a2e60b4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -153,14 +153,18 @@ are applied. The policy will stop the affected container and trigger a capture f further troubleshooting. ```hcl -resource "sysdig_secure_policy" "terminal_shell_or_ssh_in_container" { +resource "sysdig_secure_custom_policy" "terminal_shell_or_ssh_in_container" { name = "Terminal shell or SSH detected in container" description = "Detects a terminal shell or a ssh spawned in a container" enabled = true severity = 0 // HIGH scope = "container.id != \"\"" - rule_names = [sysdig_secure_rule_network.disallowed_ssh_connection.name, - sysdig_secure_rule_process.terminal_shell.name] + rules { + name = sysdig_secure_rule_network.disallowed_ssh_connection.name + } + rules { + name = sysdig_secure_rule_process.terminal_shell.name + } actions { container = "stop" @@ -221,14 +225,18 @@ resource "sysdig_secure_notification_channel_slack" "devops-slack" { Bind them to the policy, modifying the file `policy.tf`; note the `notification_channels` property: ```hcl -resource "sysdig_secure_policy" "terminal_shell_or_ssh_in_container" { +resource "sysdig_secure_custom_policy" "terminal_shell_or_ssh_in_container" { name = "Terminal shell or SSH detected in container" description = "Detects a terminal shell or a ssh spawned in a container" enabled = true severity = 0 // HIGH scope = "container.id != \"\"" - rule_names = [sysdig_secure_rule_network.disallowed_ssh_connection.name, - sysdig_secure_rule_process.terminal_shell.name] + rules { + name = sysdig_secure_rule_network.disallowed_ssh_connection.name + } + rules { + name = sysdig_secure_rule_process.terminal_shell.name + } actions { container = "stop" diff --git a/website/docs/index.md b/website/docs/index.md index c27b9dd57..a601b677e 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -72,7 +72,7 @@ provider "sysdig" { // create a new secure policy -resource "sysdig_secure_policy" "unexpected_inbound_tcp_connection_traefik" { +resource "sysdig_secure_custom_policy" "unexpected_inbound_tcp_connection_traefik" { # ... } ``` From b478a65ce21ca1d1129ebf0f7c71c60f65d23941 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Wed, 17 Sep 2025 15:47:42 +0200 Subject: [PATCH 06/25] refactor!: remove deprecated sysdig_secure_policy resource --- sysdig/provider.go | 1 - ...> resource_sysdig_secure_common_policy.go} | 271 ++++-------------- sysdig/resource_sysdig_secure_policy_test.go | 268 ----------------- website/docs/r/secure_policy.md | 119 -------- 4 files changed, 51 insertions(+), 608 deletions(-) rename sysdig/{deprecated_resource_sysdig_secure_policy.go => resource_sysdig_secure_common_policy.go} (54%) delete mode 100644 sysdig/resource_sysdig_secure_policy_test.go delete mode 100644 website/docs/r/secure_policy.md diff --git a/sysdig/provider.go b/sysdig/provider.go index c7a968c50..d927d2773 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -130,7 +130,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), - "sysdig_secure_policy": deprecatedResourceSysdigSecurePolicy(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), "sysdig_monitor_alert_v2_downtime": resourceSysdigMonitorAlertV2Downtime(), diff --git a/sysdig/deprecated_resource_sysdig_secure_policy.go b/sysdig/resource_sysdig_secure_common_policy.go similarity index 54% rename from sysdig/deprecated_resource_sysdig_secure_policy.go rename to sysdig/resource_sysdig_secure_common_policy.go index 71dbf81e3..8ca711fa2 100644 --- a/sysdig/deprecated_resource_sysdig_secure_policy.go +++ b/sysdig/resource_sysdig_secure_common_policy.go @@ -3,17 +3,13 @@ package sysdig import ( "context" "fmt" - "net/http" "strconv" "strings" "sync" "time" v2 "github.com/draios/terraform-provider-sysdig/sysdig/internal/client/v2" - "github.com/hashicorp/terraform-plugin-log/tflog" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) @@ -36,135 +32,32 @@ var validatePolicyType = validation.StringInSlice([]string{ "awscloudtrail_stateful", }, false) -func deprecatedResourceSysdigSecurePolicy() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - CreateContext: deprecatedResourceSysdigPolicyCreate, - ReadContext: deprecatedResourceSysdigPolicyRead, - UpdateContext: deprecatedResourceSysdigPolicyUpdate, - DeleteContext: deprecatedResourceSysdigPolicyDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - }, - - DeprecationMessage: "The sysdig_secure_policy resource is being replaced by sysdig_secure_custom_policy, " + - "sysdig_secure_managed_policy, and sysdig_secure_managed_ruleset depending on the type of policy.", - - Schema: createPolicySchema(map[string]*schema.Schema{ - "description": { - Type: schema.TypeString, - Required: true, - }, - "type": { - Type: schema.TypeString, - Optional: true, - Default: "falco", - ValidateDiagFunc: validateDiagFunc(validatePolicyType), - }, - "severity": { - Type: schema.TypeInt, - Default: 4, - Optional: true, - ValidateDiagFunc: validateDiagFunc(validation.IntBetween(0, 7)), - }, - "rule_names": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }), - } -} - func getSecurePolicyClient(c SysdigClients) (v2.PolicyInterface, error) { return c.sysdigSecureClientV2() } -func deprecatedResourceSysdigPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - sysdigClients := meta.(SysdigClients) - client, err := getSecurePolicyClient(sysdigClients) - if err != nil { - return diag.FromErr(err) - } - - policy := deprecatedPolicyFromResourceData(d) - policy, err = client.CreatePolicy(ctx, policy) - if err != nil { - return diag.FromErr(err) - } - sysdigClients.AddCleanupHook(sendPoliciesToAgents) - - deprecatedPolicyToResourceData(&policy, d) - - return nil -} - -// Saves the resource data information for the common fields of the policy -func commonPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { - if policy.ID != 0 { - d.SetId(strconv.Itoa(policy.ID)) - } - - _ = d.Set("name", policy.Name) - _ = d.Set("scope", policy.Scope) - _ = d.Set("enabled", policy.Enabled) - _ = d.Set("version", policy.Version) - _ = d.Set("runbook", policy.Runbook) - - actions := []map[string]any{{}} - for _, action := range policy.Actions { - 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, - "filter": action.Filter, - "bucket_name": action.BucketName, - "folder": action.Folder, - }} +var sendPoliciesToAgentsOnce sync.Once - case "POLICY_ACTION_KILL_PROCESS": - actions[0]["kill_process"] = true - default: - action := strings.Replace(action.Type, "POLICY_ACTION_", "", 1) - actions[0]["container"] = strings.ToLower(action) +func sendPoliciesToAgents(ctx context.Context, clients SysdigClients) error { + var err error + sendPoliciesToAgentsOnce.Do(func() { + tflog.Info(ctx, "Sending policies to agents") + var client v2.PolicyInterface + client, err = getSecurePolicyClient(clients) + if err != nil { + return } - } - - currentContainerAction := d.Get("actions.0.container").(string) - 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 { - _ = d.Set("actions", actions) - } - - _ = d.Set("notification_channels", policy.NotificationChannelIds) -} - -func deprecatedPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { - commonPolicyToResourceData(policy, d) - _ = d.Set("description", policy.Description) - _ = d.Set("severity", policy.Severity) - if policy.Type != "" { - _ = d.Set("type", policy.Type) - } else { - _ = d.Set("type", "falco") + // When running as a cleanup hook, the terraform context is in a cancelled state. + // Using a background context with a deadline will allow us to complete this request. + backgroundCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(15*time.Second)) + defer cancel() + err = client.SendPoliciesToAgents(backgroundCtx) + }) + if err != nil { + tflog.Error(ctx, fmt.Sprintf("Error in sendPoliciesToAgents: %s", err.Error())) } - - _ = d.Set("rule_names", policy.RuleNames) + return err } func commonPolicyFromResourceData(policy *v2.Policy, d *schema.ResourceData) { @@ -182,26 +75,6 @@ func commonPolicyFromResourceData(policy *v2.Policy, d *schema.ResourceData) { } } -func deprecatedPolicyFromResourceData(d *schema.ResourceData) v2.Policy { - policy := &v2.Policy{} - commonPolicyFromResourceData(policy, d) - - policy.Description = d.Get("description").(string) - policy.Severity = d.Get("severity").(int) - policy.Type = d.Get("type").(string) - - policy.RuleNames = []string{} - 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) - } - } - - return *policy -} - func addActionsToPolicy(d *schema.ResourceData, policy *v2.Policy) { policy.Actions = []v2.Action{} actions := d.Get("actions").([]any) @@ -252,87 +125,45 @@ func addActionsToPolicy(d *schema.ResourceData, policy *v2.Policy) { } } -func deprecatedResourceSysdigPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecurePolicyClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, _ := strconv.Atoi(d.Id()) - policy, statusCode, err := client.GetPolicyByID(ctx, id) - if err != nil { - if statusCode == http.StatusNotFound { - d.SetId("") - } else { - return diag.FromErr(err) - } - } - - deprecatedPolicyToResourceData(&policy, d) - - return nil -} - -func deprecatedResourceSysdigPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - sysdigClients := meta.(SysdigClients) - client, err := getSecurePolicyClient(sysdigClients) - if err != nil { - return diag.FromErr(err) +func commonPolicyToResourceData(policy *v2.Policy, d *schema.ResourceData) { + if policy.ID != 0 { + d.SetId(strconv.Itoa(policy.ID)) } - id, _ := strconv.Atoi(d.Id()) - - err = client.DeletePolicy(ctx, id) - if err != nil { - return diag.FromErr(err) - } - sysdigClients.AddCleanupHook(sendPoliciesToAgents) + _ = d.Set("name", policy.Name) + _ = d.Set("scope", policy.Scope) + _ = d.Set("enabled", policy.Enabled) + _ = d.Set("version", policy.Version) + _ = d.Set("runbook", policy.Runbook) - return nil -} + actions := []map[string]any{{}} + for _, action := range policy.Actions { + 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, + "filter": action.Filter, + "bucket_name": action.BucketName, + "folder": action.Folder, + }} -func deprecatedResourceSysdigPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - sysdigClients := meta.(SysdigClients) - client, err := getSecurePolicyClient(sysdigClients) - if err != nil { - return diag.FromErr(err) + case "POLICY_ACTION_KILL_PROCESS": + actions[0]["kill_process"] = true + default: + action := strings.Replace(action.Type, "POLICY_ACTION_", "", 1) + actions[0]["container"] = strings.ToLower(action) + } } - policy := deprecatedPolicyFromResourceData(d) - policy.Version = d.Get("version").(int) - - id, _ := strconv.Atoi(d.Id()) - policy.ID = id - - _, err = client.UpdatePolicy(ctx, policy) - if err != nil { - return diag.FromErr(err) + currentContainerAction := d.Get("actions.0.container").(string) + 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 { + _ = d.Set("actions", actions) } - sysdigClients.AddCleanupHook(sendPoliciesToAgents) - - return nil -} - -var sendPoliciesToAgentsOnce sync.Once - -func sendPoliciesToAgents(ctx context.Context, clients SysdigClients) error { - var err error - sendPoliciesToAgentsOnce.Do(func() { - tflog.Info(ctx, "Sending policies to agents") - var client v2.PolicyInterface - client, err = getSecurePolicyClient(clients) - if err != nil { - return - } - // When running as a cleanup hook, the terraform context is in a cancelled state. - // Using a background context with a deadline will allow us to complete this request. - backgroundCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(15*time.Second)) - defer cancel() - err = client.SendPoliciesToAgents(backgroundCtx) - }) - if err != nil { - tflog.Error(ctx, fmt.Sprintf("Error in sendPoliciesToAgents: %s", err.Error())) - } - return err + _ = d.Set("notification_channels", policy.NotificationChannelIds) } diff --git a/sysdig/resource_sysdig_secure_policy_test.go b/sysdig/resource_sysdig_secure_policy_test.go deleted file mode 100644 index a0682eb96..000000000 --- a/sysdig/resource_sysdig_secure_policy_test.go +++ /dev/null @@ -1,268 +0,0 @@ -//go:build tf_acc_sysdig_secure || tf_acc_policies || tf_acc_onprem_secure - -package sysdig_test - -import ( - "fmt" - "os" - "strings" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/buildinfo" - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccPolicy(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - steps := []resource.TestStep{ - { - Config: policyWithName(rText()), - }, - { - ResourceName: "sysdig_secure_policy.sample", - ImportState: true, - ImportStateVerify: true, - }, - { - Config: policyWithoutActions(rText()), - }, - { - Config: policyWithoutNotificationChannels(rText()), - }, - { - Config: policyWithMinimumConfiguration(rText()), - }, - { - Config: policiesWithDifferentSeverities(rText()), - }, - { - Config: policiesWithKillAction(rText()), - }, - } - - if !buildinfo.OnpremSecure { - steps = append(steps, - resource.TestStep{Config: policiesForAWSCloudtrail(rText())}, - resource.TestStep{Config: policiesForGCPAuditLog(rText())}, - resource.TestStep{Config: policiesForAzurePlatformlogs(rText())}, - ) - if !strings.HasSuffix(os.Getenv("SYSDIG_SECURE_URL"), "ibm.com") { - steps = append(steps, - resource.TestStep{Config: policiesForFalcoCloudAWSCloudtrail(rText())}, - resource.TestStep{Config: policiesForOkta(rText())}, - resource.TestStep{Config: policiesForGithub(rText())}, - resource.TestStep{Config: policiesForGuardDuty(rText())}, - ) - } - } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigSecureApiTokenEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: steps, - }) -} - -func policyWithName(name string) string { - return fmt.Sprintf(` -%s -%s -resource "sysdig_secure_policy" "sample" { - name = "TERRAFORM TEST 1 %s" - description = "TERRAFORM TEST %s" - enabled = true - severity = 4 - scope = "container.id != \"\"" - rule_names = [sysdig_secure_rule_falco.terminal_shell.name] - runbook = "https://sysdig.com" - - actions { - container = "stop" - capture { - seconds_before_event = 5 - seconds_after_event = 10 - name = "testcapture" - filter = "proc.name=cat" - bucket_name = "testbucket" - folder = "testfolder" - } - } - - notification_channels = [sysdig_secure_notification_channel_email.sample_email.id] -} -`, secureNotificationChannelEmailWithName(name), ruleFalcoTerminalShell(name), name, name) -} - -func policyWithoutActions(name string) string { - return fmt.Sprintf(` -%s -%s -resource "sysdig_secure_policy" "sample2" { - name = "TERRAFORM TEST 2 %s" - description = "TERRAFORM TEST %s" - enabled = true - severity = 4 - scope = "container.id != \"\"" - rule_names = [sysdig_secure_rule_falco.terminal_shell.name] - - notification_channels = [sysdig_secure_notification_channel_email.sample_email.id] - - actions {} -} -`, secureNotificationChannelEmailWithName(name), ruleFalcoTerminalShell(name), name, name) -} - -func policyWithoutNotificationChannels(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample3" { - name = "TERRAFORM TEST 3 %s" - description = "TERRAFORM TEST %s" - enabled = true - severity = 4 - scope = "container.id != \"\"" - rule_names = ["Terminal shell in container"] - actions {} -} -`, name, name) -} - -func policyWithMinimumConfiguration(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample4" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - actions {} -} -`, name, name) -} - -func policiesWithDifferentSeverities(name string) (res string) { - for i := 0; i <= 7; i++ { - res += fmt.Sprintf(` -resource "sysdig_secure_policy" "sample_%d" { - name = "TERRAFORM TEST 1 %s-%d" - description = "TERRAFORM TEST %s-%d" - enabled = true - severity = %d - scope = "container.id != \"\"" - rule_names = ["Terminal shell in container"] - - actions { - container = "stop" - capture { - seconds_before_event = 5 - seconds_after_event = 10 - name = "capture_name" - filter = "proc.name=cat" - bucket_name = "testbucket" - } - } -} - -`, i, name, i, name, i, i) - } - return -} - -func policiesWithKillAction(name string) (res string) { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample" { - name = "TERRAFORM TEST 1 %s" - description = "TERRAFORM TEST %s" - enabled = true - severity = 4 - scope = "container.id != \"\"" - rule_names = ["Terminal shell in container"] - - actions { - container = "kill" - } -} -`, name, name) -} - -func policiesForAWSCloudtrail(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample4" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - type = "aws_cloudtrail" - actions {} -} -`, name, name) -} - -func policiesForGCPAuditLog(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample5" { - name = "TERRAFORM TEST %s" - description = "TERRAFORM TEST %s" - type = "gcp_auditlog" - actions {} -} -`, name, name) -} - -func policiesForAzurePlatformlogs(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample6" { - name = "TERRAFORM TEST %s" - description = "TERRAFORM TEST %s" - type = "azure_platformlogs" - actions {} -} -`, name, name) -} - -func policiesForFalcoCloudAWSCloudtrail(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample7" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - type = "awscloudtrail" - actions {} -} -`, name, name) -} - -func policiesForOkta(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample8" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - type = "okta" - actions {} -} -`, name, name) -} - -func policiesForGithub(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample9" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - type = "github" - actions {} -} -`, name, name) -} - -func policiesForGuardDuty(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_policy" "sample10" { - name = "TERRAFORM TEST 4 %s" - description = "TERRAFORM TEST %s" - type = "guardduty" - actions {} -} -`, name, name) -} diff --git a/website/docs/r/secure_policy.md b/website/docs/r/secure_policy.md deleted file mode 100644 index 260ffb1d9..000000000 --- a/website/docs/r/secure_policy.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_policy" -description: |- - Creates a Sysdig Secure Policy. ---- - -# Resource: sysdig_secure_policy - -Creates a Sysdig Secure Policy. - -~> **Deprecation Notice:** The `sysdig_secure_policy` resource has been deprecated and is being replaced by -`sysdig_secure_custom_policy`, `sysdig_secure_managed_policy`, and `sysdig_secure_managed_ruleset` depending on the type -of policy. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -data "sysdig_secure_notification_channel" "email_notification_channel" { - name = "Test Email Channel" -} - -resource "sysdig_secure_policy" "write_apt_database" { - name = "Write apt database" - description = "an attempt to write to the dpkg database by any non-dpkg related program" - severity = 4 - enabled = true - runbook = "https://runbook.com" - - // Scope selection - scope = "container.id != \"\"" - - // Rule selection - rule_names = ["Terminal shell in container"] - - actions { - container = "stop" - capture { - seconds_before_event = 5 - seconds_after_event = 10 - } - } - - notification_channels = [data.sysdig_secure_notification_channel.email_notification_channel.id] -} -``` - -## Argument Reference - -* `name` - (Required) The name of the Secure policy. It must be unique. - -* `description` - (Required) The description of Secure policy. - -* `severity` - (Optional) The severity of Secure policy. The accepted values - are: 0, 1, 2, 3 (High), 4, 5 (Medium), 6 (Low) and 7 (Info). The default value is 4 (Medium). - -* `enabled` - (Optional) Will secure process with this rule?. By default this is true. - -* `type` - (Optional) Specifies the type of the runtime policy. Must be one of: `falco`, `list_matching`, `k8s_audit`, - `aws_cloudtrail`, `gcp_auditlog`, `azure_platformlogs`, `awscloudtrail`, `okta`, `github`, `guardduty`. By default it is `falco`. - -* `runbook` - (Optional) Customer provided url that provides a runbook for a given policy. -- - - - -### Scope selection - -* `scope` - (Optional) Limit application scope based in one expression. For - example: "host.ip.private = \\"10.0.23.1\\"". By default the rule won't be scoped - and will target the entire infrastructure. - -- - - - -### Actions block - -The actions block is optional and supports: - -* `container` - (Optional) The action applied to container when this Policy is - triggered. Can be *stop*, *pause* or *kill*. If this is not specified, - no action will be applied at the container level. - -* `capture` - (Optional) Captures with Sysdig the stream of system calls: - * `seconds_before_event` - (Required) Captures the system calls during the - amount of seconds before the policy was triggered. - * `seconds_after_event` - (Required) Captures the system calls for the amount - of seconds after the policy was triggered. - * `name` - (Required) The name of the capture file - * `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name=cat` - * `bucket_name` - (Optional) Custom bucket to store capture in, - bucket should be onboarded in Integrations > S3 Capture Storage. Default is to use Sysdig Secure Storage - * `folder` - (Optional) Name of folder to store capture inside the bucket. - By default we will store the capture file at the root of the bucket - -- - - - -### Falco rule selection - -* `rule_names` - (Optional) Array with the name of the rules to match. - -- - - - -### Notification - -* `notification_channels` - (Optional) IDs of the notification channels to send alerts to - when the policy is fired. - -## Attributes Reference - -No additional attributes are exported. - -## Import - -Secure runtime policies can be imported using the ID, e.g. - -``` -$ terraform import sysdig_secure_policy.example 12345 -``` From 50a1f50cdb97a00a66f32ba619ec634610ebe3ad Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:19:49 +0200 Subject: [PATCH 07/25] refactor!: remove deprecated sysdig_secure_notification_channel data source --- ...mon_sysdig_monitor_notification_channel.go | 24 +++ ...sysdig_secure_notification_channel_test.go | 49 ----- ...urce_sysdig_secure_notification_channel.go | 168 ------------------ sysdig/provider.go | 2 - website/docs/d/secure_notification_channel.md | 88 --------- 5 files changed, 24 insertions(+), 307 deletions(-) create mode 100644 sysdig/common_sysdig_monitor_notification_channel.go delete mode 100644 sysdig/data_source_sysdig_secure_notification_channel_test.go delete mode 100644 sysdig/deprecated_data_source_sysdig_secure_notification_channel.go delete mode 100644 website/docs/d/secure_notification_channel.md diff --git a/sysdig/common_sysdig_monitor_notification_channel.go b/sysdig/common_sysdig_monitor_notification_channel.go new file mode 100644 index 000000000..0576657bc --- /dev/null +++ b/sysdig/common_sysdig_monitor_notification_channel.go @@ -0,0 +1,24 @@ +package sysdig + +const ( + 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" + + 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" + + notificationChannelSecureEventNotificationContentSection = "SECURE_EVENT_NOTIFICATION_CONTENT" +) diff --git a/sysdig/data_source_sysdig_secure_notification_channel_test.go b/sysdig/data_source_sysdig_secure_notification_channel_test.go deleted file mode 100644 index c576a45a5..000000000 --- a/sysdig/data_source_sysdig_secure_notification_channel_test.go +++ /dev/null @@ -1,49 +0,0 @@ -//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 ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccNotificationChannelDataSource(t *testing.T) { - rText := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigSecureApiTokenEnv, SysdigIBMSecureAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: notificationChannelEmailWithNameAndDatasource(rText), - }, - }, - }) -} - -func notificationChannelEmailWithNameAndDatasource(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_notification_channel_email" "sample_email" { - name = "%s" - enabled = true - recipients = ["root@localhost.com"] - notify_when_ok = false - notify_when_resolved = false -} - -data "sysdig_secure_notification_channel" "sample_email" { - depends_on = [sysdig_secure_notification_channel_email.sample_email] - name = sysdig_secure_notification_channel_email.sample_email.name -} -`, name) -} diff --git a/sysdig/deprecated_data_source_sysdig_secure_notification_channel.go b/sysdig/deprecated_data_source_sysdig_secure_notification_channel.go deleted file mode 100644 index fc8775a39..000000000 --- a/sysdig/deprecated_data_source_sysdig_secure_notification_channel.go +++ /dev/null @@ -1,168 +0,0 @@ -package sysdig - -import ( - "context" - "regexp" - "strconv" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -const ( - 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" - - 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" - - notificationChannelSecureEventNotificationContentSection = "SECURE_EVENT_NOTIFICATION_CONTENT" -) - -func deprecatedDataSourceSysdigSecureNotificationChannel() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - ReadContext: deprecatedDataSourceSysdigNotificationChannelRead, - - Timeouts: &schema.ResourceTimeout{ - Read: schema.DefaultTimeout(timeout), - }, - - DeprecationMessage: "The sysdig_secure_notification_channel data source will be replaced in the next version, " + - "and split out into different data sources, depending on the type of the notification channel.", - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "recipients": { - Type: schema.TypeString, - Computed: true, - }, - "topics": { - Type: schema.TypeString, - Computed: true, - }, - "api_key": { - Type: schema.TypeString, - Computed: true, - }, - "routing_key": { - Type: schema.TypeString, - Computed: true, - }, - "url": { - Type: schema.TypeString, - Computed: true, - }, - "channel": { - Type: schema.TypeString, - Computed: true, - }, - "account": { - Type: schema.TypeString, - Computed: true, - }, - "service_key": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - }, - "service_name": { - Type: schema.TypeString, - Computed: true, - }, - "notify_when_ok": { - Type: schema.TypeBool, - Computed: true, - }, - "notify_when_resolved": { - Type: schema.TypeBool, - Computed: true, - }, - "version": { - Type: schema.TypeInt, - Computed: true, - }, - "send_test_notification": { - Type: schema.TypeBool, - Computed: true, - }, - }, - } -} - -// Retrieves the information of a resource form the file and loads it in Terraform -func deprecatedDataSourceSysdigNotificationChannelRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - client, err := getSecureNotificationChannelClient(meta.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - nc, err := client.GetNotificationChannelByName(ctx, d.Get("name").(string)) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.Itoa(nc.ID)) - _ = d.Set("version", nc.Version) - _ = d.Set("name", nc.Name) - _ = d.Set("enabled", nc.Enabled) - _ = d.Set("type", nc.Type) - _ = 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("channel", nc.Options.Channel) - _ = d.Set("account", nc.Options.Account) - _ = d.Set("service_key", nc.Options.ServiceKey) - _ = d.Set("service_name", nc.Options.ServiceName) - _ = d.Set("routing_key", nc.Options.RoutingKey) - _ = d.Set("notify_when_ok", nc.Options.NotifyOnOk) - _ = d.Set("notify_when_resolved", nc.Options.NotifyOnResolve) - _ = d.Set("send_test_notification", nc.Options.SendTestNotification) - - // When we receive a notification channel of type OpsGenie, - // the API sends us the URL, but we are configuring the API - // key in the file, so terraform identifies this as a change in - // the resource and tries to update it remotely even if it - // 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 == notificationChannelTypeOpsGenie { - regex, err := regexp.Compile("apiKey=(.*)?$") - if err != nil { - return diag.FromErr(err) - } - key := regex.FindStringSubmatch(nc.Options.URL)[1] - _ = d.Set("api_key", key) - _ = d.Set("url", "") - - } - return nil -} diff --git a/sysdig/provider.go b/sysdig/provider.go index d927d2773..6a963c626 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -205,8 +205,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_fargate_workload_agent": dataSourceSysdigFargateWorkloadAgent(), "sysdig_user": dataSourceSysdigUser(), - "sysdig_secure_notification_channel": deprecatedDataSourceSysdigSecureNotificationChannel(), - "sysdig_monitor_custom_role_permissions": dataSourceSysdigMonitorCustomRolePermissions(), "sysdig_monitor_notification_channel_custom_webhook": dataSourceSysdigMonitorNotificationChannelCustomWebhook(), "sysdig_monitor_notification_channel_email": dataSourceSysdigMonitorNotificationChannelEmail(), diff --git a/website/docs/d/secure_notification_channel.md b/website/docs/d/secure_notification_channel.md deleted file mode 100644 index 72b96001a..000000000 --- a/website/docs/d/secure_notification_channel.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -subcategory: "Sysdig Secure" -layout: "sysdig" -page_title: "Sysdig: sysdig_secure_notification_channel" -description: |- - Retrieves a Sysdig Secure Notification Channel. ---- - -# Data Source: sysdig_secure_notification_channel - -Retrieves the information of an existing Sysdig Secure Notification Channel. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -data "sysdig_secure_notification_channel" "sample-email" { - name = "Example Channel - Email" -} -``` - -## Argument Reference - -* `name` - (Required) The name of the Notification Channel. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -* `enabled` - If false, the channel will not emit notifications. - -* `type` - Will be one of the following: "EMAIL", "SNS", "OPSGENIE", - "VICTOROPS", "WEBHOOK", "SLACK", "PAGER_DUTY". - -* `notify_when_ok` - Send a new notification when the alert condition is - no longer triggered. - -* `notify_when_resolved` - Send a new notification when the alert is manually - acknowledged by a user. - -* `send_test_notification` - Send an initial test notification to check - if the notification channel is working. - -### Attributes for type EMAIL - -* `recipients` - Comma-separated list of recipients that will receive - the message. - -### Attributes for type Amazon SNS - -* `topics` - List of ARNs from the SNS topics. - -### Attributes for type VICTOROPS - -* `api_key` - Key for the API. - -* `routing_key` - Routing key for VictorOps. - -### Attributes for type OPSGENIE - -* `api_key` - Key for the API. - -### Attributes for type WEBHOOK - -* `url` - URL to send the event. - -### Attributes for type SLACK - -* `url` - URL of the Slack. - -* `channel` - Channel name from this Slack. - -* `template_version` - The chosen template version for this channel - -### Attributes for type PAGERDUTY - -* `account` - Pagerduty account. - -* `service_key` - Service Key for the Pagerduty account. - -* `service_name` - Service name for the Pagerduty account. - -### Attributes for type MS_TEAMS - -* `url` - URL of the MS Teams webhook. - -* `template_version` - The chosen template version for this channel From c30d5a11583a2f628c1e6edc2cd52c9e9fd4ef67 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:25:31 +0200 Subject: [PATCH 08/25] docs: remove list of resources from documentation since it has maintenance burden --- website/docs/index.md | 54 ------------------------------------------- 1 file changed, 54 deletions(-) diff --git a/website/docs/index.md b/website/docs/index.md index a601b677e..c1bff3ed6 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -208,60 +208,6 @@ When IBM Workload Protection resources are to be created, this authentication mu It has exactly the same meaning as `sysdig_secure_team_id`, but instead of specifying team ID you are specifying a team name.
It can also be configured from the `SYSDIG_SECURE_TEAM_NAME` environment variable.

-> **Note** -> Enabling resources and data sources on IBM is under active development. -> -> For now, you can manage following resources: -> - `sysdig_monitor_team` -> - `sysdig_secure_team` -> - `sysdig_monitor_notification_channel_email` -> - `sysdig_secure_notification_channel_email` -> - `sysdig_monitor_notification_channel_opsgenie` -> - `sysdig_secure_notification_channel_opsgenie` -> - `sysdig_monitor_notification_channel_pagerduty` -> - `sysdig_secure_notification_channel_pagerduty` -> - `sysdig_monitor_notification_channel_slack` -> - `sysdig_secure_notification_channel_slack` -> - `sysdig_monitor_notification_channel_sns` -> - `sysdig_secure_notification_channel_sns` -> - `sysdig_monitor_notification_channel_victorops` -> - `sysdig_secure_notification_channel_victorops` -> - `sysdig_monitor_notification_channel_webhook` -> - `sysdig_secure_notification_channel_webhook` -> - `sysdig_monitor_notification_channel_prometheus_alert_manager` -> - `sysdig_secure_notification_channel_prometheus_alert_manager` -> - `sysdig_monitor_notification_channel_team_email` -> - `sysdig_secure_notification_channel_team_email` -> - `sysdig_monitor_notification_channel_google_chat` -> - `sysdig_monitor_notification_channel_custom_webhook` -> - `sysdig_monitor_notification_channel_ibm_event_notification` -> - `sysdig_monitor_silence_rule` -> - `sysdig_monitor_inhibition_rule` -> - `sysdig_monitor_alert_downtime` -> - `sysdig_monitor_alert_event` -> - `sysdig_monitor_alert_metric` -> - `sysdig_monitor_alert_promql` -> - `sysdig_monitor_alert_anomaly` -> - `sysdig_monitor_alert_group_outlier` -> - `sysdig_monitor_alert_v2_downtime` -> - `sysdig_monitor_alert_v2_event` -> - `sysdig_monitor_alert_v2_metric` -> - `sysdig_monitor_alert_v2_prometheus` -> - `sysdig_monitor_alert_v2_change` -> - `sysdig_monitor_alert_v2_form_based_prometheus` -> - `sysdig_monitor_alert_v2_group_outlier` -> - `sysdig_monitor_dashboard` -> - `sysdig_secure_posture_zone` -> - `sysdig_secure_posture_policy` - -> -> And data sources: -> - `sysdig_monitor_notification_channel_pagerduty` -> - `sysdig_monitor_notification_channel_email` -> - `sysdig_current_user` -> - `sysdig_secure_notification_channel` -> - `sysdig_secure_posture_policies` -> - `sysdig_secure_posture_policy` ### Others * `extra_headers` - (Optional) Defines extra HTTP headers that will be added to the client From 0d9044bacd23b27449ca8c1d75864a3f7066e7db Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:26:55 +0200 Subject: [PATCH 09/25] refactor!: delete deprecated sysdig_monitor_alert_downtime resource --- ..._resource_sysdig_monitor_alert_downtime.go | 169 ------------------ sysdig/provider.go | 1 - ...urce_sysdig_monitor_alert_downtime_test.go | 60 ------- website/docs/r/monitor_alert_downtime.md | 91 ---------- 4 files changed, 321 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_downtime.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_downtime_test.go delete mode 100644 website/docs/r/monitor_alert_downtime.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_downtime.go b/sysdig/deprecated_resource_sysdig_monitor_alert_downtime.go deleted file mode 100644 index 71f9fde27..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_downtime.go +++ /dev/null @@ -1,169 +0,0 @@ -package sysdig - -import ( - "context" - "fmt" - "strconv" - "time" - - 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" - "github.com/spf13/cast" -) - -func deprecatedResourceSysdigMonitorAlertDowntime() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "\"sysdig_monitor_alert_downtime\" has been deprecated and will be removed in future releases, use \"sysdig_monitor_alert_v2_downtime\" instead", - CreateContext: deprecatedResourceSysdigAlertDowntimeCreate, - UpdateContext: deprecatedResourceSysdigAlertDowntimeUpdate, - ReadContext: deprecatedResourceSysdigAlertDowntimeRead, - DeleteContext: deprecatedResourceSysdigAlertDowntimeDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "entities_to_monitor": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "trigger_after_pct": { - Type: schema.TypeInt, - Optional: true, - Default: 100, - }, - }), - } -} - -func deprecatedResourceSysdigAlertDowntimeCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedDowntimeAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - - return nil -} - -func deprecatedResourceSysdigAlertDowntimeUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedDowntimeAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertDowntimeRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedDowntimeAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertDowntimeDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedDowntimeAlertFromResourceData(d *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(d) - if err != nil { - return - } - - 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").([]any) - for _, entityRaw := range entitiesRaw { - alert.SegmentBy = append(alert.SegmentBy, entityRaw.(string)) - } - - return -} - -func deprecatedDowntimeAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - var triggerAfterPct float64 - _, _ = fmt.Sscanf(alert.Condition, "avg(timeAvg(uptime)) <= %f", &triggerAfterPct) - triggerAfterPct = (1 - triggerAfterPct) * 100 - - _ = data.Set("trigger_after_pct", int(triggerAfterPct)) - _ = data.Set("entities_to_monitor", alert.SegmentBy) - - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index 6a963c626..d3d1799ab 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -125,7 +125,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_user": resourceSysdigUser(), "sysdig_monitor_alert_anomaly": deprecatedResourceSysdigMonitorAlertAnomaly(), - "sysdig_monitor_alert_downtime": deprecatedResourceSysdigMonitorAlertDowntime(), "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), diff --git a/sysdig/resource_sysdig_monitor_alert_downtime_test.go b/sysdig/resource_sysdig_monitor_alert_downtime_test.go deleted file mode 100644 index 57184f90e..000000000 --- a/sysdig/resource_sysdig_monitor_alert_downtime_test.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertDowntime(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertDowntimeWithName(rText()), - }, - { - ResourceName: "sysdig_monitor_alert_downtime.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func alertDowntimeWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_downtime" "sample" { - name = "TERRAFORM TEST - DOWNTIME %s" - description = "TERRAFORM TEST - DOWNTIME %s" - severity = 2 - - entities_to_monitor = ["host.hostName", "host.mac"] - scope = "kubernetes.cluster.name in (\"pulsar\")" - - trigger_after_minutes = 10 - trigger_after_pct = 99 - - enabled = false - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } -} -`, name, name) -} diff --git a/website/docs/r/monitor_alert_downtime.md b/website/docs/r/monitor_alert_downtime.md deleted file mode 100644 index 4a86ebc70..000000000 --- a/website/docs/r/monitor_alert_downtime.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_downtime" -description: |- - Creates a Sysdig Monitor Downtime Alert. ---- - -# Resource: sysdig_monitor_alert_downtime - -Creates a Sysdig Monitor Downtime Alert. Monitor any type of entity - host, container, process, service, etc - and alert when the entity goes down. - -~> **Deprecation Notice:** `sysdig_monitor_alert_downtime` has been deprecated and will be removed in future releases, use `sysdig_monitor_alert_v2_downtime` instead. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_downtime" "sample" { - name = "[Kubernetes] Downtime Alert" - description = "Detects a downtime in the Kubernetes cluster" - severity = 2 - - entities_to_monitor = ["kubernetes.namespace.name"] - - trigger_after_minutes = 10 - trigger_after_pct = 100 -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `scope` - (Optional) Part of the infrastructure where the alert is valid. Defaults to the entire infrastructure. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `capture` - (Optional) Enables the creation of a capture file of the syscalls during the event. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `capture` - -Enables the creation of a capture file of the syscalls during the event. - -* `filename` - (Required) Defines the name of the capture file. -* `duration` - (Required) Time frame in seconds of the capture. -* `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name contains nginx`. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Downtime alert arguments - -* `entities_to_monitor` - (Required) List of metrics to monitor downtime and alert on. Example: `["kubernetes.namespace.name"]` to detect namespace removal or `["host.hostName"]` to detect host downtime. -* `trigger_after_pct` - (Optional) Below of this percentage of downtime the alert will be triggered. Defaults to 100. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - - -## Import - -Downtime alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_downtime.example 12345 -``` From 8e82c490018058426983202173913b0480a09579 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:31:17 +0200 Subject: [PATCH 10/25] refactor!: remove deprecated sysdig_monitor_alert_metric resource --- ...ed_resource_sysdig_monitor_alert_metric.go | 161 ------------------ sysdig/provider.go | 1 - ...source_sysdig_monitor_alert_metric_test.go | 156 ----------------- website/docs/r/monitor_alert_metric.md | 99 ----------- 4 files changed, 417 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_metric.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_metric_test.go delete mode 100644 website/docs/r/monitor_alert_metric.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_metric.go b/sysdig/deprecated_resource_sysdig_monitor_alert_metric.go deleted file mode 100644 index f076237cb..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_metric.go +++ /dev/null @@ -1,161 +0,0 @@ -package sysdig - -import ( - "context" - "strconv" - "time" - - 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" -) - -func deprecatedResourceSysdigMonitorAlertMetric() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "\"sysdig_monitor_alert_metric\" has been deprecated and will be removed in future releases, use \"sysdig_monitor_alert_v2_metric\" instead", - CreateContext: deprecatedResourceSysdigAlertMetricCreate, - UpdateContext: deprecatedResourceSysdigAlertMetricUpdate, - ReadContext: deprecatedResourceSysdigAlertMetricRead, - DeleteContext: deprecatedResourceSysdigAlertMetricDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "metric": { - Type: schema.TypeString, - Required: true, - }, - "multiple_alerts_by": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }), - } -} - -func deprecatedResourceSysdigAlertMetricCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedMetricAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - - return nil -} - -func deprecatedResourceSysdigAlertMetricUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedMetricAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertMetricRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedMetricAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertMetricDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedMetricAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(data) - if err != nil { - return - } - alert.Condition = data.Get("metric").(string) - - if alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { - alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alertsBy.([]any) { - alert.SegmentBy = append(alert.SegmentBy, v.(string)) - } - } - return -} - -func deprecatedMetricAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - _ = data.Set("metric", alert.Condition) - _ = data.Set("multiple_alerts_by", alert.SegmentBy) - - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index d3d1799ab..bc33095e0 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -127,7 +127,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_monitor_alert_anomaly": deprecatedResourceSysdigMonitorAlertAnomaly(), "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), - "sysdig_monitor_alert_metric": deprecatedResourceSysdigMonitorAlertMetric(), "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), diff --git a/sysdig/resource_sysdig_monitor_alert_metric_test.go b/sysdig/resource_sysdig_monitor_alert_metric_test.go deleted file mode 100644 index 9d72c08ad..000000000 --- a/sysdig/resource_sysdig_monitor_alert_metric_test.go +++ /dev/null @@ -1,156 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/draios/terraform-provider-sysdig/buildinfo" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertMetric(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertMetricWithName(rText()), - }, - { - Config: alertMetricWithGroupName(rText()), - }, - { - Config: alertMetricWithoutScopeWithName(rText()), - }, - { - Config: alertMetricWithNotificationChannel(rText()), - SkipFunc: func() (bool, error) { - return buildinfo.IBMMonitor, nil - }, - }, - { - ResourceName: "sysdig_secure_notification_channel_pagerduty.sample-pagerduty", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"send_test_notification"}, - SkipFunc: func() (bool, error) { - return buildinfo.IBMMonitor, nil - }, - }, - }, - }) -} - -func alertMetricWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_metric" "sample" { - name = "TERRAFORM TEST - METRIC %s" - description = "TERRAFORM TEST - METRIC %s" - severity = 3 - - metric = "avg(avg(cpu.used.percent)) > 50" - scope = "agent.id in (\"foo\")" - - trigger_after_minutes = 10 - - enabled = false - - multiple_alerts_by = ["kubernetes.deployment.name"] - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } -} -`, name, name) -} - -func alertMetricWithGroupName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_metric" "sample" { - name = "TERRAFORM TEST - METRIC %s" - description = "TERRAFORM TEST - METRIC %s" - severity = 3 - - metric = "avg(avg(cpu.used.percent)) > 50" - scope = "agent.id in (\"foo\")" - - trigger_after_minutes = 10 - group_name = "sample_group_name" - enabled = false - - multiple_alerts_by = ["kubernetes.deployment.name"] - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } -} -`, name, name) -} - -func alertMetricWithoutScopeWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_metric" "sample2" { - name = "TERRAFORM TEST - METRIC %s" - description = "TERRAFORM TEST - METRIC %s" - severity = 3 - - metric = "avg(avg(cpu.used.percent)) > 50" - - trigger_after_minutes = 10 - - enabled = false - - multiple_alerts_by = ["host.hostName"] - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } -} -`, name, name) -} - -// Reported by @logdnalf at https://github.com/draios/terraform-provider-sysdig/issues/24 -func alertMetricWithNotificationChannel(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_notification_channel_pagerduty" "sample-pagerduty" { - name = "Example Channel %s - Pagerduty" - enabled = true - account = "account" - service_key = "XXXXXXXXXX" - service_name = "sysdig" - notify_when_ok = true - notify_when_resolved = true -} - -resource "sysdig_monitor_alert_metric" "sample3" { - enabled = true - name = "TERAFORM TEST - METRIC %s" - description = "TERRAFORM TEST - METRIC %s" - severity = 6 - metric = "sum(min(cpu.used.percent)) > 100000" - scope = "agent.id in (\"foo\")" - trigger_after_minutes = 20 - notification_channels = [ - sysdig_secure_notification_channel_pagerduty.sample-pagerduty.id - ] - multiple_alerts_by = [ - "host.hostName" - ] -}`, name, name, name) -} diff --git a/website/docs/r/monitor_alert_metric.md b/website/docs/r/monitor_alert_metric.md deleted file mode 100644 index 5305cb9fc..000000000 --- a/website/docs/r/monitor_alert_metric.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_metric" -description: |- - Creates a Sysdig Monitor Metric Threshold Alert. ---- - -# Resource: sysdig_monitor_alert_metric - -Creates a Sysdig Monitor Metric Threshold Alert. Monitor time-series metrics and alert if they violate user-defined thresholds. - -~> **Deprecation Notice:** `sysdig_monitor_alert_metric` has been deprecated and will be removed in future releases, use `sysdig_monitor_alert_v2_metric` instead. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_metric" "sample" { - name = "[Kubernetes] CrashLoopBackOff" - description = "A Kubernetes pod failed to restart" - severity = 6 - - metric = "sum(timeAvg(kubernetes.pod.restart.count)) > 2" - trigger_after_minutes = 1 - - multiple_alerts_by = ["kubernetes.cluster.name", - "kubernetes.namespace.name", - "kubernetes.deployment.name", - "kubernetes.pod.name"] - - capture { - filename = "CrashLoopBackOff" - duration = 15 - } -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `scope` - (Optional) Part of the infrastructure where the alert is valid. Defaults to the entire infrastructure. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `capture` - (Optional) Enables the creation of a capture file of the syscalls during the event. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `capture` - -Enables the creation of a capture file of the syscalls during the event. - -* `filename` - (Required) Defines the name of the capture file. -* `duration` - (Required) Time frame in seconds of the capture. -* `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name contains nginx`. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Metric alert arguments - -* `metric` - (Required) Metric to monitor and alert on. Example: `sum(timeAvg(kubernetes.pod.restart.count)) > 2` or `avg(avg(cpu.used.percent)) > 50`. -* `multiple_alerts_by` - (Optional) List of segments to trigger a separate alert on. Example: `["kubernetes.cluster.name", "kubernetes.namespace.name"]`. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - - -## Import - -Metric Threshold alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_metric.example 12345 -``` From 8153eda1a99c2f2970db00c68ada8fc1296de8e4 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:32:46 +0200 Subject: [PATCH 11/25] refactor!: remove deprecated sysdig_monitor_alert_anomaly resource --- ...d_resource_sysdig_monitor_alert_anomaly.go | 174 ------------------ sysdig/provider.go | 1 - ...ource_sysdig_monitor_alert_anomaly_test.go | 67 ------- website/docs/r/monitor_alert_anomaly.md | 94 ---------- 4 files changed, 336 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_anomaly.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_anomaly_test.go delete mode 100644 website/docs/r/monitor_alert_anomaly.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_anomaly.go b/sysdig/deprecated_resource_sysdig_monitor_alert_anomaly.go deleted file mode 100644 index 6b26951b9..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_anomaly.go +++ /dev/null @@ -1,174 +0,0 @@ -package sysdig - -import ( - "context" - "strconv" - "time" - - 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" -) - -func deprecatedResourceSysdigMonitorAlertAnomaly() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "Anomaly Detection Alerts have been deprecated, \"sysdig_monitor_alert_anomaly\" will be removed in future releases", - CreateContext: deprecatedResourceSysdigAlertAnomalyCreate, - UpdateContext: deprecatedResourceSysdigAlertAnomalyUpdate, - ReadContext: deprecatedResourceSysdigAlertAnomalyRead, - DeleteContext: deprecatedResourceSysdigAlertAnomalyDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "monitor": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "multiple_alerts_by": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }), - } -} - -func deprecatedResourceSysdigAlertAnomalyCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedAnomalyAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - return nil -} - -func deprecatedResourceSysdigAlertAnomalyUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedAnomalyAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertAnomalyRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedAnomalyAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertAnomalyDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedAnomalyAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(data) - if err != nil { - return - } - - alert.Type = "BASELINE" - - for _, metric := range data.Get("monitor").([]any) { - alert.Monitor = append(alert.Monitor, &v2.Monitor{ - Metric: metric.(string), - StdDevFactor: 2, - }) - } - - if alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { - alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alertsBy.([]any) { - alert.SegmentBy = append(alert.SegmentBy, v.(string)) - } - } - - return -} - -func deprecatedAnomalyAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - _ = data.Set("multiple_alerts_by", alert.SegmentBy) - - monitorMetrics := []string{} - for _, v := range alert.Monitor { - monitorMetrics = append(monitorMetrics, v.Metric) - } - _ = data.Set("monitor", monitorMetrics) - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index bc33095e0..e104bfb6c 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -124,7 +124,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_team_service_account": resourceSysdigTeamServiceAccount(), "sysdig_user": resourceSysdigUser(), - "sysdig_monitor_alert_anomaly": deprecatedResourceSysdigMonitorAlertAnomaly(), "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), diff --git a/sysdig/resource_sysdig_monitor_alert_anomaly_test.go b/sysdig/resource_sysdig_monitor_alert_anomaly_test.go deleted file mode 100644 index 74cb1057b..000000000 --- a/sysdig/resource_sysdig_monitor_alert_anomaly_test.go +++ /dev/null @@ -1,67 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertAnomaly(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertAnomalyWithName(rText()), - }, - { - ResourceName: "sysdig_monitor_alert_anomaly.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func alertAnomalyWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_anomaly" "sample" { - name = "TERRAFORM TEST - ANOMALY %s" - description = "TERRAFORM TEST - ANOMALY %s" - severity = 0 - - monitor = ["cpu.cores.used", "cpu.cores.used.percent", "cpu.stolen.percent", "cpu.used.percent"] - - multiple_alerts_by = ["kubernetes.deployment.name"] - scope = "kubernetes.cluster.name in (\"pulsar\")" - - trigger_after_minutes = 10 - - enabled = false - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } - - custom_notification { - title = "{{__alert_name__}} is {{__alert_status__}}" - prepend = "{{kubernetes.deployment.name}}" - append = "{{kubernetes.deployment.name}}" - } -} -`, name, name) -} diff --git a/website/docs/r/monitor_alert_anomaly.md b/website/docs/r/monitor_alert_anomaly.md deleted file mode 100644 index 838af033c..000000000 --- a/website/docs/r/monitor_alert_anomaly.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_anomaly" -description: |- - Creates a Sysdig Monitor Anomaly Alert. ---- - -# Resource: sysdig_monitor_alert_anomaly - -Creates a Sysdig Monitor Anomaly Alert. Monitor hosts based on their historical behaviors and alert when they deviate. - -~> **Deprecation Notice:** Anomaly Detection Alerts have been deprecated in Sysdig Monitor, `sysdig_monitor_alert_anomaly` will be removed in future releases, consider rewriting the resource as a promql alert. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_anomaly" "sample" { - name = "[Kubernetes] Anomaly Detection Alert" - description = "Detects an anomaly in the cluster" - severity = 6 - - monitor = ["cpu.used.percent", "memory.bytes.used"] - - trigger_after_minutes = 10 - - multiple_alerts_by = ["kubernetes.cluster.name", - "kubernetes.namespace.name", - "kubernetes.deployment.name", - "kubernetes.pod.name"] -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `scope` - (Optional) Part of the infrastructure where the alert is valid. Defaults to the entire infrastructure. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `capture` - (Optional) Enables the creation of a capture file of the syscalls during the event. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `capture` - -Enables the creation of a capture file of the syscalls during the event. - -* `filename` - (Required) Defines the name of the capture file. -* `duration` - (Required) Time frame in seconds of the capture. -* `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name contains nginx`. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Anomaly alert arguments - -* `monitor` - (Required) Array of metrics to monitor and alert on. Example: `["cpu.used.percent", "cpu.cores.used", "memory.bytes.used", "fs.used.percent", "thread.count", "net.request.count.in"]`. -* `multiple_alerts_by` - (Optional) List of segments to trigger a separate alert on. Example: `["kubernetes.cluster.name", "kubernetes.namespace.name"]`. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - -## Import - -Anomaly Monitor alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_anomaly.example 12345 -``` From f4d7963a4ff019ea5cae2a7536b3863e570ee59d Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:33:57 +0200 Subject: [PATCH 12/25] refactor!: remove deprecated sysdig_monitor_alert_promql resource --- ...ed_resource_sysdig_monitor_alert_promql.go | 160 ------------------ sysdig/provider.go | 1 - ...source_sysdig_monitor_alert_promql_test.go | 72 -------- website/docs/r/monitor_alert_promql.md | 78 --------- 4 files changed, 311 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_promql.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_promql_test.go delete mode 100644 website/docs/r/monitor_alert_promql.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_promql.go b/sysdig/deprecated_resource_sysdig_monitor_alert_promql.go deleted file mode 100644 index 8e64a7296..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_promql.go +++ /dev/null @@ -1,160 +0,0 @@ -package sysdig - -import ( - "context" - "strconv" - "time" - - 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" -) - -func deprecatedResourceSysdigMonitorAlertPromql() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "\"sysdig_monitor_alert_promql\" has been deprecated and will be removed in future releases, use \"sysdig_monitor_alert_v2_prometheus\" instead", - CreateContext: deprecatedResourceSysdigAlertPromqlCreate, - UpdateContext: deprecatedResourceSysdigAlertPromqlUpdate, - ReadContext: deprecatedResourceSysdigAlertPromqlRead, - DeleteContext: deprecatedResourceSysdigAlertPromqlDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "promql": { - Type: schema.TypeString, - Required: true, - }, - }), - } -} - -func deprecatedResourceSysdigAlertPromqlCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedPromqlAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - - return nil -} - -func deprecatedResourceSysdigAlertPromqlUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedPromqlAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertPromqlRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedPromqlAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertPromqlDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedPromqlAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(data) - if err != nil { - return - } - duration := int((time.Duration(*alert.Timespan) * time.Microsecond).Seconds()) - alert.Duration = &duration - alert.Timespan = nil - - alert.Type = "PROMETHEUS" - - alert.Condition = data.Get("promql").(string) - - return -} - -func deprecatedPromqlAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - if alert.Duration != nil { - triggerAfterMinutes := int((time.Duration(*alert.Duration) * time.Second).Minutes()) - _ = data.Set("trigger_after_minutes", triggerAfterMinutes) - } - - _ = data.Set("promql", alert.Condition) - - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index e104bfb6c..9d4cff327 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -126,7 +126,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), - "sysdig_monitor_alert_promql": deprecatedResourceSysdigMonitorAlertPromql(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), "sysdig_monitor_alert_v2_downtime": resourceSysdigMonitorAlertV2Downtime(), diff --git a/sysdig/resource_sysdig_monitor_alert_promql_test.go b/sysdig/resource_sysdig_monitor_alert_promql_test.go deleted file mode 100644 index eb14c54d5..000000000 --- a/sysdig/resource_sysdig_monitor_alert_promql_test.go +++ /dev/null @@ -1,72 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertPromql(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertPromqlWithName(rText()), - }, - { - Config: alertPromqlWithGroupName(rText()), - }, - { - ResourceName: "sysdig_monitor_alert_promql.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func alertPromqlWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_promql" "sample" { - name = "TERRAFORM TEST - PROMQL %s" - description = "TERRAFORM TEST - PROMQL %s" - severity = 3 - - promql = "(elasticsearch_jvm_memory_used_bytes{area=\"heap\"} / elasticsearch_jvm_memory_max_bytes{area=\"heap\"}) * 100 > 80" - - trigger_after_minutes = 10 - - enabled = false -} -`, name, name) -} - -func alertPromqlWithGroupName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_promql" "sample" { - name = "TERRAFORM TEST - PROMQL %s" - description = "TERRAFORM TEST - PROMQL %s" - severity = 3 - group_name = "sample_group_name" - promql = "(elasticsearch_jvm_memory_used_bytes{area=\"heap\"} / elasticsearch_jvm_memory_max_bytes{area=\"heap\"}) * 100 > 80" - - trigger_after_minutes = 10 - - enabled = false -} -`, name, name) -} diff --git a/website/docs/r/monitor_alert_promql.md b/website/docs/r/monitor_alert_promql.md deleted file mode 100644 index 7c845366c..000000000 --- a/website/docs/r/monitor_alert_promql.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_promql" -description: |- - Creates a Sysdig Monitor Prometheus Alert. ---- - -# Resource: sysdig_monitor_alert_promql - -Creates a Sysdig Monitor Prometheus Alert. Monitor prometheus metrics and alert if they violate user-defined PromQL-based metric expression. - -~> **Deprecation Notice:** `sysdig_monitor_alert_promql` has been deprecated and will be removed in future releases, use `sysdig_monitor_alert_v2_prometheus` instead. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_promql" "sample" { - name = "Elasticsearch JVM heap usage" - description = "Elasticsearch JVM heap used over attention threshold" - severity = 6 - - promql = "(elasticsearch_jvm_memory_used_bytes{area=\"heap\"} / elasticsearch_jvm_memory_max_bytes{area=\"heap\"}) * 100 > 80" - trigger_after_minutes = 10 -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Prometheus alert arguments - -* `promql` - (Required) PromQL-based metric expression to alert on. Example: `histogram_quantile(0.99, rate(etcd_http_successful_duration_seconds_bucket[5m]) > 0.15` or `predict_linear(sysdig_fs_free_bytes{fstype!~"tmpfs"}[1h], 24*3600) < 10000000000`. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - - -## Import - -Prometheus alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_promql.example 12345 -``` From 5c1583e462d727ec8c6c87754cde088c39aef9ae Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:34:55 +0200 Subject: [PATCH 13/25] refactor!: remove deprecated sysdig_monitor_alert_group_outlier resource --- ...urce_sysdig_monitor_alert_group_outlier.go | 165 ------------------ sysdig/provider.go | 1 - ...sysdig_monitor_alert_group_outlier_test.go | 60 ------- website/docs/r/monitor_alert_group_outlier.md | 94 ---------- 4 files changed, 320 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_group_outlier.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_group_outlier_test.go delete mode 100644 website/docs/r/monitor_alert_group_outlier.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_group_outlier.go b/sysdig/deprecated_resource_sysdig_monitor_alert_group_outlier.go deleted file mode 100644 index 13e1f287b..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_group_outlier.go +++ /dev/null @@ -1,165 +0,0 @@ -package sysdig - -import ( - "context" - "strconv" - "time" - - 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" -) - -func deprecatedResourceSysdigMonitorAlertGroupOutlier() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "Group Outlier Alerts have been deprecated, \"sysdig_monitor_alert_group_outlier\" will be removed in future releases", - CreateContext: deprecatedResourceSysdigAlertGroupOutlierCreate, - UpdateContext: deprecatedResourceSysdigAlertGroupOutlierUpdate, - ReadContext: deprecatedResourceSysdigAlertGroupOutlierRead, - DeleteContext: deprecatedResourceSysdigAlertGroupOutlierDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "monitor": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }), - } -} - -func deprecatedResourceSysdigAlertGroupOutlierCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedGroupOutlierAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - - return nil -} - -func deprecatedResourceSysdigAlertGroupOutlierUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedGroupOutlierAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertGroupOutlierRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedGroupOutlierAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertGroupOutlierDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedGroupOutlierAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(data) - if err != nil { - return - } - - alert.Type = "HOST_COMPARISON" - - for _, metric := range data.Get("monitor").([]any) { - alert.Monitor = append(alert.Monitor, &v2.Monitor{ - Metric: metric.(string), - StdDevFactor: 2, - }) - } - - alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - alert.SegmentBy = []string{"host.mac"} - - return -} - -func deprecatedGroupOutlierAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - monitorMetrics := []string{} - for _, v := range alert.Monitor { - monitorMetrics = append(monitorMetrics, v.Metric) - } - _ = data.Set("monitor", monitorMetrics) - - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index 9d4cff327..285fe0357 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -125,7 +125,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_user": resourceSysdigUser(), "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), - "sysdig_monitor_alert_group_outlier": deprecatedResourceSysdigMonitorAlertGroupOutlier(), "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), "sysdig_monitor_alert_v2_downtime": resourceSysdigMonitorAlertV2Downtime(), diff --git a/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go b/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go deleted file mode 100644 index a942142c5..000000000 --- a/sysdig/resource_sysdig_monitor_alert_group_outlier_test.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertGroupOutlier(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertGroupOutlierWithName(rText()), - }, - { - ResourceName: "sysdig_monitor_alert_group_outlier.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func alertGroupOutlierWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_group_outlier" "sample" { - name = "TERRAFORM TEST - GROUP OUTLIER %s" - description = "TERRAFORM TEST - GROUP OUTLIER %s" - severity = 6 - - monitor = ["cpu.cores.used", "cpu.cores.used.percent", "cpu.stolen.percent", "cpu.used.percent"] - - scope = "kubernetes.cluster.name in (\"pulsar\")" - - trigger_after_minutes = 10 - - enabled = false - - capture { - filename = "TERRAFORM_TEST.scap" - duration = 15 - } -} -`, name, name) -} diff --git a/website/docs/r/monitor_alert_group_outlier.md b/website/docs/r/monitor_alert_group_outlier.md deleted file mode 100644 index 6a55b51e4..000000000 --- a/website/docs/r/monitor_alert_group_outlier.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_group_outlier" -description: |- - Creates a Sysdig Monitor Group Outlier Alert. ---- - -# Resource: sysdig_monitor_alert_group_outlier - -Creates a Sysdig Monitor Group Outlier Alert. Monitor a group of hosts and be notified when one acts differently from the rest. - -~> **Deprecation Notice:** Group Outlier Alerts have been deprecated in Sysdig Monitor, `sysdig_monitor_alert_group_outlier` will be removed in future releases, consider rewriting the resource as a promql alert. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_group_outlier" "sample" { - name = "[Kubernetes] A node is using more CPU than the rest" - description = "Monitors the cluster and checks when a node has more CPU usage than the others" - severity = 6 - - monitor = ["cpu.used.percent"] - - trigger_after_minutes = 10 - - capture { - filename = "TERRAFORM_TEST" - duration = 15 - } -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `scope` - (Optional) Part of the infrastructure where the alert is valid. Defaults to the entire infrastructure. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `capture` - (Optional) Enables the creation of a capture file of the syscalls during the event. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `capture` - -Enables the creation of a capture file of the syscalls during the event. - -* `filename` - (Required) Defines the name of the capture file. -* `duration` - (Required) Time frame in seconds of the capture. -* `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name contains nginx`. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Group Outlier alert arguments - -* `monitor` - (Required) Array of metrics to monitor and alert on. Example: `["cpu.used.percent", "cpu.cores.used", "memory.bytes.used", "fs.used.percent", "thread.count", "net.request.count.in"]`. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - - -## Import - -Group Outlier alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_group_outlier.example 12345 -``` From c05a4412784759ffc8648cae544a517a6168daa4 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:36:29 +0200 Subject: [PATCH 14/25] refactor!: remove deprecated sysdig_monitor_alert_event resource --- ...ted_resource_sysdig_monitor_alert_event.go | 203 ------------ sysdig/provider.go | 2 - .../resource_sysdig_monitor_alert_common.go | 292 ------------------ ...esource_sysdig_monitor_alert_event_test.go | 59 ---- website/docs/r/monitor_alert_event.md | 100 ------ 5 files changed, 656 deletions(-) delete mode 100644 sysdig/deprecated_resource_sysdig_monitor_alert_event.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_common.go delete mode 100644 sysdig/resource_sysdig_monitor_alert_event_test.go delete mode 100644 website/docs/r/monitor_alert_event.md diff --git a/sysdig/deprecated_resource_sysdig_monitor_alert_event.go b/sysdig/deprecated_resource_sysdig_monitor_alert_event.go deleted file mode 100644 index d7325b8c7..000000000 --- a/sysdig/deprecated_resource_sysdig_monitor_alert_event.go +++ /dev/null @@ -1,203 +0,0 @@ -package sysdig - -import ( - "context" - "fmt" - "regexp" - "strconv" - "time" - - 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" -) - -func deprecatedResourceSysdigMonitorAlertEvent() *schema.Resource { - timeout := 5 * time.Minute - - return &schema.Resource{ - DeprecationMessage: "\"sysdig_monitor_alert_event\" has been deprecated and will be removed in future releases, use \"sysdig_monitor_alert_v2_event\" instead", - CreateContext: deprecatedResourceSysdigAlertEventCreate, - UpdateContext: deprecatedResourceSysdigAlertEventUpdate, - ReadContext: deprecatedResourceSysdigAlertEventRead, - DeleteContext: deprecatedResourceSysdigAlertEventDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(timeout), - Update: schema.DefaultTimeout(timeout), - Read: schema.DefaultTimeout(timeout), - Delete: schema.DefaultTimeout(timeout), - }, - - Schema: createAlertSchema(map[string]*schema.Schema{ - "event_name": { - Type: schema.TypeString, - Required: true, - }, - "source": { - Type: schema.TypeString, - Required: true, - }, - "event_rel": { - Type: schema.TypeString, - Required: true, - }, - "event_count": { - Type: schema.TypeInt, - Required: true, - }, - "multiple_alerts_by": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }), - } -} - -func deprecatedResourceSysdigAlertEventCreate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedEventAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alertCreated, err := client.CreateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - data.SetId(strconv.Itoa(alertCreated.ID)) - _ = data.Set("version", alertCreated.Version) - - return nil -} - -func deprecatedResourceSysdigAlertEventUpdate(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - alert, err := deprecatedEventAlertFromResourceData(data) - if err != nil { - return diag.FromErr(err) - } - - alert.ID, _ = strconv.Atoi(data.Id()) - - _, err = client.UpdateAlert(ctx, *alert) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertEventRead(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - alert, err := client.GetAlertByID(ctx, id) - if err != nil { - data.SetId("") - return nil - } - - err = deprecatedEventAlertToResourceData(&alert, data) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedResourceSysdigAlertEventDelete(ctx context.Context, data *schema.ResourceData, i any) diag.Diagnostics { - client, err := getMonitorAlertClient(i.(SysdigClients)) - if err != nil { - return diag.FromErr(err) - } - - id, err := strconv.Atoi(data.Id()) - if err != nil { - return diag.FromErr(err) - } - - err = client.DeleteAlertByID(ctx, id) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func deprecatedEventAlertFromResourceData(data *schema.ResourceData) (alert *v2.Alert, err error) { - alert, err = alertFromResourceData(data) - if err != nil { - return - } - - 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 alertsBy, ok := data.GetOk("multiple_alerts_by"); ok { - alert.SegmentCondition = &v2.SegmentCondition{Type: "ANY"} - for _, v := range alertsBy.([]any) { - alert.SegmentBy = append(alert.SegmentBy, v.(string)) - } - } - - return -} - -// https://regex101.com/r/79VIkC/1 -var deprecatedAlertConditionRegex = regexp.MustCompile(`count\(customEvent\)\s*(?P[^\w\s]+)\s*(?P\d+)`) - -func deprecatedEventAlertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - err = alertToResourceData(alert, data) - if err != nil { - return - } - - relIndex := deprecatedAlertConditionRegex.SubexpIndex("rel") - countIndex := deprecatedAlertConditionRegex.SubexpIndex("count") - matches := deprecatedAlertConditionRegex.FindStringSubmatch(alert.Condition) - if matches == nil { - return fmt.Errorf("alert condition %s does not match expected expression %s", alert.Condition, deprecatedAlertConditionRegex.String()) - } - - eventRel := matches[relIndex] - eventCount, err := strconv.Atoi(matches[countIndex]) - if err != nil { - return - } - - _ = 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) - - return -} diff --git a/sysdig/provider.go b/sysdig/provider.go index 285fe0357..67dfe93a4 100644 --- a/sysdig/provider.go +++ b/sysdig/provider.go @@ -124,8 +124,6 @@ func (p *SysdigProvider) Provider() *schema.Provider { "sysdig_team_service_account": resourceSysdigTeamServiceAccount(), "sysdig_user": resourceSysdigUser(), - "sysdig_monitor_alert_event": deprecatedResourceSysdigMonitorAlertEvent(), - "sysdig_monitor_alert_v2_change": resourceSysdigMonitorAlertV2Change(), "sysdig_monitor_alert_v2_downtime": resourceSysdigMonitorAlertV2Downtime(), "sysdig_monitor_alert_v2_event": resourceSysdigMonitorAlertV2Event(), diff --git a/sysdig/resource_sysdig_monitor_alert_common.go b/sysdig/resource_sysdig_monitor_alert_common.go deleted file mode 100644 index ba7c14797..000000000 --- a/sysdig/resource_sysdig_monitor_alert_common.go +++ /dev/null @@ -1,292 +0,0 @@ -package sysdig - -import ( - "errors" - "maps" - "regexp" - "strings" - "time" - - v2 "github.com/draios/terraform-provider-sysdig/sysdig/internal/client/v2" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -const defaultAlertTitle = "{{__alert_name__}} is {{__alert_status__}}" - -func createAlertSchema(original map[string]*schema.Schema) map[string]*schema.Schema { - alertSchema := map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "description": { - Type: schema.TypeString, - Optional: true, - }, - "severity": { - Type: schema.TypeInt, - Optional: true, - Default: 4, - ValidateFunc: validation.IntBetween(0, 7), - }, - "trigger_after_minutes": { - Type: schema.TypeInt, - Required: true, - }, - "scope": { - Type: schema.TypeString, - Optional: true, - Default: "", - }, - "version": { - Type: schema.TypeInt, - Computed: true, - }, - "group_name": { - Type: schema.TypeString, - Optional: true, - Default: "default", - DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { - return strings.EqualFold(old, new) - }, - }, - "team": { - Type: schema.TypeInt, - Computed: true, - }, - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - "notification_channels": { - Type: schema.TypeSet, - Elem: &schema.Schema{Type: schema.TypeInt}, - Optional: true, - }, - "renotification_minutes": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: validation.IntAtLeast(1), - }, - "custom_notification": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "title": { - Type: schema.TypeString, - Required: true, - }, - "prepend": { - Type: schema.TypeString, - Optional: true, - }, - "append": { - Type: schema.TypeString, - Optional: true, - }, - }, - }, - }, - "capture": { - Type: schema.TypeSet, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "filename": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`.*?\.scap`), "the filename must end in .scap"), - }, - "duration": { - Type: schema.TypeInt, - Required: true, - }, - "filter": { - Type: schema.TypeString, - Optional: true, - Default: "", - }, - }, - }, - }, - } - - maps.Copy(alertSchema, original) - - return alertSchema -} - -func alertFromResourceData(d *schema.ResourceData) (alert *v2.Alert, err error) { - 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", - Timespan: ×pan, - SegmentBy: []string{}, - NotificationChannelIds: []int{}, - CustomNotification: &v2.CustomNotification{ - TitleTemplate: defaultAlertTitle, - UseNewTemplate: true, - }, - } - - if _, ok := d.GetOk("custom_notification"); ok { - if title, ok := d.GetOk("custom_notification.0.title"); ok { - alert.CustomNotification.TitleTemplate = title.(string) - } - if prependText, ok := d.GetOk("custom_notification.0.prepend"); ok { - alert.CustomNotification.PrependText = prependText.(string) - } - if appendText, ok := d.GetOk("custom_notification.0.append"); ok { - alert.CustomNotification.AppendText = appendText.(string) - } - } - - if scope, ok := d.GetOk("scope"); ok { - alert.Filter = scope.(string) - } - - if description, ok := d.GetOk("description"); ok { - alert.Description = description.(string) - } - if groupName, ok := d.GetOk("group_name"); ok { - alert.GroupName = strings.ToLower(groupName.(string)) - } - if version, ok := d.GetOk("version"); ok { - alert.Version = version.(int) - } - if team, ok := d.GetOk("team"); ok { - alert.TeamID = team.(int) - } - if enabled, ok := d.GetOk("enabled"); ok { - alert.Enabled = enabled.(bool) - } - - if channels, ok := d.GetOk("notification_channels"); ok { - channelSet := channels.(*schema.Set) - for _, channel := range channelSet.List() { - alert.NotificationChannelIds = append(alert.NotificationChannelIds, channel.(int)) - } - } - - if renotificationMinutes, ok := d.GetOk("renotification_minutes"); ok { - alert.ReNotify = true - alert.ReNotifyMinutes = renotificationMinutes.(int) - } else { - alert.ReNotify = false - alert.ReNotifyMinutes = 1 // Required by the API to be higher than 0 even if the re notification is not set - } - - if set, ok := d.GetOk("capture"); ok { - captures, err := sysdigCaptureFromSet(set.(*schema.Set)) - if err != nil { - return nil, err - } - if len(captures) == 0 { - err = errors.New("capture set is empty") - return nil, err - } - alert.SysdigCapture = captures[0] - } - - alert.Severity = d.Get("severity").(int) - - return -} - -func alertToResourceData(alert *v2.Alert, data *schema.ResourceData) (err error) { - var triggerAfterMinutes int - if alert.Timespan != nil { - 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", triggerAfterMinutes) - _ = data.Set("group_name", alert.GroupName) - _ = data.Set("team", alert.TeamID) - _ = data.Set("enabled", alert.Enabled) - _ = data.Set("severity", alert.Severity) - - if len(alert.NotificationChannelIds) > 0 { - _ = data.Set("notification_channels", alert.NotificationChannelIds) - } - - if alert.ReNotify { - _ = data.Set("renotification_minutes", alert.ReNotifyMinutes) - } - - if alert.CustomNotification != nil && - (alert.CustomNotification.TitleTemplate != defaultAlertTitle || alert.CustomNotification.AppendText != "" || alert.CustomNotification.PrependText != "") { - customNotification := map[string]any{ - "title": alert.CustomNotification.TitleTemplate, - } - - if alert.CustomNotification.AppendText != "" { - customNotification["append"] = alert.CustomNotification.AppendText - } - - if alert.CustomNotification.PrependText != "" { - customNotification["prepend"] = alert.CustomNotification.PrependText - } - - _ = data.Set("custom_notification", []any{customNotification}) - } - - if alert.SysdigCapture != nil && alert.SysdigCapture.Enabled { - capture := map[string]any{ - "filename": alert.SysdigCapture.Name, - "duration": alert.SysdigCapture.Duration, - } - if alert.SysdigCapture.Filters != "" { - capture["filters"] = alert.SysdigCapture.Filters - } - _ = data.Set("capture", []any{capture}) - } - - return -} - -func sysdigCaptureFromSet(d *schema.Set) (captures []*v2.SysdigCapture, err error) { - for _, v := range d.List() { - m := v.(map[string]any) - capture := &v2.SysdigCapture{ - Name: m["filename"].(string), - Duration: m["duration"].(int), - Enabled: true, - } - if filter, ok := m["filter"]; ok { - capture.Filters = filter.(string) - } - captures = append(captures, capture) - } - - return -} - -func getMonitorAlertClient(c SysdigClients) (v2.AlertInterface, error) { - var client v2.AlertInterface - var err error - switch c.GetClientType() { - case IBMMonitor: - client, err = c.ibmMonitorClient() - if err != nil { - return nil, err - } - default: - client, err = c.sysdigMonitorClientV2() - if err != nil { - return nil, err - } - } - return client, nil -} diff --git a/sysdig/resource_sysdig_monitor_alert_event_test.go b/sysdig/resource_sysdig_monitor_alert_event_test.go deleted file mode 100644 index a9e715a88..000000000 --- a/sysdig/resource_sysdig_monitor_alert_event_test.go +++ /dev/null @@ -1,59 +0,0 @@ -//go:build tf_acc_sysdig_monitor || tf_acc_ibm_monitor || tf_acc_onprem_monitor - -package sysdig_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/draios/terraform-provider-sysdig/sysdig" -) - -func TestAccAlertEvent(t *testing.T) { - rText := func() string { return acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: preCheckAnyEnv(t, SysdigMonitorApiTokenEnv, SysdigIBMMonitorAPIKeyEnv), - ProviderFactories: map[string]func() (*schema.Provider, error){ - "sysdig": func() (*schema.Provider, error) { - return sysdig.Provider(), nil - }, - }, - Steps: []resource.TestStep{ - { - Config: alertEventWithName(rText()), - }, - { - ResourceName: "sysdig_monitor_alert_event.sample", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func alertEventWithName(name string) string { - return fmt.Sprintf(` -resource "sysdig_monitor_alert_event" "sample" { - name = "TERRAFORM TEST - EVENT %s" - description = "TERRAFORM TEST - EVENT %s" - severity = 4 - - event_name = "deployment" - source = "kubernetes" - event_rel = ">" - event_count = 2 - - multiple_alerts_by = ["kubernetes.deployment.name"] - scope = "kubernetes.cluster.name in (\"pulsar\")" - - trigger_after_minutes = 10 - - enabled = false -} -`, name, name) -} diff --git a/website/docs/r/monitor_alert_event.md b/website/docs/r/monitor_alert_event.md deleted file mode 100644 index e9d40203e..000000000 --- a/website/docs/r/monitor_alert_event.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -subcategory: "Sysdig Monitor" -layout: "sysdig" -page_title: "Sysdig: sysdig_monitor_alert_event" -description: |- - Creates a Sysdig Monitor Event Alert. ---- - -# Resource: sysdig_monitor_alert_event - -Creates a Sysdig Monitor Event Alert. Monitor occurrences of specific events, and alert if the total -number of occurrences violates a threshold. Useful for alerting on container, orchestration, and -service events like restarts and deployments. - -~> **Deprecation Notice:** `sysdig_monitor_alert_event` has been deprecated and will be removed in future releases, use `sysdig_monitor_alert_v2_event` instead. - --> **Note:** Sysdig Terraform Provider is under rapid development at this point. If you experience any issue or discrepancy while using it, please make sure you have the latest version. If the issue persists, or you have a Feature Request to support an additional set of resources, please open a [new issue](https://github.com/sysdiglabs/terraform-provider-sysdig/issues/new) in the GitHub repository. - -## Example Usage - -```terraform -resource "sysdig_monitor_alert_event" "sample" { - name = "[Kubernetes] Failed to pull image" - description = "A Kubernetes pod failed to pull an image from the registry" - severity = 4 - - event_name = "Failed to pull image" - source = "kubernetes" - event_rel = ">" - event_count = 0 - - multiple_alerts_by = ["kubernetes.pod.name"] - - trigger_after_minutes = 1 -} -``` - -## Argument Reference - -### Common alert arguments - -These arguments are common to all alerts in Sysdig Monitor. - -* `name` - (Required) The name of the Monitor alert. It must be unique. -* `description` - (Optional) The description of Monitor alert. -* `severity` - (Optional) Severity of the Monitor alert. It must be a value between 0 and 7, - with 0 being the most critical and 7 the less critical. Defaults to 4. -* `trigger_after_minutes` - (Required) Threshold of time for the status to stabilize until the alert is fired. -* `scope` - (Optional) Part of the infrastructure where the alert is valid. Defaults to the entire infrastructure. -* `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Defaults to true. -* `group_name` - (Optional) Lowercase string to group alerts in the UI -* `notification_channels` - (Optional) List of notification channel IDs where an alert must be sent to once fired. -* `renotification_minutes` - (Optional) Number of minutes for the alert to re-notify until the status is solved. -* `capture` - (Optional) Enables the creation of a capture file of the syscalls during the event. -* `custom_notification` - (Optional) Allows to define a custom notification title, prepend and append text. - -### `capture` - -Enables the creation of a capture file of the syscalls during the event. - -* `filename` - (Required) Defines the name of the capture file. -* `duration` - (Required) Time frame in seconds of the capture. -* `filter` - (Optional) Additional filter to apply to the capture. For example: `proc.name contains nginx`. - -### `custom_notification` - -By defining this field, the user can modify the title and the body of the message sent when the alert is fired. - -* `title` - (Required) Sets the title of the alert. It is commonly defined as `{{__alert_name__}} is {{__alert_status__}}`. -* `prepend` - (Optional) Text to add before the alert template. -* `append` - (Optional) Text to add after the alert template. - -### Event alert arguments - -* `event_name` - (Required) String that matches part of name, tag or the description of Sysdig Events. -* `source` - (Required) Source of the event. It can be `docker` or `kubernetes`. -* `event_rel` - (Required) Relationship of the event count. It can be `>`, `>=`, `<`, `<=`, `=` or `!=`. -* `event_count` - (Required) Number of events to match with event_rel. -* `multiple_alerts_by` - (Optional) List of segments to trigger a separate alert on. Example: `["kubernetes.cluster.name", "kubernetes.namespace.name"]`. - -## Attributes Reference - -In addition to all arguments above, the following attributes are exported: - -### Common alert attributes - -In addition to all arguments above, the following attributes are exported, which are common to all the alerts in Sysdig Monitor: - -* `id` - ID of the alert created. -* `version` - Current version of the resource in Sysdig Monitor. -* `team` - Team ID that owns the alert. - - -## Import - -Event alerts can be imported using the alert ID, e.g. - -``` -$ terraform import sysdig_monitor_alert_event.example 12345 -``` From 389f1860aa3d68af62c541b3cffcd9e5790eae79 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:41:37 +0200 Subject: [PATCH 15/25] refactor(secure_team): remove deprecated IBM platform metrics fields --- sysdig/resource_sysdig_secure_team.go | 28 --------------------------- 1 file changed, 28 deletions(-) diff --git a/sysdig/resource_sysdig_secure_team.go b/sysdig/resource_sysdig_secure_team.go index 3580d6837..95a6982f2 100644 --- a/sysdig/resource_sysdig_secure_team.go +++ b/sysdig/resource_sysdig_secure_team.go @@ -71,16 +71,6 @@ func resourceSysdigSecureTeam() *schema.Resource { Type: schema.TypeString, Optional: true, }, - "enable_ibm_platform_metrics": { - Type: schema.TypeBool, - Optional: true, - Deprecated: "This option should be not used anymore and will be removed in the future", - }, - "ibm_platform_metrics": { - Type: schema.TypeString, - Optional: true, - Deprecated: "This option should be not used anymore and will be removed in the future", - }, "use_sysdig_capture": { Type: schema.TypeBool, Optional: true, @@ -216,13 +206,6 @@ func resourceSysdigSecureTeamRead(ctx context.Context, d *schema.ResourceData, m return diag.FromErr(err) } - var ibmPlatformMetrics *string - if t.NamespaceFilters != nil { - ibmPlatformMetrics = t.NamespaceFilters.IBMPlatformMetrics - } - _ = d.Set("enable_ibm_platform_metrics", t.CanUseBeaconMetrics) - _ = d.Set("ibm_platform_metrics", ibmPlatformMetrics) - return nil } @@ -313,16 +296,5 @@ func secureTeamFromResourceData(d *schema.ResourceData) v2.Team { t.ZoneIDs[i] = z.(int) } - canUseBeaconMetrics := d.Get("enable_ibm_platform_metrics").(bool) - t.CanUseBeaconMetrics = &canUseBeaconMetrics - - if v, ok := d.GetOk("ibm_platform_metrics"); ok { - metrics := v.(string) - if t.NamespaceFilters == nil { - t.NamespaceFilters = &v2.NamespaceFilters{} - } - t.NamespaceFilters.IBMPlatformMetrics = &metrics - } - return t } From d1f6b2d0af35b9eb6a5b6860ed36d275faf94f86 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:43:30 +0200 Subject: [PATCH 16/25] refactor(monitor_alert_v2): remove deprecated trigger_after_minutes field --- ...esource_sysdig_monitor_alert_v2_downtime.go | 18 ------------------ website/docs/r/monitor_alert_v2_downtime.md | 3 +-- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_downtime.go b/sysdig/resource_sysdig_monitor_alert_v2_downtime.go index f353b8453..33721b52e 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_downtime.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_downtime.go @@ -32,18 +32,10 @@ func resourceSysdigMonitorAlertV2Downtime() *schema.Resource { }, Schema: createScopedSegmentedAlertV2Schema(createAlertV2Schema(map[string]*schema.Schema{ - "trigger_after_minutes": { - Type: schema.TypeInt, - Optional: true, - Computed: true, // computed if range_seconds is defined - Deprecated: "Use range_seconds instead", - ValidateFunc: validation.IntAtLeast(1), - }, "range_seconds": { Type: schema.TypeInt, Optional: true, Computed: true, // computed if trigger_after_minutes is defined - ExactlyOneOf: []string{"trigger_after_minutes"}, ValidateFunc: validation.IntAtLeast(60), }, "threshold": { @@ -189,15 +181,6 @@ func buildAlertV2DowntimeStruct(d *schema.ResourceData) *v2.AlertV2Downtime { config.Range = d.Get("range_seconds").(int) } - if d.HasChange("trigger_after_minutes") { - // GetOk returns true even if the value is stored only in the state and not in the user config: - // to avoid applying a trigger_after_minutes old value from the state even if the user removed it from the config - // we use HasChange that is true only if the user has changed (or created) it - and so it must be in the config - if attr, ok := d.GetOk("trigger_after_minutes"); ok && attr != nil { - config.Range = minutesToSeconds(d.Get("trigger_after_minutes").(int)) - } - } - var unreportedAlertNotificationsRetentionSec *int if unreportedAlertNotificationsRetentionSecInterface, ok := d.GetOk("unreported_alert_notifications_retention_seconds"); ok { u := unreportedAlertNotificationsRetentionSecInterface.(int) @@ -223,7 +206,6 @@ func updateAlertV2DowntimeState(d *schema.ResourceData, alert *v2.AlertV2Downtim return err } - _ = d.Set("trigger_after_minutes", secondsToMinutes(alert.Config.Range)) _ = d.Set("range_seconds", alert.Config.Range) _ = d.Set("threshold", (1-alert.Config.Threshold)*100) diff --git a/website/docs/r/monitor_alert_v2_downtime.md b/website/docs/r/monitor_alert_v2_downtime.md index 4c21cd3f1..b5e3ad0fd 100644 --- a/website/docs/r/monitor_alert_v2_downtime.md +++ b/website/docs/r/monitor_alert_v2_downtime.md @@ -47,8 +47,7 @@ These arguments are common to all alerts in Sysdig Monitor. * `name` - (Required) The name of the alert rule. It must be unique. * `description` - (Optional) The description of Monitor alert. -* `range_seconds` - (Optional, required if `trigger_after_minutes` is not defined): The rolling time aggregation period in which the relevant metric data is evaluated. -* `trigger_after_minutes` - (Optional, Deprecated) The rolling time aggregation period in which the relevant metric data is evaluated. Deprecated: use `range_seconds` instead. +* `range_seconds` - (Optional): The rolling time aggregation period in which the relevant metric data is evaluated. * `group` - (Optional) Used to group alert rules in the UI. This value must be a lowercase string. * `severity` - (Optional) Severity of the Monitor alert. It must be `high`, `medium`, `low` or `info`. Default: `low`. * `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Default: `true`. From 5a3830567ecbe63227f059f11356a84481893813 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:44:15 +0200 Subject: [PATCH 17/25] refactor(monitor_alert_v2): remove deprecated type field from notification_channels --- sysdig/resource_sysdig_monitor_alert_v2_common.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_common.go b/sysdig/resource_sysdig_monitor_alert_v2_common.go index e1e28971b..cab9ee41e 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_common.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_common.go @@ -73,12 +73,6 @@ func createAlertV2Schema(original map[string]*schema.Schema) map[string]*schema. Type: schema.TypeInt, Required: true, }, - "type": { - Type: schema.TypeString, - Optional: true, // for retro compatibility, content will be discarded, remove this is the next major release - Default: "", - Deprecated: "no need to define \"type\" attribute anymore, please remove it", - }, "renotify_every_minutes": { Type: schema.TypeInt, Optional: true, From 41292b5b88d30f47634d1ba25379ae5174a947e1 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:45:39 +0200 Subject: [PATCH 18/25] refactor(monitor_alert_v2): remove deprecated trigger_after_minutes field --- .../resource_sysdig_monitor_alert_v2_event.go | 18 ------------------ website/docs/r/monitor_alert_v2_event.md | 3 +-- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_event.go b/sysdig/resource_sysdig_monitor_alert_v2_event.go index a9899416f..cbe07b8fa 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_event.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_event.go @@ -33,18 +33,10 @@ func resourceSysdigMonitorAlertV2Event() *schema.Resource { }, Schema: createScopedSegmentedAlertV2Schema(createAlertV2Schema(map[string]*schema.Schema{ - "trigger_after_minutes": { - Type: schema.TypeInt, - Optional: true, - Computed: true, // computed if range_seconds is defined - Deprecated: "Use range_seconds instead", - ValidateFunc: validation.IntAtLeast(1), - }, "range_seconds": { Type: schema.TypeInt, Optional: true, Computed: true, // computed if trigger_after_minutes is defined - ExactlyOneOf: []string{"trigger_after_minutes"}, ValidateFunc: validation.IntAtLeast(60), }, "operator": { @@ -217,15 +209,6 @@ func buildAlertV2EventStruct(d *schema.ResourceData) (*v2.AlertV2Event, error) { config.Range = d.Get("range_seconds").(int) } - if d.HasChange("trigger_after_minutes") { - // GetOk returns true even if the value is stored only in the state and not in the user config: - // to avoid applying a trigger_after_minutes old value from the state even if the user removed it from the config - // we use HasChange that is true only if the user has changed (or created) it - and so it must be in the config - if attr, ok := d.GetOk("trigger_after_minutes"); ok && attr != nil { - config.Range = minutesToSeconds(d.Get("trigger_after_minutes").(int)) - } - } - alert := &v2.AlertV2Event{ AlertV2Common: *alertV2Common, Config: config, @@ -244,7 +227,6 @@ func updateAlertV2EventState(d *schema.ResourceData, alert *v2.AlertV2Event) err return err } - _ = d.Set("trigger_after_minutes", secondsToMinutes(alert.Config.Range)) _ = d.Set("range_seconds", alert.Config.Range) _ = d.Set("operator", alert.Config.ConditionOperator) diff --git a/website/docs/r/monitor_alert_v2_event.md b/website/docs/r/monitor_alert_v2_event.md index 96f9dbc96..4d801315a 100644 --- a/website/docs/r/monitor_alert_v2_event.md +++ b/website/docs/r/monitor_alert_v2_event.md @@ -57,8 +57,7 @@ These arguments are common to all alerts in Sysdig Monitor. * `name` - (Required) The name of the alert rule. It must be unique. * `description` - (Optional) The description of Monitor alert. -* `range_seconds` - (Optional, required if `trigger_after_minutes` is not defined): The time period in seconds over which to count events and trigger an alert if the total exceeds the threshold. -* `trigger_after_minutes` - (Optional, Deprecated) The time period in minutes over which to count events and trigger an alert if the total exceeds the threshold. Deprecated: use `range_seconds` instead. +* `range_seconds` - (Optional): The time period in seconds over which to count events and trigger an alert if the total exceeds the threshold. * `group` - (Optional) Used to group alert rules in the UI. This value must be a lowercase string. * `severity` - (Optional) Severity of the Monitor alert. It must be `high`, `medium`, `low` or `info`. Default: `low`. * `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Default: `true`. From 011548e4e330a028581e52fc934fbbbd668c3ae6 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:47:13 +0200 Subject: [PATCH 19/25] refactor(monitor_alert_v2): remove deprecated trigger_after_minutes field --- .../resource_sysdig_monitor_alert_v2_metric.go | 18 ------------------ website/docs/r/monitor_alert_v2_metric.md | 3 +-- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_metric.go b/sysdig/resource_sysdig_monitor_alert_v2_metric.go index ac7ef72fb..593d8bee0 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_metric.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_metric.go @@ -33,18 +33,10 @@ func resourceSysdigMonitorAlertV2Metric() *schema.Resource { }, Schema: createScopedSegmentedAlertV2Schema(createAlertV2Schema(map[string]*schema.Schema{ - "trigger_after_minutes": { - Type: schema.TypeInt, - Optional: true, - Computed: true, // computed if range_seconds is defined - Deprecated: "Use range_seconds instead", - ValidateFunc: validation.IntAtLeast(1), - }, "range_seconds": { Type: schema.TypeInt, Optional: true, Computed: true, // computed if trigger_after_minutes is defined - ExactlyOneOf: []string{"trigger_after_minutes"}, ValidateFunc: validation.IntAtLeast(60), }, "duration_seconds": { @@ -236,15 +228,6 @@ func buildAlertV2MetricStruct(d *schema.ResourceData) (*v2.AlertV2Metric, error) config.Range = d.Get("range_seconds").(int) } - if d.HasChange("trigger_after_minutes") { - // GetOk returns true even if the value is stored only in the state and not in the user config: - // to avoid applying a trigger_after_minutes old value from the state even if the user removed it from the config - // we use HasChange that is true only if the user has changed (or created) it - and so it must be in the config - if attr, ok := d.GetOk("trigger_after_minutes"); ok && attr != nil { - config.Range = minutesToSeconds(d.Get("trigger_after_minutes").(int)) - } - } - if attr, ok := d.GetOk("duration_seconds"); ok && attr != nil { config.Duration = d.Get("duration_seconds").(int) } @@ -276,7 +259,6 @@ func updateAlertV2MetricState(d *schema.ResourceData, alert *v2.AlertV2Metric) e return err } - _ = d.Set("trigger_after_minutes", secondsToMinutes(alert.Config.Range)) _ = d.Set("range_seconds", alert.Config.Range) _ = d.Set("duration_seconds", alert.Config.Duration) diff --git a/website/docs/r/monitor_alert_v2_metric.md b/website/docs/r/monitor_alert_v2_metric.md index 76a19c364..01484092a 100644 --- a/website/docs/r/monitor_alert_v2_metric.md +++ b/website/docs/r/monitor_alert_v2_metric.md @@ -73,8 +73,7 @@ These arguments are common to all alerts in Sysdig Monitor. * `name` - (Required) The name of the alert rule. It must be unique. * `description` - (Optional) The description of Monitor alert. -* `range_seconds` - (Optional, Required if `trigger_after_minutes` is not defined): The rolling time aggregation period in which the relevant metric data is evaluated. -* `trigger_after_minutes` - (Optional, Deprecated) The rolling time aggregation period in which the relevant metric data is evaluated. Deprecated: use `range_seconds` instead. +* `range_seconds` - (Optional): The rolling time aggregation period in which the relevant metric data is evaluated. * `duration_seconds` - (Optional) A time interval that defines for how long a condition should be met before an alert occurrence is created. * `group` - (Optional) Used to group alert rules in the UI. This value must be a lowercase string. * `severity` - (Optional) Severity of the Monitor alert. It must be `high`, `medium`, `low` or `info`. Default: `low`. From a85aec860b25cdceb5db5e2c4291cf4301b0ea45 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 09:50:11 +0200 Subject: [PATCH 20/25] refactor(monitor_alert_v2): remove deprecated trigger_after_minutes field --- ...ource_sysdig_monitor_alert_v2_prometheus.go | 18 ------------------ website/docs/r/monitor_alert_v2_prometheus.md | 3 +-- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go index b11518a8b..c94a2490f 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go @@ -32,18 +32,10 @@ func resourceSysdigMonitorAlertV2Prometheus() *schema.Resource { }, Schema: createAlertV2Schema(map[string]*schema.Schema{ - "trigger_after_minutes": { - Type: schema.TypeInt, - Optional: true, - Computed: true, // computed if duration_seconds is defined - Deprecated: "Use duration_seconds instead", - ValidateFunc: validation.IntAtLeast(0), - }, "duration_seconds": { Type: schema.TypeInt, Optional: true, Computed: true, // computed if trigger_after_minutes is defined - ConflictsWith: []string{"trigger_after_minutes"}, ValidateFunc: validation.IntAtLeast(0), }, "query": { @@ -171,15 +163,6 @@ func buildAlertV2PrometheusStruct(d *schema.ResourceData) *v2.AlertV2Prometheus config.Duration = d.Get("duration_seconds").(int) } - if d.HasChange("trigger_after_minutes") { - // GetOk returns true even if the value is stored only in the state and not in the user config: - // to avoid applying a trigger_after_minutes old value from the state even if the user removed it from the config - // we use HasChange that is true only if the user has changed (or created) it - and so it must be in the config - if attr, ok := d.GetOk("trigger_after_minutes"); ok && attr != nil { - config.Duration = minutesToSeconds(d.Get("trigger_after_minutes").(int)) - } - } - alert := &v2.AlertV2Prometheus{ AlertV2Common: *alertV2Common, Config: config, @@ -193,7 +176,6 @@ func updateAlertV2PrometheusState(d *schema.ResourceData, alert *v2.AlertV2Prome return } - _ = d.Set("trigger_after_minutes", secondsToMinutes(alert.Config.Duration)) _ = d.Set("duration_seconds", alert.Config.Duration) _ = d.Set("query", alert.Config.Query) diff --git a/website/docs/r/monitor_alert_v2_prometheus.md b/website/docs/r/monitor_alert_v2_prometheus.md index aae059700..4eab3b8b1 100644 --- a/website/docs/r/monitor_alert_v2_prometheus.md +++ b/website/docs/r/monitor_alert_v2_prometheus.md @@ -40,8 +40,7 @@ These arguments are common to all alerts in Sysdig Monitor. * `name` - (Required) The name of the alert rule. It must be unique. * `description` - (Optional) The description of Monitor alert. -* `duration_seconds` - (Optional, cannot be used with `trigger_after_minutes`) Specifies the amount of time, in seconds, that an alert condition must remain continuously true before the alert rule is triggered. -* `trigger_after_minutes` - (Optional, Deprecated, cannot be used with `duration_seconds`) Specifies the amount of time, in minutes, that an alert condition must remain continuously true before the alert rule is triggered. Deprecated: use `duration_seconds` instead. +* `duration_seconds` - (Optional) Specifies the amount of time, in seconds, that an alert condition must remain continuously true before the alert rule is triggered. * `group` - (Optional) Used to group alert rules in the UI. This value must be a lowercase string. * `severity` - (Optional) Severity of the Monitor alert. It must be `high`, `medium`, `low` or `info`. Default: `low`. * `enabled` - (Optional) Boolean that defines if the alert is enabled or not. Default: `true`. From d8215f166b901c208e54f7c1b6bf5b8dfdc663ec Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 10:20:45 +0200 Subject: [PATCH 21/25] docs: update documentation --- README.md | 9 +- docs/index.md | 280 +----------------------------------------- website/docs/index.md | 2 +- 3 files changed, 8 insertions(+), 283 deletions(-) diff --git a/README.md b/README.md index b37ad6a9b..db37cc1ae 100644 --- a/README.md +++ b/README.md @@ -21,13 +21,12 @@ ## Requirements -- [Terraform](https://www.terraform.io/downloads.html) > 0.12.x +- [Terraform](https://www.terraform.io/downloads.html) >= 1.0 is recommended (the provider supports > 0.12.x) - [Go](https://golang.org/doc/install) > Go version specified in [go.mod](./go.mod#L3) - - Correctly setup a [GOPATH](http://golang.org/doc/code.html#GOPATH), as well as adding `$GOPATH/bin` to your `$PATH`. ## Develop -First **clone** source repository to: `$GOPATH/src/github.com/draios/terraform-provider-sysdig` +First **clone** the source repository: ```sh $ git clone git@github.com:draios/terraform-provider-sysdig @@ -47,7 +46,7 @@ TL;DR; ## Compile -To **compile** the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory. +To **compile** the provider, run `make build`. This will build the provider and put the provider binary in the `$(go env GOPATH)/bin` directory, which should be in your `PATH`. ```sh $ make build @@ -82,7 +81,7 @@ terraform { required_providers { sysdig = { source = "local/sysdiglabs/sysdig" - version = "~> 1.0.0" + version = "~> 2.0.0" } } } diff --git a/docs/index.md b/docs/index.md index a4a2e60b4..5bc3ba54f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,277 +1,3 @@ - -> ⚠️ content deprecated, use https://docs.sysdig.com/en/docs/developer-tools/terraform-provider/ - -# Terraform Provider for Sysdig - -## Introduction - -### What is Terraform - -[Terraform](https://www.terraform.io/) is a tool for building, changing, and versioning infrastructure safely and efficiently. -Terraform can manage existing and popular service providers as well as custom in-house solutions. - -Configuration files describe to Terraform the components needed to run a single application or -your entire datacenter. Terraform generates an execution plan describing what it will do to reach the -desired state, and then executes it to build the described infrastructure or configuration. - -As the configuration changes, Terraform is able to determine what changed and create incremental execution -plans which can be applied. - -### Terraform Provider for Sysdig - -The Terraform Provider for Sysdig allows you to manage your configuration in Sysdig Secure -and Sysdig Monitor as code, allowing you to synchronize your declarative configuration with -the configuration at the Platform. - -You can instrument several use cases like: -- Backup/restore -- Disaster recovery -- Configuration version management - -## Installation - -To use the provider, first you need to install Terraform, which is the main executable that -interacts with the provider. - -Download the Terraform executable for your OS/Architecture from -here: [https://www.terraform.io/downloads.html](https://www.terraform.io/downloads.html) - - -### Terraform v0.13+ - -As of Terraform 0.13, the new block `required_providers` was added, -making it easier to use community providers, since they are automatically -downloaded from the Terraform Registry. - -You can tell Terraform to download and use `sysdiglabs/sysdig` as the `sysdig` -provider by defining this block in one of your .tf files. - -```hcl -terraform { - required_providers { - sysdig = { - source = "sysdiglabs/sysdig" - version = ">= 0.4.0" - } - } -} -``` - -### Terraform v0.12 - -In older Terraform versions, you need to download the -[latest version of the Terraform Provider for Sysdig](https://github.com/sysdiglabs/terraform-provider-sysdig/releases/latest) -for your OS/Architecture, extract it and move the executable under `$HOME/.terraform.d/plugins` (you need to create -this directory if it does not exist yet) as this link suggests: -[https://www.terraform.io/docs/configuration/providers.html#third-party-plugins](https://www.terraform.io/docs/configuration/providers.html#third-party-plugins) . - -## Usage example - -Terraform will use the Sysdig provider when you specify a [resource](https://www.terraform.io/docs/configuration/resources.html) -or [data source](https://www.terraform.io/docs/configuration/data-sources.html) with a name starting with `sysdig_*` (i.e.: `sysdig_user`) - -But in order to actually create valid requests to the API and create/update/remove those resources, -you need to specify a correct API token for the product. - -You can do so in 2 ways: -1. Using environment variables -2. Using a tfvars file. - -### Configure the provider: Using env vars - -You can configure the following environment variables to specify the API token: -- `SYSDIG_SECURE_API_TOKEN` -- `SYSDIG_MONITOR_API_TOKEN` - -For example: - -```sh -$ export SYSDIG_SECURE_API_TOKEN=323232323-3232-3232-32323232 -$ export SYSDIG_MONITOR_API_TOKEN=343434343-3434-3434-34343434 -``` - -Once you execute Terraform and apply the manifests, that env vars will be used to configure -the provider and create API calls. - -### Configure the provider: Using a tfvars file - -To use a [tfvars file](https://www.terraform.io/docs/configuration/variables.html#variable-definitions-tfvars-files) -you need to first create it, and specify the API tokens as [variables](https://www.terraform.io/docs/configuration/variables.html), for example: - -``` -# File: terraform.tfvars - -secure_token = "323232323-3232-3232-32323232" -monitor_token = "343434343-3434-3434-34343434" -``` - -Then, you can reference it in the [provider configuration block](https://www.terraform.io/docs/configuration/providers.html#provider-configuration): - -```hcl -provider "sysdig" { - sysdig_monitor_api_token = var.monitor_token - sysdig_secure_api_token = var.secure_token -} -``` - -### Creating resources with Terraform - -This is an example to create a pair of rules able to detect SSH connections and -shells spawned in containers. - -Start by defining a couple of rules in the `rules.tf` file. One rule will detect inbound and outbound connections -made to the port 22, and the other will detect a shell process being spawned. - -For more information about the configuration blocks, see: [https://www.terraform.io/docs/configuration/syntax.html](https://www.terraform.io/docs/configuration/syntax.html) - -```hcl -resource "sysdig_secure_rule_network" "disallowed_ssh_connection" { - name = "Disallowed SSH Connection detected" - description = "Detect any new ssh connection to a host" - tags = ["network"] - - block_inbound = true - block_outbound = true - - tcp { - matching = true - ports = [22] - } -} - -resource "sysdig_secure_rule_process" "terminal_shell" { - name = "Terminal shell detected" - description = "A shell was used as the entrypoint/exec point" - tags = ["shell"] - - processes = ["ash", "bash", "csh", "ksh", "sh", "tcsh", "zsh", "dash"] -} -``` - -Now create a policy in a file called `policy.tf` to define how these rules -are applied. The policy will stop the affected container and trigger a capture for -further troubleshooting. - -```hcl -resource "sysdig_secure_custom_policy" "terminal_shell_or_ssh_in_container" { - name = "Terminal shell or SSH detected in container" - description = "Detects a terminal shell or a ssh spawned in a container" - enabled = true - severity = 0 // HIGH - scope = "container.id != \"\"" - rules { - name = sysdig_secure_rule_network.disallowed_ssh_connection.name - } - rules { - name = sysdig_secure_rule_process.terminal_shell.name - } - - actions { - container = "stop" - capture { - seconds_before_event = 5 - seconds_after_event = 10 - } - } -} -``` - -With the given `scope`, the policy will only be applied to processes being executed inside containers: - -``` -scope = "container.id != \"\"" -``` - -Using `terraform apply` the resources are applied in the backend: - -![Terraform apply creates the resources](./assets/img/terraform-apply-create-sysdig-provider.png) - - Terraform tells us that is going to create 3 resources, which matches what we defined in `rules.tf` and `policy.tf`. - -![Terraform application completes successfully](./assets/img/terraform-apply-completed-sysdig-provider.png) - - After applying the plan, Terraform reports that the 3 resources have been successfully created. The policy uses the - rules created before, that’s why it’s the last one being created. - -The resources have been created, this is how they look in Sysdig Secure: - -![Terraform rules created in Sysdig Secure](./assets/img/terraform-rules-created-sysdig-secure.png) - -![Terraform policy created in Sysdig Secure](./assets/img/terraform-policy-created-sysdig-secure.png) - - But now the problem is that, if this policy triggers there's no alert notice unless notification channels are defined. -Creating two notification channels, one for the email and another one for slack in a file called `notification.tf`, -will alert us when the policy is triggered: - -```hcl -resource "sysdig_secure_notification_channel_email" "devops-email" { - name = "DevOps e-mail" - enabled = true - recipients = "devops@example.com" - notify_when_ok = false - notify_when_resolved = false -} - -resource "sysdig_secure_notification_channel_slack" "devops-slack" { - name = "DevOps Slack" - enabled = true - url = "https://hooks.slack.com/services/xxxxxx/xxxxxxx/xxxxxxxxxxx" - channel = "#devops" - notify_when_ok = false - notify_when_resolved = false -} -``` - -Bind them to the policy, modifying the file `policy.tf`; note the `notification_channels` property: - -```hcl -resource "sysdig_secure_custom_policy" "terminal_shell_or_ssh_in_container" { - name = "Terminal shell or SSH detected in container" - description = "Detects a terminal shell or a ssh spawned in a container" - enabled = true - severity = 0 // HIGH - scope = "container.id != \"\"" - rules { - name = sysdig_secure_rule_network.disallowed_ssh_connection.name - } - rules { - name = sysdig_secure_rule_process.terminal_shell.name - } - - actions { - container = "stop" - capture { - seconds_before_event = 5 - seconds_after_event = 10 - } - } - - notification_channels = [sysdig_secure_notification_channel_email.devops-email.id, - sysdig_secure_notification_channel_slack.devops-slack.id] -} -``` - -Finally, doing a `terraform apply`, it will inform that it will create 2 new resources and modify the existing policy: - -![Terraform apply updates the resources](./assets/img/terraform-apply-update-sysdig-provider.png) - - After inputting **yes**, Terraform will create the notification channels and bind them to the policy, - ensuring that the state in Monitor and Secure matches our state defined in the code. - -This is how the resources appear on the Sysdig Secure UI: - -![Terraform apply creates new notification channels](./assets/img/terraform-new-resources-notification-sysdig.png) - -![Terraform updates the policy resource](./assets/img/terraform-updated-resources-policy-sysdig.png) - -Now, if someone tries to update it manually, by re-applying the policies, Terraform will -restore the desired status from the `.tf` manifests. - -## Full Terraform resources documentation - -Check all the available resources and datasources for the Terraform Provider for Sysdig here: - -[Terraform provider for Sysdig Datasources](https://registry.terraform.io/providers/sysdiglabs/sysdig/latest/docs) - ---- -![Sysdig logo](./assets/img/sysdig-logo-220.png) +> ⚠️ This documentation is deprecated and will be removed in a future version. +> +> Please refer to the [official documentation on the Terraform Registry](https://registry.terraform.io/providers/sysdiglabs/sysdig/latest/docs). \ No newline at end of file diff --git a/website/docs/index.md b/website/docs/index.md index c1bff3ed6..999151ab6 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -30,7 +30,7 @@ terraform { required_providers { sysdig = { source = "sysdiglabs/sysdig" - version = ">=0.5" + version = ">=2.0.0" } } } From abc661e4cdb4e575b840bc707d23a78959ff64da Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 10:23:50 +0200 Subject: [PATCH 22/25] lint: execute pre-commit hooks --- sysdig/data_source_sysdig_fargate_ECS_test.go | 14 ++++++-------- sysdig/internal/client/v2/users.go | 4 ++-- .../resource_sysdig_monitor_alert_v2_prometheus.go | 12 ++++++------ sysdig/resource_sysdig_monitor_dashboard.go | 6 +++--- ...e_sysdig_monitor_notification_channel_common.go | 4 ++-- ..._monitor_notification_channel_custom_webhook.go | 8 ++++---- ...ce_sysdig_monitor_notification_channel_email.go | 8 ++++---- ...dig_monitor_notification_channel_google_chat.go | 8 ++++---- ..._notification_channel_ibm_event_notification.go | 8 ++++---- ..._sysdig_monitor_notification_channel_msteams.go | 8 ++++---- ...sysdig_monitor_notification_channel_opsgenie.go | 8 ++++---- ...ysdig_monitor_notification_channel_pagerduty.go | 8 ++++---- ...otification_channel_prometheus_alert_manager.go | 8 ++++---- ...ce_sysdig_monitor_notification_channel_slack.go | 8 ++++---- ...urce_sysdig_monitor_notification_channel_sns.go | 8 ++++---- ...sdig_monitor_notification_channel_team_email.go | 8 ++++---- ...ysdig_monitor_notification_channel_victorops.go | 8 ++++---- ..._sysdig_monitor_notification_channel_webhook.go | 8 ++++---- sysdig/resource_sysdig_monitor_team.go | 4 ++-- .../resource_sysdig_secure_custom_policy_test.go | 2 +- ...ce_sysdig_secure_notification_channel_common.go | 4 ++-- ...rce_sysdig_secure_notification_channel_email.go | 8 ++++---- ...e_sysdig_secure_notification_channel_msteams.go | 10 +++++----- ..._sysdig_secure_notification_channel_opsgenie.go | 8 ++++---- ...sysdig_secure_notification_channel_pagerduty.go | 8 ++++---- ...otification_channel_prometheus_alert_manager.go | 8 ++++---- ...rce_sysdig_secure_notification_channel_slack.go | 10 +++++----- ...ource_sysdig_secure_notification_channel_sns.go | 8 ++++---- ...ysdig_secure_notification_channel_team_email.go | 8 ++++---- ...sysdig_secure_notification_channel_victorops.go | 8 ++++---- ...e_sysdig_secure_notification_channel_webhook.go | 8 ++++---- sysdig/resource_sysdig_secure_rule_filesystem.go | 2 +- sysdig/resource_sysdig_secure_rule_network.go | 2 +- sysdig/resource_sysdig_secure_team.go | 2 +- 34 files changed, 121 insertions(+), 123 deletions(-) diff --git a/sysdig/data_source_sysdig_fargate_ECS_test.go b/sysdig/data_source_sysdig_fargate_ECS_test.go index 57ff7c84a..c0cf6c1cf 100644 --- a/sysdig/data_source_sysdig_fargate_ECS_test.go +++ b/sysdig/data_source_sysdig_fargate_ECS_test.go @@ -42,14 +42,12 @@ func sortAndCompare(t *testing.T, expected []byte, actual []byte) { // getKiltRecipe returns the default json Kilt recipe func getKiltRecipe(t *testing.T) string { recipeConfig := KiltRecipeConfig{ - SysdigAccessKey: "sysdig_access_key", - AgentImage: "workload_agent_image", - OrchestratorHost: "orchestrator_host", - OrchestratorPort: "orchestrator_port", - CollectorHost: "collector_host", - CollectorPort: "collector_port", - SysdigLogging: "sysdig_logging", - Priority: "priority", + SysdigAccessKey: "sysdig_access_key", + AgentImage: "workload_agent_image", + CollectorHost: "collector_host", + CollectorPort: "collector_port", + SysdigLogging: "sysdig_logging", + Priority: "priority", } jsonRecipeConfig, err := json.Marshal(&recipeConfig) diff --git a/sysdig/internal/client/v2/users.go b/sysdig/internal/client/v2/users.go index 1c3131de6..28e349fe0 100644 --- a/sysdig/internal/client/v2/users.go +++ b/sysdig/internal/client/v2/users.go @@ -152,7 +152,7 @@ func (c *Client) DeleteUser(ctx context.Context, id int) (err error) { 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 + return u, err } defer func() { if dErr := response.Body.Close(); dErr != nil { @@ -162,7 +162,7 @@ func (c *Client) GetCurrentUser(ctx context.Context) (u *User, err error) { if response.StatusCode != http.StatusOK { err = c.ErrorFromResponse(response) - return + return u, err } wrapper, err := Unmarshal[userWrapper](response.Body) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go index c94a2490f..896beddec 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_prometheus.go @@ -33,10 +33,10 @@ func resourceSysdigMonitorAlertV2Prometheus() *schema.Resource { Schema: createAlertV2Schema(map[string]*schema.Schema{ "duration_seconds": { - Type: schema.TypeInt, - Optional: true, - Computed: true, // computed if trigger_after_minutes is defined - ValidateFunc: validation.IntAtLeast(0), + Type: schema.TypeInt, + Optional: true, + Computed: true, // computed if trigger_after_minutes is defined + ValidateFunc: validation.IntAtLeast(0), }, "query": { Type: schema.TypeString, @@ -173,7 +173,7 @@ func buildAlertV2PrometheusStruct(d *schema.ResourceData) *v2.AlertV2Prometheus func updateAlertV2PrometheusState(d *schema.ResourceData, alert *v2.AlertV2Prometheus) (err error) { err = updateAlertV2CommonState(d, &alert.AlertV2Common) if err != nil { - return + return err } _ = d.Set("duration_seconds", alert.Config.Duration) @@ -186,5 +186,5 @@ func updateAlertV2PrometheusState(d *schema.ResourceData, alert *v2.AlertV2Prome _ = d.Set("keep_firing_for_minutes", nil) } - return + return err } diff --git a/sysdig/resource_sysdig_monitor_dashboard.go b/sysdig/resource_sysdig_monitor_dashboard.go index bd939c899..f52bc5a17 100644 --- a/sysdig/resource_sysdig_monitor_dashboard.go +++ b/sysdig/resource_sysdig_monitor_dashboard.go @@ -428,7 +428,7 @@ func sharingFromResourceData(data *schema.ResourceData) (sharingSettings []*v2.S Role: shareInfo["role"].(string), }) } - return + return sharingSettings, err } func panelsFromResourceData(data *schema.ResourceData) (panels []*v2.Panels, err error) { @@ -452,7 +452,7 @@ func panelsFromResourceData(data *schema.ResourceData) (panels []*v2.Panels, err panels = append(panels, panel) } - return + return panels, err } func defaultLegendConfiguration() *v2.LegendConfiguration { @@ -726,7 +726,7 @@ func queriesFromResourceData(panelInfo map[string]any, panel *v2.Panels) (newQue newQueries = append(newQueries, promqlQuery) } - return + return newQueries, err } func dashboardToResourceData(dashboard *v2.Dashboard, data *schema.ResourceData) (err error) { diff --git a/sysdig/resource_sysdig_monitor_notification_channel_common.go b/sysdig/resource_sysdig_monitor_notification_channel_common.go index c8dfcf903..b98c25a63 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_common.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_common.go @@ -66,7 +66,7 @@ func monitorNotificationChannelFromResourceData(d *schema.ResourceData, teamID i SendTestNotification: d.Get("send_test_notification").(bool), }, } - return + return nc, err } func monitorNotificationChannelToResourceData(nc *v2.NotificationChannel, data *schema.ResourceData) (err error) { @@ -86,7 +86,7 @@ func monitorNotificationChannelToResourceData(nc *v2.NotificationChannel, data * _ = data.Set("notify_when_resolved", nc.Options.NotifyOnResolve) // do not update "send_test_notification" from the api response as it will always be "false" on subsequent reads because the fields is not persisted - return + return err } func getMonitorNotificationChannelClient(c SysdigClients) (v2.NotificationChannelInterface, error) { diff --git a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go index 56c5d93be..8fde2ade9 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_custom_webhook.go @@ -156,7 +156,7 @@ func resourceSysdigMonitorNotificationChannelCustomWebhookDelete(ctx context.Con func monitorNotificationChannelCustomWebhookFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeCustomWebhook @@ -166,13 +166,13 @@ func monitorNotificationChannelCustomWebhookFromResourceData(d *schema.ResourceD nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections - return + return nc, err } func monitorNotificationChannelCustomWebhookToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -183,5 +183,5 @@ func monitorNotificationChannelCustomWebhookToResourceData(nc *v2.NotificationCh _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) } - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_email.go b/sysdig/resource_sysdig_monitor_notification_channel_email.go index bb01a7b1e..6a44fe228 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_email.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_email.go @@ -138,21 +138,21 @@ func resourceSysdigMonitorNotificationChannelEmailDelete(ctx context.Context, d func monitorNotificationChannelEmailFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeEmail nc.Options.EmailRecipients = cast.ToStringSlice(d.Get("recipients").(*schema.Set).List()) - return + return nc, err } func monitorNotificationChannelEmailToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("recipients", nc.Options.EmailRecipients) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go b/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go index 2648d8415..89c3660bf 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_google_chat.go @@ -145,21 +145,21 @@ func resourceSysdigMonitorNotificationChannelGoogleChatDelete(ctx context.Contex func monitorNotificationChannelGoogleChatFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeGChat nc.Options.URL = d.Get("url").(string) - return + return nc, err } func monitorNotificationChannelGoogleChatToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) - return + return err } 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 a3d2e3c69..cffebef12 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_ibm_event_notification.go @@ -145,21 +145,21 @@ func resourceSysdigMonitorNotificationChannelIBMEventNotificationDelete(ctx cont func monitorNotificationChannelIBMEventNotificationFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeIBMEventNotification nc.Options.InstanceID = d.Get("instance_id").(string) - return + return nc, err } func monitorNotificationChannelIBMEventNotificationToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("instance_id", nc.Options.InstanceID) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_msteams.go b/sysdig/resource_sysdig_monitor_notification_channel_msteams.go index 092f899a6..b8dd30469 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_msteams.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_msteams.go @@ -145,21 +145,21 @@ func resourceSysdigMonitorNotificationChannelMSTeamsDelete(ctx context.Context, func monitorNotificationChannelMSTeamsFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeMSTeams nc.Options.URL = d.Get("url").(string) - return + return nc, err } func monitorNotificationChannelMSTeamsToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go index 4270ef96b..f56682e84 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_opsgenie.go @@ -143,24 +143,24 @@ func resourceSysdigMonitorNotificationChannelOpsGenieDelete(ctx context.Context, func monitorNotificationChannelOpsGenieFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeOpsGenie apiKey := d.Get("api_key").(string) nc.Options.APIKey = apiKey nc.Options.Region = d.Get("region").(string) - return + return nc, err } func monitorNotificationChannelOpsGenieToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("api_key", nc.Options.APIKey) _ = d.Set("region", nc.Options.Region) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go index cf1e5b8c5..7da6a9122 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_pagerduty.go @@ -144,7 +144,7 @@ func resourceSysdigMonitorNotificationChannelPagerdutyDelete(ctx context.Context func monitorNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypePagerduty @@ -152,18 +152,18 @@ func monitorNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, nc.Options.ServiceKey = d.Get("service_key").(string) nc.Options.ServiceName = d.Get("service_name").(string) - return + return nc, err } func monitorNotificationChannelPagerdutyToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("account", nc.Options.Account) _ = d.Set("service_key", nc.Options.ServiceKey) _ = d.Set("service_name", nc.Options.ServiceName) - return + return err } 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 f8d9a3097..435861882 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_prometheus_alert_manager.go @@ -145,7 +145,7 @@ func resourceSysdigMonitorNotificationChannelPrometheusAlertManagerDelete(ctx co func monitorNotificationChannelPrometheusAlertManagerFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypePrometheusAlertManager @@ -153,13 +153,13 @@ func monitorNotificationChannelPrometheusAlertManagerFromResourceData(d *schema. nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections - return + return nc, err } func monitorNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -169,5 +169,5 @@ func monitorNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.Notif _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) } - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_slack.go b/sysdig/resource_sysdig_monitor_notification_channel_slack.go index f1b9b3409..1fff6f968 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_slack.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_slack.go @@ -198,7 +198,7 @@ func resourceSysdigMonitorNotificationChannelSlackDelete(ctx context.Context, d func monitorNotificationChannelSlackFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeSlack @@ -246,13 +246,13 @@ func monitorNotificationChannelSlackFromResourceData(d *schema.ResourceData, tea }, } - return + return nc, err } func monitorNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -297,5 +297,5 @@ func monitorNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d _ = d.Set("show_section_alert_details", alertDetails) _ = d.Set("show_section_capturing_information", capturingInformation) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_sns.go b/sysdig/resource_sysdig_monitor_notification_channel_sns.go index d31b7a1a4..9d21973c8 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_sns.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_sns.go @@ -137,21 +137,21 @@ func resourceSysdigMonitorNotificationChannelSNSDelete(ctx context.Context, d *s func monitorNotificationChannelSNSFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeAmazonSNS nc.Options.SnsTopicARNs = cast.ToStringSlice(d.Get("topics").(*schema.Set).List()) - return + return nc, err } func monitorNotificationChannelSNSToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("topics", nc.Options.SnsTopicARNs) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_team_email.go b/sysdig/resource_sysdig_monitor_notification_channel_team_email.go index eca0277a7..f65761137 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_team_email.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_team_email.go @@ -136,21 +136,21 @@ func resourceSysdigMonitorNotificationChannelTeamEmailDelete(ctx context.Context func monitorNotificationChannelTeamEmailFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeTeamEmail nc.Options.TeamID = d.Get("team_id").(int) - return + return nc, err } func monitorNotificationChannelTeamEmailToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("team_id", nc.Options.TeamID) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_victorops.go b/sysdig/resource_sysdig_monitor_notification_channel_victorops.go index 5ff6a92f1..cc472d881 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_victorops.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_victorops.go @@ -138,23 +138,23 @@ func resourceSysdigMonitorNotificationChannelVictorOpsDelete(ctx context.Context func monitorNotificationChannelVictorOpsFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeVictorOps nc.Options.APIKey = d.Get("api_key").(string) nc.Options.RoutingKey = d.Get("routing_key").(string) - return + return nc, err } func monitorNotificationChannelVictorOpsToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("api_key", nc.Options.APIKey) _ = d.Set("routing_key", nc.Options.RoutingKey) - return + return err } diff --git a/sysdig/resource_sysdig_monitor_notification_channel_webhook.go b/sysdig/resource_sysdig_monitor_notification_channel_webhook.go index ab15044cf..f4e0064fd 100644 --- a/sysdig/resource_sysdig_monitor_notification_channel_webhook.go +++ b/sysdig/resource_sysdig_monitor_notification_channel_webhook.go @@ -150,7 +150,7 @@ func resourceSysdigMonitorNotificationChannelWebhookDelete(ctx context.Context, func monitorNotificationChannelWebhookFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = monitorNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeWebhook @@ -159,13 +159,13 @@ func monitorNotificationChannelWebhookFromResourceData(d *schema.ResourceData, t nc.Options.CustomData = d.Get("custom_data").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections - return + return nc, err } func monitorNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = monitorNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -175,5 +175,5 @@ func monitorNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) } - return + return err } diff --git a/sysdig/resource_sysdig_monitor_team.go b/sysdig/resource_sysdig_monitor_team.go index a52044ba0..e06913191 100644 --- a/sysdig/resource_sysdig_monitor_team.go +++ b/sysdig/resource_sysdig_monitor_team.go @@ -228,12 +228,12 @@ func userMonitorRolesToSet(userRoles []v2.UserRoles) (res []map[string]any) { } res = append(res, roleMap) } - return + return res } func entrypointToSet(entrypoint *v2.EntryPoint) (res []map[string]any) { if entrypoint == nil { - return + return res } module := entrypoint.Module diff --git a/sysdig/resource_sysdig_secure_custom_policy_test.go b/sysdig/resource_sysdig_secure_custom_policy_test.go index cf80c8cb3..4c58b9ae5 100644 --- a/sysdig/resource_sysdig_secure_custom_policy_test.go +++ b/sysdig/resource_sysdig_secure_custom_policy_test.go @@ -220,7 +220,7 @@ resource "sysdig_secure_custom_policy" "sample_%d" { `, i, name, i, name, i, i) } - return + return res } func customPoliciesWithKillAction(name string) (res string) { diff --git a/sysdig/resource_sysdig_secure_notification_channel_common.go b/sysdig/resource_sysdig_secure_notification_channel_common.go index da8bd579d..ec0d63f7e 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_common.go +++ b/sysdig/resource_sysdig_secure_notification_channel_common.go @@ -66,7 +66,7 @@ func secureNotificationChannelFromResourceData(d *schema.ResourceData, teamID in SendTestNotification: d.Get("send_test_notification").(bool), }, } - return + return nc, err } func secureNotificationChannelToResourceData(nc *v2.NotificationChannel, data *schema.ResourceData) (err error) { @@ -86,7 +86,7 @@ func secureNotificationChannelToResourceData(nc *v2.NotificationChannel, data *s _ = data.Set("notify_when_resolved", nc.Options.NotifyOnResolve) // do not update "send_test_notification" from the api response as it will always be "false" on subsequent reads because the fields is not persisted - return + return err } func getSecureNotificationChannelClient(c SysdigClients) (v2.NotificationChannelInterface, error) { diff --git a/sysdig/resource_sysdig_secure_notification_channel_email.go b/sysdig/resource_sysdig_secure_notification_channel_email.go index e270e9127..cd6ad13cc 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_email.go +++ b/sysdig/resource_sysdig_secure_notification_channel_email.go @@ -138,21 +138,21 @@ func resourceSysdigSecureNotificationChannelEmailDelete(ctx context.Context, d * func secureNotificationChannelEmailFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeEmail nc.Options.EmailRecipients = cast.ToStringSlice(d.Get("recipients").(*schema.Set).List()) - return + return nc, err } func secureNotificationChannelEmailToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("recipients", nc.Options.EmailRecipients) - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_msteams.go b/sysdig/resource_sysdig_secure_notification_channel_msteams.go index e4054ca36..423aded15 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_msteams.go +++ b/sysdig/resource_sysdig_secure_notification_channel_msteams.go @@ -150,7 +150,7 @@ func resourceSysdigSecureNotificationChannelMSTeamsDelete(ctx context.Context, d func secureNotificationChannelMSTeamsFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeMSTeams @@ -158,7 +158,7 @@ func secureNotificationChannelMSTeamsFromResourceData(d *schema.ResourceData, te setNotificationChannelMSTeamsTemplateConfig(&nc, d) - return + return nc, err } func setNotificationChannelMSTeamsTemplateConfig(nc *v2.NotificationChannel, d *schema.ResourceData) { @@ -195,19 +195,19 @@ func setNotificationChannelMSTeamsTemplateConfig(nc *v2.NotificationChannel, d * func secureNotificationChannelMSTeamsToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) err = getTemplateVersionFromNotificationChannelMSTeams(nc, d) - return + return err } func getTemplateVersionFromNotificationChannelMSTeams(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { if len(nc.Options.TemplateConfiguration) == 0 { - return + return err } if len(nc.Options.TemplateConfiguration) > 1 { diff --git a/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go b/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go index 2b6ae82b6..62c45b898 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go +++ b/sysdig/resource_sysdig_secure_notification_channel_opsgenie.go @@ -143,24 +143,24 @@ func resourceSysdigSecureNotificationChannelOpsGenieDelete(ctx context.Context, func secureNotificationChannelOpsGenieFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeOpsGenie apiKey := d.Get("api_key").(string) nc.Options.APIKey = apiKey nc.Options.Region = d.Get("region").(string) - return + return nc, err } func secureNotificationChannelOpsGenieToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("api_key", nc.Options.APIKey) _ = d.Set("region", nc.Options.Region) - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go b/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go index 88c58ac5e..302c085b5 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go +++ b/sysdig/resource_sysdig_secure_notification_channel_pagerduty.go @@ -144,7 +144,7 @@ func resourceSysdigSecureNotificationChannelPagerdutyDelete(ctx context.Context, func secureNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypePagerduty @@ -152,18 +152,18 @@ func secureNotificationChannelPagerdutyFromResourceData(d *schema.ResourceData, nc.Options.ServiceKey = d.Get("service_key").(string) nc.Options.ServiceName = d.Get("service_name").(string) - return + return nc, err } func secureNotificationChannelPagerdutyToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("account", nc.Options.Account) _ = d.Set("service_key", nc.Options.ServiceKey) _ = d.Set("service_name", nc.Options.ServiceName) - return + return err } 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 e97b1ceb7..ac6fec27d 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go +++ b/sysdig/resource_sysdig_secure_notification_channel_prometheus_alert_manager.go @@ -146,7 +146,7 @@ func resourceSysdigSecureNotificationChannelPrometheusAlertManagerDelete(ctx con func secureNotificationChannelPrometheusAlertManagerFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypePrometheusAlertManager @@ -154,13 +154,13 @@ func secureNotificationChannelPrometheusAlertManagerFromResourceData(d *schema.R nc.Options.AdditionalHeaders = d.Get("additional_headers").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections - return + return nc, err } func secureNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -170,5 +170,5 @@ func secureNotificationChannelPrometheusAlertManagerToResourceData(nc *v2.Notifi _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) } - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_slack.go b/sysdig/resource_sysdig_secure_notification_channel_slack.go index 9d0931f82..a23a1aa8b 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_slack.go +++ b/sysdig/resource_sysdig_secure_notification_channel_slack.go @@ -168,7 +168,7 @@ func resourceSysdigSecureNotificationChannelSlackDelete(ctx context.Context, d * func secureNotificationChannelSlackFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeSlack @@ -179,7 +179,7 @@ func secureNotificationChannelSlackFromResourceData(d *schema.ResourceData, team setNotificationChannelSlackTemplateConfig(&nc, d) - return + return nc, err } func setNotificationChannelSlackTemplateConfig(nc *v2.NotificationChannel, d *schema.ResourceData) { @@ -216,7 +216,7 @@ func setNotificationChannelSlackTemplateConfig(nc *v2.NotificationChannel, d *sc func secureNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -226,12 +226,12 @@ func secureNotificationChannelSlackToResourceData(nc *v2.NotificationChannel, d err = getTemplateVersionFromNotificationChannelSlack(nc, d) - return + return err } func getTemplateVersionFromNotificationChannelSlack(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { if len(nc.Options.TemplateConfiguration) == 0 { - return + return err } if len(nc.Options.TemplateConfiguration) > 1 { diff --git a/sysdig/resource_sysdig_secure_notification_channel_sns.go b/sysdig/resource_sysdig_secure_notification_channel_sns.go index 460d0c4bc..b8a71a5a9 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_sns.go +++ b/sysdig/resource_sysdig_secure_notification_channel_sns.go @@ -137,21 +137,21 @@ func resourceSysdigSecureNotificationChannelSNSDelete(ctx context.Context, d *sc func secureNotificationChannelSNSFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeAmazonSNS nc.Options.SnsTopicARNs = cast.ToStringSlice(d.Get("topics").(*schema.Set).List()) - return + return nc, err } func secureNotificationChannelSNSToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("topics", nc.Options.SnsTopicARNs) - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_team_email.go b/sysdig/resource_sysdig_secure_notification_channel_team_email.go index dbc442b94..f66e5f9c9 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_team_email.go +++ b/sysdig/resource_sysdig_secure_notification_channel_team_email.go @@ -136,21 +136,21 @@ func resourceSysdigSecureNotificationChannelTeamEmailDelete(ctx context.Context, func secureNotificationChannelTeamEmailFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeTeamEmail nc.Options.TeamID = d.Get("team_id").(int) - return + return nc, err } func secureNotificationChannelTeamEmailToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("team_id", nc.Options.TeamID) - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_victorops.go b/sysdig/resource_sysdig_secure_notification_channel_victorops.go index f71acd195..0b0e82b12 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_victorops.go +++ b/sysdig/resource_sysdig_secure_notification_channel_victorops.go @@ -138,23 +138,23 @@ func resourceSysdigSecureNotificationChannelVictorOpsDelete(ctx context.Context, func secureNotificationChannelVictorOpsFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeVictorOps nc.Options.APIKey = d.Get("api_key").(string) nc.Options.RoutingKey = d.Get("routing_key").(string) - return + return nc, err } func secureNotificationChannelVictorOpsToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("api_key", nc.Options.APIKey) _ = d.Set("routing_key", nc.Options.RoutingKey) - return + return err } diff --git a/sysdig/resource_sysdig_secure_notification_channel_webhook.go b/sysdig/resource_sysdig_secure_notification_channel_webhook.go index a59a83268..0df0d1699 100644 --- a/sysdig/resource_sysdig_secure_notification_channel_webhook.go +++ b/sysdig/resource_sysdig_secure_notification_channel_webhook.go @@ -149,7 +149,7 @@ func resourceSysdigSecureNotificationChannelWebhookDelete(ctx context.Context, d func secureNotificationChannelWebhookFromResourceData(d *schema.ResourceData, teamID int) (nc v2.NotificationChannel, err error) { nc, err = secureNotificationChannelFromResourceData(d, teamID) if err != nil { - return + return nc, err } nc.Type = notificationChannelTypeWebhook @@ -158,13 +158,13 @@ func secureNotificationChannelWebhookFromResourceData(d *schema.ResourceData, te nc.Options.CustomData = d.Get("custom_data").(map[string]any) allowInsecureConnections := d.Get("allow_insecure_connections").(bool) nc.Options.AllowInsecureConnections = &allowInsecureConnections - return + return nc, err } func secureNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, d *schema.ResourceData) (err error) { err = secureNotificationChannelToResourceData(nc, d) if err != nil { - return + return err } _ = d.Set("url", nc.Options.URL) @@ -174,5 +174,5 @@ func secureNotificationChannelWebhookToResourceData(nc *v2.NotificationChannel, _ = d.Set("allow_insecure_connections", *nc.Options.AllowInsecureConnections) } - return + return err } diff --git a/sysdig/resource_sysdig_secure_rule_filesystem.go b/sysdig/resource_sysdig_secure_rule_filesystem.go index 3d609b1ea..17e65ce2a 100644 --- a/sysdig/resource_sysdig_secure_rule_filesystem.go +++ b/sysdig/resource_sysdig_secure_rule_filesystem.go @@ -224,5 +224,5 @@ func resourceSysdigRuleFilesystemFromResourceData(d *schema.ResourceData) (rule } } } - return + return rule, err } diff --git a/sysdig/resource_sysdig_secure_rule_network.go b/sysdig/resource_sysdig_secure_rule_network.go index 60c9f4223..4ed87a356 100644 --- a/sysdig/resource_sysdig_secure_rule_network.go +++ b/sysdig/resource_sysdig_secure_rule_network.go @@ -247,5 +247,5 @@ func resourceSysdigRuleNetworkFromResourceData(d *schema.ResourceData) (rule v2. } } - return + return rule, err } diff --git a/sysdig/resource_sysdig_secure_team.go b/sysdig/resource_sysdig_secure_team.go index 95a6982f2..1f8a66adb 100644 --- a/sysdig/resource_sysdig_secure_team.go +++ b/sysdig/resource_sysdig_secure_team.go @@ -220,7 +220,7 @@ func userSecureRolesToSet(userRoles []v2.UserRoles) (res []map[string]any) { } res = append(res, roleMap) } - return + return res } func resourceSysdigSecureTeamUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { From 8b8a52e7d4b3ec4ab654ae0f9e318ce09e494925 Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 13:03:10 +0200 Subject: [PATCH 23/25] fix(tests): update deprecated trigger_after_minutes Replaces the deprecated 'trigger_after_minutes' field with its correct counterparts ('duration_seconds' or 'range_seconds') across multiple alert test files. This change aligns the tests with the recent removal of the deprecated field, ensuring that the test suite passes and reflects the current resource schemas. --- ...e_sysdig_monitor_alert_v2_downtime_test.go | 2 +- ...urce_sysdig_monitor_alert_v2_event_test.go | 2 +- ...rce_sysdig_monitor_alert_v2_metric_test.go | 6 ++-- ...sysdig_monitor_alert_v2_prometheus_test.go | 2 +- ...source_sysdig_monitor_silence_rule_test.go | 28 +++++++++---------- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go b/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go index 960319e66..76c3302c8 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_downtime_test.go @@ -80,7 +80,7 @@ resource "sysdig_monitor_alert_v2_downtime" "sample" { values = ["thom-cluster1", "demo-env-prom"] } - trigger_after_minutes = 15 + range_seconds = 900 } diff --git a/sysdig/resource_sysdig_monitor_alert_v2_event_test.go b/sysdig/resource_sysdig_monitor_alert_v2_event_test.go index 4cc9562ec..d68d5c85c 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_event_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_event_test.go @@ -85,7 +85,7 @@ resource "sysdig_monitor_alert_v2_event" "sample" { values = ["thom-cluster1", "demo-env-prom"] } - trigger_after_minutes = 15 + range_seconds = 900 } diff --git a/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go b/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go index 3f01a9416..be5094d88 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_metric_test.go @@ -122,7 +122,7 @@ resource "sysdig_monitor_alert_v2_metric" "sample" { time_aggregation = "avg" operator = ">=" threshold = 50 - trigger_after_minutes = 15 + range_seconds = 900 } `, name) @@ -266,7 +266,7 @@ resource "sysdig_monitor_alert_v2_metric" "sample" { time_aggregation = "avg" operator = ">=" threshold = 50 - trigger_after_minutes = 15 + range_seconds = 900 severity = "info" } @@ -517,7 +517,7 @@ resource "sysdig_monitor_alert_v2_metric" "sample" { time_aggregation = "avg" operator = ">=" threshold = 50 - trigger_after_minutes = 15 + range_seconds = 900 labels = { application = "app1" maturity = "high" diff --git a/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go b/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go index 9b1019423..5b0306568 100644 --- a/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go +++ b/sysdig/resource_sysdig_monitor_alert_v2_prometheus_test.go @@ -65,7 +65,7 @@ resource "sysdig_monitor_alert_v2_prometheus" "sample" { description = "TERRAFORM TEST - PROMQL %s" severity = "high" query = "(elasticsearch_jvm_memory_used_bytes{area=\"heap\"} / elasticsearch_jvm_memory_max_bytes{area=\"heap\"}) * 100 > 80" - trigger_after_minutes = 10 + duration_seconds = 600 enabled = false } `, name, name) diff --git a/sysdig/resource_sysdig_monitor_silence_rule_test.go b/sysdig/resource_sysdig_monitor_silence_rule_test.go index c8ef0b382..2fc3e04c3 100644 --- a/sysdig/resource_sysdig_monitor_silence_rule_test.go +++ b/sysdig/resource_sysdig_monitor_silence_rule_test.go @@ -73,16 +73,16 @@ resource "sysdig_monitor_silence_rule" "sample1" { func monitorSilenceRuleWithAlertIds(name string) string { return fmt.Sprintf(` -resource "sysdig_monitor_alert_promql" "sample1" { +resource "sysdig_monitor_alert_v2_prometheus" "sample1" { name = "TERRAFORM TEST - PROMQL %s 1" - promql = "up" - trigger_after_minutes = 1 + query = "up" + duration_seconds = 60 enabled = false } -resource "sysdig_monitor_alert_promql" "sample2" { +resource "sysdig_monitor_alert_v2_prometheus" "sample2" { name = "TERRAFORM TEST - PROMQL %s 2" - promql = "up" - trigger_after_minutes = 1 + query = "up" + duration_seconds = 60 enabled = false } resource "sysdig_monitor_silence_rule" "sample2" { @@ -90,22 +90,22 @@ resource "sysdig_monitor_silence_rule" "sample2" { enabled = false start_ts = 1691168134153 duration_seconds = 3600 - alert_ids = [ sysdig_monitor_alert_promql.sample1.id, sysdig_monitor_alert_promql.sample2.id ] + alert_ids = [ sysdig_monitor_alert_v2_prometheus.sample1.id, sysdig_monitor_alert_v2_prometheus.sample2.id ] }`, name, name, name) } func monitorSilenceRuleWithAlertIdsAndScope(name string) string { return fmt.Sprintf(` -resource "sysdig_monitor_alert_promql" "sample3" { +resource "sysdig_monitor_alert_v2_prometheus" "sample3" { name = "TERRAFORM TEST - PROMQL %s 3" - promql = "up" - trigger_after_minutes = 1 + query = "up" + duration_seconds = 60 enabled = false } -resource "sysdig_monitor_alert_promql" "sample4" { +resource "sysdig_monitor_alert_v2_prometheus" "sample4" { name = "TERRAFORM TEST - PROMQL %s 4" - promql = "up" - trigger_after_minutes = 1 + query = "up" + duration_seconds = 60 enabled = false } resource "sysdig_monitor_silence_rule" "sample3" { @@ -114,7 +114,7 @@ resource "sysdig_monitor_silence_rule" "sample3" { start_ts = 1691168134153 duration_seconds = 3600 scope = "container.name in (\"test\")" - alert_ids = [ sysdig_monitor_alert_promql.sample3.id, sysdig_monitor_alert_promql.sample4.id ] + alert_ids = [ sysdig_monitor_alert_v2_prometheus.sample3.id, sysdig_monitor_alert_v2_prometheus.sample4.id ] }`, name, name, name) } From 4a1a07d1f1c272dd3d06d2c71e63a3adc89dd46f Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 15:00:13 +0200 Subject: [PATCH 24/25] fix(tests): remove deprecated fields from secure_team test --- sysdig/resource_sysdig_secure_team_test.go | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/sysdig/resource_sysdig_secure_team_test.go b/sysdig/resource_sysdig_secure_team_test.go index 68b078b83..1e705a499 100644 --- a/sysdig/resource_sysdig_secure_team_test.go +++ b/sysdig/resource_sysdig_secure_team_test.go @@ -33,12 +33,6 @@ func TestAccSecureTeam(t *testing.T) { { Config: secureTeamMinimumConfiguration(randomText(10)), }, - { - Config: secureTeamWithPlatformMetricsIBM(randomText(10)), - SkipFunc: func() (bool, error) { - return !buildinfo.IBMSecure, nil - }, - }, { Config: secureTeamWithPostureZones(randomText(10)), SkipFunc: func() (bool, error) { @@ -96,15 +90,6 @@ resource "sysdig_secure_team" "sample" { }`, name) } -func secureTeamWithPlatformMetricsIBM(name string) string { - return fmt.Sprintf(` -resource "sysdig_secure_team" "sample" { - name = "sample-%s" - enable_ibm_platform_metrics = true - ibm_platform_metrics = "foo in (\"0\") and bar in (\"3\")" -}`, name) -} - func secureTeamWithPostureZones(name string) string { return fmt.Sprintf(` resource "sysdig_secure_posture_zone" "z1" { From 37f693cae870aa77df2c5d660490e6d10668045b Mon Sep 17 00:00:00 2001 From: Fede Barcelona Date: Thu, 18 Sep 2025 15:54:25 +0200 Subject: [PATCH 25/25] fix(tests): add orchestrator params to fargate ECS test --- sysdig/data_source_sysdig_fargate_ECS_test.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/sysdig/data_source_sysdig_fargate_ECS_test.go b/sysdig/data_source_sysdig_fargate_ECS_test.go index c0cf6c1cf..0563e3320 100644 --- a/sysdig/data_source_sysdig_fargate_ECS_test.go +++ b/sysdig/data_source_sysdig_fargate_ECS_test.go @@ -42,12 +42,14 @@ func sortAndCompare(t *testing.T, expected []byte, actual []byte) { // getKiltRecipe returns the default json Kilt recipe func getKiltRecipe(t *testing.T) string { recipeConfig := KiltRecipeConfig{ - SysdigAccessKey: "sysdig_access_key", - AgentImage: "workload_agent_image", - CollectorHost: "collector_host", - CollectorPort: "collector_port", - SysdigLogging: "sysdig_logging", - Priority: "priority", + SysdigAccessKey: "sysdig_access_key", + AgentImage: "workload_agent_image", + CollectorHost: "collector_host", + CollectorPort: "collector_port", + OrchestratorHost: "orchestrator_host", + OrchestratorPort: "orchestrator_port", + SysdigLogging: "sysdig_logging", + Priority: "priority", } jsonRecipeConfig, err := json.Marshal(&recipeConfig)