Skip to content

Add skip_destory flag for Fleet Agent Policies #357

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Added
- Logging of Kibana action connectors HTTP requests and responses when [Terraform logs are enabled](https://developer.hashicorp.com/terraform/internals/debugging).
- Add `skip_destroy` flag to `elasticstack_fleet_agent_policy` resource ([#357](https://github.com./elastic/terraform-provider-elasticstack/pull/357))

## [0.6.1] - 2023-05-30

Expand Down
1 change: 1 addition & 0 deletions docs/resources/fleet_agent_policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ resource "elasticstack_fleet_agent_policy" "test_policy" {
- `monitor_metrics` (Boolean) Enable collection of agent metrics.
- `monitoring_output_id` (String) The identifier for monitoring output.
- `policy_id` (String) Unique identifier of the agent policy.
- `skip_destroy` (Boolean) Set to true if you do not wish the agent policy to be deleted at destroy time, and instead just remove the agent policy from the Terraform state.
- `sys_monitoring` (Boolean) Enable collection of system logs and metrics.

### Read-Only
Expand Down
11 changes: 11 additions & 0 deletions internal/fleet/agent_policy_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com./elastic/terraform-provider-elasticstack/internal/clients/fleet"
"github.com./elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi"
"github.com./hashicorp/terraform-plugin-log/tflog"
"github.com./hashicorp/terraform-plugin-sdk/v2/diag"
"github.com./hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -73,6 +74,11 @@ func ResourceAgentPolicy() *schema.Resource {
Type: schema.TypeBool,
Optional: true,
},
"skip_destroy": {
Description: "Set to true if you do not wish the agent policy to be deleted at destroy time, and instead just remove the agent policy from the Terraform state.",
Type: schema.TypeBool,
Optional: true,
},
}

return &schema.Resource{
Expand Down Expand Up @@ -264,6 +270,11 @@ func resourceAgentPolicyRead(ctx context.Context, d *schema.ResourceData, meta i
}

func resourceAgentPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
if d.Get("skip_destroy").(bool) {
tflog.Debug(ctx, "Skipping destroy of Agent Policy", map[string]interface{}{"policy_id": d.Id()})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO this should be at a higher log level so it's clear to users that we're not destroying this policy during apply.

return nil
}

fleetClient, diags := getFleetClient(d, meta)
if diags.HasError() {
return diags
Expand Down
70 changes: 64 additions & 6 deletions internal/fleet/agent_policy_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,57 @@ func TestAccResourceAgentPolicy(t *testing.T) {
Steps: []resource.TestStep{
{
SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionAgentPolicy),
Config: testAccResourceAgentPolicyCreate(policyName),
Config: testAccResourceAgentPolicyCreate(policyName, false),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "name", fmt.Sprintf("Policy %s", policyName)),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "namespace", "default"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "description", "Test Agent Policy"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_logs", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_metrics", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "skip_destroy", "false"),
),
},
{
SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionAgentPolicy),
Config: testAccResourceAgentPolicyUpdate(policyName),
Config: testAccResourceAgentPolicyUpdate(policyName, false),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "name", fmt.Sprintf("Updated Policy %s", policyName)),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "namespace", "default"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "description", "This policy was updated"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_logs", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_metrics", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "skip_destroy", "false"),
),
},
},
})
}

func testAccResourceAgentPolicyCreate(id string) string {
func TestAccResourceAgentPolicySkipDestroy(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️

policyName := sdkacctest.RandStringFromCharSet(22, sdkacctest.CharSetAlphaNum)

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
CheckDestroy: checkResourceAgentPolicySkipDestroy,
ProtoV5ProviderFactories: acctest.Providers,
Steps: []resource.TestStep{
{
SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionAgentPolicy),
Config: testAccResourceAgentPolicyCreate(policyName, true),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "name", fmt.Sprintf("Policy %s", policyName)),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "namespace", "default"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "description", "Test Agent Policy"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_logs", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "monitor_metrics", "true"),
resource.TestCheckResourceAttr("elasticstack_fleet_agent_policy.test_policy", "skip_destroy", "true"),
),
},
},
})
}

func testAccResourceAgentPolicyCreate(id string, skipDestroy bool) string {
return fmt.Sprintf(`
provider "elasticstack" {
elasticsearch {}
Expand All @@ -64,16 +90,17 @@ resource "elasticstack_fleet_agent_policy" "test_policy" {
description = "Test Agent Policy"
monitor_logs = true
monitor_metrics = true
skip_destroy = %t
}

data "elasticstack_fleet_enrollment_tokens" "test_policy" {
policy_id = elasticstack_fleet_agent_policy.test_policy.policy_id
}

`, fmt.Sprintf("Policy %s", id))
`, fmt.Sprintf("Policy %s", id), skipDestroy)
}

func testAccResourceAgentPolicyUpdate(id string) string {
func testAccResourceAgentPolicyUpdate(id string, skipDestroy bool) string {
return fmt.Sprintf(`
provider "elasticstack" {
elasticsearch {}
Expand All @@ -86,12 +113,13 @@ resource "elasticstack_fleet_agent_policy" "test_policy" {
description = "This policy was updated"
monitor_logs = true
monitor_metrics = true
skip_destroy = %t
}

data "elasticstack_fleet_enrollment_tokens" "test_policy" {
policy_id = elasticstack_fleet_agent_policy.test_policy.policy_id
}
`, fmt.Sprintf("Updated Policy %s", id))
`, fmt.Sprintf("Updated Policy %s", id), skipDestroy)
}

func checkResourceAgentPolicyDestroy(s *terraform.State) error {
Expand Down Expand Up @@ -119,3 +147,33 @@ func checkResourceAgentPolicyDestroy(s *terraform.State) error {
}
return nil
}

func checkResourceAgentPolicySkipDestroy(s *terraform.State) error {
client, err := clients.NewAcceptanceTestingClient()
if err != nil {
return err
}

for _, rs := range s.RootModule().Resources {
if rs.Type != "elasticstack_fleet_agent_policy" {
continue
}

fleetClient, err := client.GetFleetClient()
if err != nil {
return err
}
packagePolicy, diag := fleet.ReadAgentPolicy(context.Background(), fleetClient, rs.Primary.ID)
if diag.HasError() {
return fmt.Errorf(diag[0].Summary)
}
if packagePolicy == nil {
return fmt.Errorf("agent policy id=%v does not exist, but should still exist when skip_destroy is true", rs.Primary.ID)
}

if diag = fleet.DeleteAgentPolicy(context.Background(), fleetClient, rs.Primary.ID); diag.HasError() {
return fmt.Errorf(diag[0].Summary)
}
}
return nil
}