Skip to content
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

[#TF-722] Allow safe and force delete through the tfe provider #675

Merged
merged 5 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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 @@

FEATURES:
* r/tfe_organization: Add `allow_force_delete_workspaces` attribute to set whether admins are permitted to delete workspaces with resource under management. ([#661](https://github.com/hashicorp/terraform-provider-tfe/pull/661))
* r/tfe_workspace: Add `force_delete` attribute to set whether workspaces will be force deleted when removed through the provider. Otherwise, they will be safe deleted. ([#675](https://github.com/hashicorp/terraform-provider-tfe/pull/675))

## v0.38.0 (October 24, 2022)

Expand Down
17 changes: 15 additions & 2 deletions tfe/client_mock_workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tfe
import (
"context"
"errors"
"fmt"
"io"

tfe "github.com/hashicorp/go-tfe"
Expand Down Expand Up @@ -37,6 +38,7 @@ func (m *mockWorkspaces) Create(ctx context.Context, organization string, option
Organization: &tfe.Organization{
Name: organization,
},
Permissions: &tfe.WorkspacePermissions{},
}

m.workspaceNames[workspaceNamesKey{organization, *options.Name}] = ws
Expand Down Expand Up @@ -66,7 +68,12 @@ func (m *mockWorkspaces) Readme(ctx context.Context, workspaceID string) (io.Rea
}

func (m *mockWorkspaces) ReadByID(ctx context.Context, workspaceID string) (*tfe.Workspace, error) {
panic("not implemented")
for _, workspace := range m.workspaceNames {
if workspace.ID == workspaceID {
return workspace, nil
}
}
return nil, tfe.ErrResourceNotFound
}

func (m *mockWorkspaces) Update(ctx context.Context, organization, workspace string, options tfe.WorkspaceUpdateOptions) (*tfe.Workspace, error) {
Expand All @@ -82,7 +89,13 @@ func (m *mockWorkspaces) Delete(ctx context.Context, organization, workspace str
}

func (m *mockWorkspaces) DeleteByID(ctx context.Context, workspaceID string) error {
panic("not implemented")
for key, workspace := range m.workspaceNames {
if workspace.ID == workspaceID {
delete(m.workspaceNames, key)
return nil
}
}
return fmt.Errorf("no workspace found with id %s", workspaceID)
}

func (m *mockWorkspaces) RemoveVCSConnection(ctx context.Context, organization, workspace string) (*tfe.Workspace, error) {
Expand Down
29 changes: 28 additions & 1 deletion tfe/resource_tfe_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ func resourceTFEWorkspace() *schema.Resource {
},
},
},
"force_delete": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
Expand Down Expand Up @@ -671,7 +676,29 @@ func resourceTFEWorkspaceDelete(d *schema.ResourceData, meta interface{}) error
id := d.Id()

log.Printf("[DEBUG] Delete workspace %s", id)
err := tfeClient.Workspaces.DeleteByID(ctx, id)

ws, err := tfeClient.Workspaces.ReadByID(ctx, id)
if err != nil {
if err == tfe.ErrResourceNotFound {
return nil
}
return fmt.Errorf(
"Error reading workspace %s: %w", id, err)
}

forceDelete := d.Get("force_delete").(bool)

if ws.Permissions.CanForceDelete == nil && !forceDelete {
emlanctot marked this conversation as resolved.
Show resolved Hide resolved
return fmt.Errorf(
"Error deleting workspace %s: This workspace must be force deleted by setting force_delete=true", id)
emlanctot marked this conversation as resolved.
Show resolved Hide resolved
}

if forceDelete {
err = tfeClient.Workspaces.DeleteByID(ctx, id)
} else {
err = tfeClient.Workspaces.SafeDeleteByID(ctx, id)
}
emlanctot marked this conversation as resolved.
Show resolved Hide resolved

if err != nil {
if err == tfe.ErrResourceNotFound {
return nil
Expand Down
204 changes: 189 additions & 15 deletions tfe/resource_tfe_workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"math/rand"
"regexp"
"strconv"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1223,7 +1224,7 @@ func TestAccTFEWorkspace_updateVCSRepo(t *testing.T) {
CheckDestroy: testAccCheckTFEWorkspaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccTFEWorkspace_basic(rInt),
Config: testAccTFEWorkspace_basicForceDeleteEnabled(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceExists(
"tfe_workspace.foobar", workspace),
Expand Down Expand Up @@ -1490,15 +1491,17 @@ func TestAccTFEWorkspace_import(t *testing.T) {
},

{
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateVerify: true,
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_delete"},
},
{
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateId: fmt.Sprintf("tst-terraform-%d/workspace-test", rInt),
ImportStateVerify: true,
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateId: fmt.Sprintf("tst-terraform-%d/workspace-test", rInt),
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_delete"},
},
},
})
Expand Down Expand Up @@ -1533,9 +1536,10 @@ func TestAccTFEWorkspace_importVCSBranch(t *testing.T) {
},

{
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateVerify: true,
ResourceName: "tfe_workspace.foobar",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_delete"},
},
},
})
Expand Down Expand Up @@ -1811,6 +1815,143 @@ func TestAccTFEWorkspace_paginatedRemoteStateConsumers(t *testing.T) {
})
}

func TestAccTFEWorkspace_delete_forceDeleteSettingDisabled(t *testing.T) {
workspace := &tfe.Workspace{}
rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
tfeClient, err := getClientUsingEnv()
if err != nil {
t.Fatal(err)
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckTFEWorkspaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccTFEWorkspace_basic(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceExists(
"tfe_workspace.foobar", workspace),
testAccCheckTFEWorkspaceAttributes(workspace),
),
},
{
PreConfig: func() {
_, err := tfeClient.Workspaces.Lock(ctx, workspace.ID, tfe.WorkspaceLockOptions{})
if err != nil {
t.Fatal(err)
}
},
Config: testAccTFEWorkspace_basicDeleted(rInt),
ExpectError: regexp.MustCompile(`.*Workspace is currently locked.`),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceExists(
"tfe_workspace.foobar", workspace),
),
},
{
PreConfig: func() {
_, err := tfeClient.Workspaces.Unlock(ctx, workspace.ID)
if err != nil {
t.Fatal(err)
}
},
Config: testAccTFEWorkspace_basicDeleted(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceDestroy,
),
},
},
})
}

