Skip to content

Commit

Permalink
Retain user group app assignments (#330)
Browse files Browse the repository at this point in the history
Add option to retain `okta_app_group_assignment` and `okta_app_user` on destroy.
  • Loading branch information
Omicron7 committed Feb 23, 2021
1 parent 029386d commit e465901
Show file tree
Hide file tree
Showing 11 changed files with 255 additions and 0 deletions.
22 changes: 22 additions & 0 deletions examples/okta_app_group_assignment/retain_assignment.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
resource "okta_app_oauth" "test" {
label = "testAcc_replace_with_uuid"
type = "web"
grant_types = ["implicit", "authorization_code"]
redirect_uris = ["http://d.com/"]
response_types = ["code", "token", "id_token"]
issuer_mode = "ORG_URL"

lifecycle {
ignore_changes = ["users", "groups"]
}
}

resource "okta_group" "test" {
name = "testAcc_replace_with_uuid"
}

resource "okta_app_group_assignment" "test" {
app_id = okta_app_oauth.test.id
group_id = okta_group.test.id
retain_assignment = true
}
16 changes: 16 additions & 0 deletions examples/okta_app_group_assignment/retain_assignment_destroy.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
resource "okta_app_oauth" "test" {
label = "testAcc_replace_with_uuid"
type = "web"
grant_types = ["implicit", "authorization_code"]
redirect_uris = ["http://d.com/"]
response_types = ["code", "token", "id_token"]
issuer_mode = "ORG_URL"

lifecycle {
ignore_changes = ["users", "groups"]
}
}

resource "okta_group" "test" {
name = "testAcc_replace_with_uuid"
}
26 changes: 26 additions & 0 deletions examples/okta_app_user/retain.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
resource "okta_app_oauth" "test" {
label = "testAcc_replace_with_uuid"
type = "web"
grant_types = ["implicit", "authorization_code"]
redirect_uris = ["http://d.com/"]
response_types = ["code", "token", "id_token"]
issuer_mode = "ORG_URL"

lifecycle {
ignore_changes = ["users", "groups"]
}
}

resource "okta_user" "test" {
first_name = "TestAcc"
last_name = "Smith"
login = "testAcc_replace_with_uuid@example.com"
email = "testAcc_replace_with_uuid@example.com"
}

resource "okta_app_user" "test" {
app_id = okta_app_oauth.test.id
user_id = okta_user.test.id
username = okta_user.test.email
retain_assignment = true
}
19 changes: 19 additions & 0 deletions examples/okta_app_user/retain_destroy.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
resource "okta_app_oauth" "test" {
label = "testAcc_replace_with_uuid"
type = "web"
grant_types = ["implicit", "authorization_code"]
redirect_uris = ["http://d.com/"]
response_types = ["code", "token", "id_token"]
issuer_mode = "ORG_URL"

lifecycle {
ignore_changes = ["users", "groups"]
}
}

resource "okta_user" "test" {
first_name = "TestAcc"
last_name = "Smith"
login = "testAcc_replace_with_uuid@example.com"
email = "testAcc_replace_with_uuid@example.com"
}
13 changes: 13 additions & 0 deletions okta/resource_okta_app_group_assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func resourceAppGroupAssignment() *schema.Resource {

_ = d.Set("app_id", parts[0])
_ = d.Set("group_id", parts[1])
_ = d.Set("retain_assignment", false)

assignment, _, err := getOktaClientFromMetadata(m).Application.
GetApplicationGroupAssignment(ctx, parts[0], parts[1], nil)
Expand Down Expand Up @@ -65,6 +66,12 @@ func resourceAppGroupAssignment() *schema.Resource {
return new == ""
},
},
"retain_assignment": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Retain the group assignment on destroy. If set to true, the resource will be removed from state but not from the Okta app.",
},
},
}
}
Expand Down Expand Up @@ -121,6 +128,12 @@ func resourceAppGroupAssignmentRead(ctx context.Context, d *schema.ResourceData,
}

func resourceAppGroupAssignmentDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
retain := d.Get("retain_assignment").(bool)
if retain {
// The assignment should be retained, bail before DeleteApplicationGroupAssignment is called
return nil
}

_, err := getOktaClientFromMetadata(m).Application.DeleteApplicationGroupAssignment(
ctx,
d.Get("app_id").(string),
Expand Down
64 changes: 64 additions & 0 deletions okta/resource_okta_app_group_assignment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,41 @@ func TestAccAppGroupAssignment_crud(t *testing.T) {
})
}

func TestAccAppGroupAssignment_retain(t *testing.T) {
ri := acctest.RandInt()
resourceName := fmt.Sprintf("%s.test", appGroupAssignment)
appName := fmt.Sprintf("%s.test", appOAuth)
groupName := fmt.Sprintf("%s.test", oktaGroup)
mgr := newFixtureManager(appGroupAssignment)
retainAssignment := mgr.GetFixtures("retain_assignment.tf", ri, t)
retainAssignmentDestroy := mgr.GetFixtures("retain_assignment_destroy.tf", ri, t)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProvidersFactories,
CheckDestroy: testAccCheckUserDestroy,
Steps: []resource.TestStep{
{
Config: retainAssignment,
Check: resource.ComposeTestCheckFunc(
ensureAppGroupAssignmentExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "app_id"),
resource.TestCheckResourceAttrSet(resourceName, "group_id"),
resource.TestCheckResourceAttr(resourceName, "retain_assignment", "true"),
resource.TestCheckResourceAttr(resourceName, "profile", "{}"),
),
},
{
Config: retainAssignmentDestroy,
Check: resource.ComposeTestCheckFunc(
ensureResourceNotExists(resourceName),
ensureAppGroupAssignmentRetained(appName, groupName),
),
},
},
})
}

func ensureAppGroupAssignmentExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
missingErr := fmt.Errorf("resource not found: %s", name)
Expand All @@ -100,3 +135,32 @@ func ensureAppGroupAssignmentExists(name string) resource.TestCheckFunc {
return nil
}
}

func ensureAppGroupAssignmentRetained(appName string, groupName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
notFound := "resource not found: %s"
// app group assignment has been removed from state, so use app and group to query okta
appRes, ok := s.RootModule().Resources[appName]
if !ok {
return fmt.Errorf(notFound, appName)
}

groupRes, ok := s.RootModule().Resources[groupName]
if !ok {
return fmt.Errorf(notFound, groupName)
}

appID := appRes.Primary.ID
groupID := groupRes.Primary.ID
client := getOktaClientFromMetadata(testAccProvider.Meta())

g, _, err := client.Application.GetApplicationGroupAssignment(context.Background(), appID, groupID, nil)
if err != nil {
return err
} else if g == nil {
return fmt.Errorf("Application Group Assignment not found for app ID, group ID: %s, %s", appID, groupID)
}

return nil
}
}
13 changes: 13 additions & 0 deletions okta/resource_okta_app_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func resourceAppUser() *schema.Resource {

_ = d.Set("app_id", parts[0])
_ = d.Set("user_id", parts[1])
_ = d.Set("retain_assignment", false)

assignment, _, err := getOktaClientFromMetadata(m).Application.
GetApplicationUser(ctx, parts[0], parts[1], nil)
Expand Down Expand Up @@ -68,6 +69,12 @@ func resourceAppUser() *schema.Resource {
return new == ""
},
},
"retain_assignment": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Retain the user assignment on destroy. If set to true, the resource will be removed from state but not from the Okta app.",
},
},
}
}
Expand Down Expand Up @@ -123,6 +130,12 @@ func resourceAppUserRead(ctx context.Context, d *schema.ResourceData, m interfac
}

func resourceAppUserDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
retain := d.Get("retain_assignment").(bool)
if retain {
// The assignment should be retained, bail before DeleteApplicationUser is called
return nil
}

_, err := getOktaClientFromMetadata(m).Application.DeleteApplicationUser(
ctx,
d.Get("app_id").(string),
Expand Down
64 changes: 64 additions & 0 deletions okta/resource_okta_app_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,41 @@ func TestAccOktaAppUser_crud(t *testing.T) {
})
}