func TestAccTFEWorkspace_delete_forceDeleteSettingEnabled(t *testing.T) {
workspace := &tfe.Workspace{}
rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
tfeClient, err := getClientUsingEnv()
if err != nil {
t.Fatal(err)
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckTFEWorkspaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccTFEWorkspace_basicForceDeleteEnabled(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceExists(
"tfe_workspace.foobar", workspace),
testAccCheckTFEWorkspaceAttributes(workspace),
),
},
{
PreConfig: func() {
_, err := tfeClient.Workspaces.Lock(ctx, workspace.ID, tfe.WorkspaceLockOptions{})
if err != nil {
t.Fatal(err)
}
},
Config: testAccTFEWorkspace_basicDeleted(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckTFEWorkspaceDestroy,
),
},
},
})
}

func TestTFEWorkspace_delete_withoutCanForceDeletePermission(t *testing.T) {
// This test checks that workspace deletion works as expected when communicating with TFE servers which do not send
// the CanForceDelete workspace permission. To simulate this we use the mock workspaces client and call the
// workspace resource delete function directly, rather than use the usual resource.

rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
orgName := fmt.Sprintf("test-orgnaization-%d", rInt)
emlanctot marked this conversation as resolved.
Show resolved Hide resolved

client := testTfeClient(t, testClientOptions{defaultOrganization: orgName})
workspace, err := client.Workspaces.Create(ctx, orgName, tfe.WorkspaceCreateOptions{
Name: tfe.String(fmt.Sprintf("test-workspace-%d", rInt)),
})
if err != nil {
t.Fatalf("unexpected err creating mock workspace %v", err)
}
workspace.Permissions.CanForceDelete = nil

rd := resourceTFEWorkspace().TestResourceData()
rd.SetId(workspace.ID)
err = rd.Set("force_delete", false)
if err != nil {
t.Fatalf("unexpected err creating configuration state %v", err)
}

err = resourceTFEWorkspaceDelete(rd, client)

if err == nil {
t.Fatalf("Expected an error deleting workspace with CanForceDelete=nil and force_delete=true")
}
expectedErrSubstring := "workspace must be force deleted by setting force_delete=true"
if !strings.Contains(err.Error(), expectedErrSubstring) {
t.Fatalf("Expected error contains %s but got %s", expectedErrSubstring, err.Error())
}

// now attempt with force_delete=true and confirm that it successfully removes the workspace
err = rd.Set("force_delete", true)
if err != nil {
t.Fatalf("Unexpected err creating configuration state %v", err)
}

err = resourceTFEWorkspaceDelete(rd, client)
if err != nil {
t.Fatalf("Unexpected err deleting mock workspace %v", err)
}

workspace, err = client.Workspaces.ReadByID(ctx, workspace.ID)
if err != tfe.ErrResourceNotFound {
t.Fatalf("Expected workspace %s to have been deleted", workspace.ID)
}
}