func TestAccOktaAppUser_retain(t *testing.T) {
ri := acctest.RandInt()
resourceName := fmt.Sprintf("%s.test", appUser)
appName := fmt.Sprintf("%s.test", appOAuth)
userName := fmt.Sprintf("%s.test", oktaUser)
mgr := newFixtureManager(appUser)
retain := mgr.GetFixtures("retain.tf", ri, t)
retainDestroy := mgr.GetFixtures("retain_destroy.tf", ri, t)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProvidersFactories,
CheckDestroy: checkAppUserDestroy,
Steps: []resource.TestStep{
{
Config: retain,
Check: resource.ComposeTestCheckFunc(
ensureAppUserExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "app_id"),
resource.TestCheckResourceAttrSet(resourceName, "user_id"),
resource.TestCheckResourceAttr(resourceName, "username", fmt.Sprintf("testAcc_%d@example.com", ri)),
resource.TestCheckResourceAttr(resourceName, "retain_assignment", "true"),
),
},
{
Config: retainDestroy,
Check: resource.ComposeTestCheckFunc(
ensureResourceNotExists(resourceName),
ensureAppUserRetained(appName, userName),
),
},
},
})
}

func ensureAppUserExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
missingErr := fmt.Errorf("resource not found: %s", name)
Expand Down Expand Up @@ -124,3 +159,32 @@ func checkAppUserDestroy(s *terraform.State) error {

return nil
}

func ensureAppUserRetained(appName string, userName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
notFound := "resource not found: %s"
// app user has been removed from state, so use app and user to query okta
appRes, ok := s.RootModule().Resources[appName]
if !ok {
return fmt.Errorf(notFound, appName)
}

userRes, ok := s.RootModule().Resources[userName]
if !ok {
return fmt.Errorf(notFound, userName)
}

appID := appRes.Primary.ID
userID := userRes.Primary.ID
client := getOktaClientFromMetadata(testAccProvider.Meta())

g, _, err := client.Application.GetApplicationUser(context.Background(), appID, userID, nil)
if err != nil {
return err
} else if g == nil {
return fmt.Errorf("Application User not found for app ID, user ID: %s, %s", appID, userID)
}

return nil
}
}
10 changes: 10 additions & 0 deletions okta/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,13 @@ func createCheckResourceDestroy(typeName string, checkUpstream checkUpstream) re
return nil
}
}

func ensureResourceNotExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return nil
}
return fmt.Errorf("Resource found: %s", name)
}
}
4 changes: 4 additions & 0 deletions website/docs/r/app_group_assignment.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ resource "okta_app_oauth" "app" {
}
```

~> **Important:** When the `app_group_assignment` is retained, by setting `retain_assignment` to `true`, it is no longer managed by Terraform after it is destroyed. To truly delete the assignment, you will need to remove it either through the Okta Console or API. This argument exists for the use case where the same group is assigned in multiple places in order to prevent a single destruction removing all of them.

## Argument Reference

The following arguments are supported:
Expand All @@ -48,6 +50,8 @@ The following arguments are supported:

- `profile` - (Optional) JSON document containing [application profile](https://developer.okta.com/docs/reference/api/apps/#profile-object)

- `retain_assignment` - (Optional) Retain the group assignment on destroy. If set to true, the resource will be removed from state but not from the Okta app.

## Attributes Reference

- `id` - ID of the group assignment.
Expand Down
4 changes: 4 additions & 0 deletions website/docs/r/app_user.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ lifecycle {
}
```

~> **Important:** When the `okta_app_user` is retained, by setting `retain_assignment` to `true`, it is no longer managed by Terraform after it is destroyed. To truly delete the assignment, you will need to remove it either through the Okta Console or API. This argument exists for the use case where the same user is assigned in multiple places in order to prevent a single destruction removing all of them.

## Example Usage

```hcl
Expand All @@ -44,6 +46,8 @@ The following arguments are supported:

- `profile` - (Optional) The JSON profile of the App User.

- `retain_assignment` - (Optional) Retain the user association on destroy. If set to true, the resource will be removed from state but not from the Okta app.

## Attributes Reference

- `id` - The ID of the app user.
Expand Down

0 comments on commit e465901

Please sign in to comment.