func testAccCheckTFEWorkspaceExists(
n string, workspace *tfe.Workspace) resource.TestCheckFunc {
return func(s *terraform.State) error {
Expand Down Expand Up @@ -2288,6 +2429,32 @@ resource "tfe_workspace" "foobar" {
}`, rInt)
}

func testAccTFEWorkspace_basicDeleted(rInt int) string {
return fmt.Sprintf(`
resource "tfe_organization" "foobar" {
name = "tst-terraform-%d"
email = "admin@company.com"
}`, rInt)
}

func testAccTFEWorkspace_basicForceDeleteEnabled(rInt int) string {
return fmt.Sprintf(`
resource "tfe_organization" "foobar" {
name = "tst-terraform-%d"
email = "admin@company.com"
}

resource "tfe_workspace" "foobar" {
name = "workspace-test"
organization = tfe_organization.foobar.id
description = "My favorite workspace!"
allow_destroy_plan = false
auto_apply = true
tag_names = ["fav", "test"]
force_delete = true
}`, rInt)
}

func testAccTFEWorkspace_operationsTrue(organization string) string {
return fmt.Sprintf(`
resource "tfe_workspace" "foobar" {
Expand Down Expand Up @@ -2616,6 +2783,7 @@ resource "tfe_workspace" "foobar" {
description = "workspace-test-add-vcs-repo"
organization = tfe_organization.foobar.id
auto_apply = true
force_delete = true
vcs_repo {
identifier = "%s"
oauth_token_id = tfe_oauth_client.test.oauth_token_id
Expand Down Expand Up @@ -2683,6 +2851,7 @@ resource "tfe_workspace" "foobar" {
description = "workspace-test-update-vcs-repo-branch"
organization = tfe_organization.foobar.id
auto_apply = true
force_delete = true
vcs_repo {
identifier = "%s"
oauth_token_id = tfe_oauth_client.test.oauth_token_id
Expand All @@ -2709,6 +2878,7 @@ resource "tfe_workspace" "foobar" {
description = "workspace-test-remove-vcs-repo"
organization = tfe_organization.foobar.id
auto_apply = true
force_delete = true
}
`, rInt)
}
Expand All @@ -2733,6 +2903,7 @@ resource "tfe_workspace" "foobar" {
description = "workspace-test-update-vcs-repo-tags-regex"
organization = tfe_organization.foobar.id
auto_apply = true
force_delete = true
file_triggers_enabled = false
vcs_repo {
identifier = "%s"
Expand Down Expand Up @@ -2769,6 +2940,7 @@ resource "tfe_workspace" "foobar" {
description = "workspace-test-update-vcs-repo-tags-regex"
organization = tfe_organization.foobar.id
auto_apply = true
force_delete = true
file_triggers_enabled = false
vcs_repo {
identifier = "%s"
Expand Down Expand Up @@ -2805,8 +2977,9 @@ func testAccTFEWorkspace_updateToTriggerPatternsFromTagsRegex(rInt int) string {
description = "workspace-test-update-vcs-repo-tags-regex"
organization = tfe_organization.foobar.id
auto_apply = true
file_triggers_enabled = true
trigger_patterns = ["foo/**/*"]
force_delete = true
file_triggers_enabled = true
trigger_patterns = ["foo/**/*"]
vcs_repo {
identifier = "%s"
oauth_token_id = tfe_oauth_client.test.oauth_token_id
Expand Down Expand Up @@ -2841,8 +3014,9 @@ func testAccTFEWorkspace_updateRemoveVCSBlockFromTagsRegex(rInt int) string {
description = "workspace-test-update-vcs-repo-tags-regex"
organization = tfe_organization.foobar.id
auto_apply = true
file_triggers_enabled = true
trigger_patterns = ["foo/**/*"]
force_delete = true
file_triggers_enabled = true
trigger_patterns = ["foo/**/*"]
}
`,
rInt,
Expand Down
Loading