Skip to content

Commit

Permalink
Added new okta_policy_profile_enrollment_apps resource (okta#973)
Browse files Browse the repository at this point in the history
  • Loading branch information
bogdanprodan-okta authored and virgofx committed Mar 3, 2022
1 parent 8454c24 commit 819df0a
Show file tree
Hide file tree
Showing 9 changed files with 379 additions and 0 deletions.
22 changes: 22 additions & 0 deletions examples/okta_policy_profile_enrollment_apps/basic.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
resource "okta_app_bookmark" "test" {
label = "testAcc_replace_with_uuid"
url = "https://test.com"
}

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

resource "okta_policy_profile_enrollment" "test_2" {
name = "testAcc_replace_with_uuid_2"
}

resource "okta_policy_profile_enrollment_apps" "test" {
policy_id = okta_policy_profile_enrollment.test.id
apps = [okta_app_bookmark.test.id]
}

resource "okta_policy_profile_enrollment_apps" "test_2" {
policy_id = okta_policy_profile_enrollment.test_2.id
depends_on = [okta_policy_profile_enrollment_apps.test]
}
22 changes: 22 additions & 0 deletions examples/okta_policy_profile_enrollment_apps/basic_updated.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
resource "okta_app_bookmark" "test" {
label = "testAcc_replace_with_uuid"
url = "https://test.com"
}

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

resource "okta_policy_profile_enrollment" "test_2" {
name = "testAcc_replace_with_uuid_2"
}

resource "okta_policy_profile_enrollment_apps" "test" {
policy_id = okta_policy_profile_enrollment.test.id
}

resource "okta_policy_profile_enrollment_apps" "test_2" {
policy_id = okta_policy_profile_enrollment.test_2.id
apps = [okta_app_bookmark.test.id]
depends_on = [okta_policy_profile_enrollment_apps.test]
}
2 changes: 2 additions & 0 deletions okta/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ const (
policyPassword = "okta_policy_password"
policyPasswordDefault = "okta_policy_password_default"
policyProfileEnrollment = "okta_policy_profile_enrollment"
policyProfileEnrollmentApps = "okta_policy_profile_enrollment_apps"
policyRuleIdpDiscovery = "okta_policy_rule_idp_discovery"
policyRuleMfa = "okta_policy_rule_mfa"
policyRulePassword = "okta_policy_rule_password"
Expand Down Expand Up @@ -290,6 +291,7 @@ func Provider() *schema.Provider {
policyPassword: resourcePolicyPassword(),
policyPasswordDefault: resourcePolicyPasswordDefault(),
policyProfileEnrollment: resourcePolicyProfileEnrollment(),
policyProfileEnrollmentApps: resourcePolicyProfileEnrollmentApps(),
policyRuleIdpDiscovery: resourcePolicyRuleIdpDiscovery(),
policyRuleMfa: resourcePolicyMfaRule(),
policyRulePassword: resourcePolicyPasswordRule(),
Expand Down
169 changes: 169 additions & 0 deletions okta/resource_okta_policy_profile_enrollment_apps.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package okta

import (
"context"
"errors"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/okta/okta-sdk-golang/v2/okta"
"github.com/okta/okta-sdk-golang/v2/okta/query"
"github.com/okta/terraform-provider-okta/sdk"
)

func resourcePolicyProfileEnrollmentApps() *schema.Resource {
return &schema.Resource{
CreateContext: resourcePolicyProfileEnrollmentAppsCreate,
ReadContext: resourcePolicyProfileEnrollmentAppsRead,
UpdateContext: resourcePolicyProfileEnrollmentAppsUpdate,
DeleteContext: resourcePolicyProfileEnrollmentAppsDelete,
Importer: &schema.ResourceImporter{StateContext: schema.ImportStatePassthroughContext},
Schema: map[string]*schema.Schema{
"policy_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the enrollment policy.",
},
"apps": {
Type: schema.TypeSet,
Optional: true,
Description: "List of app IDs to be added to this policy",
Elem: &schema.Schema{Type: schema.TypeString},
},
"default_policy_id": {
Type: schema.TypeString,
Computed: true,
Description: "ID of the Default Enrollment Policy. This policy is used as a policy to re-assign apps to when they are unassigned from this one",
},
},
}
}

func resourcePolicyProfileEnrollmentAppsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
err := setDefaultPolicyID(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
policyID := d.Get("policy_id").(string)
apps := convertInterfaceToStringSetNullable(d.Get("apps"))
client := getSupplementFromMetadata(m)

for i := range apps {
body := sdk.AddAppToEnrollmentPolicyRequest{
ResourceType: "APP",
ResourceId: apps[i],
}
_, _, err := client.AddAppToEnrollmentPolicy(ctx, policyID, body)
if err != nil {
return diag.Errorf("failed to add an app to the policy, %v", err)
}
}
d.SetId(policyID)
return nil
}

func resourcePolicyProfileEnrollmentAppsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
err := setDefaultPolicyID(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
apps, err := listPolicyEnrollmentAppIDs(ctx, getSupplementFromMetadata(m), d.Id())
if err != nil {
return diag.Errorf("failed to get list of enrollment policy apps: %v", err)
}
_ = d.Set("policy_id", d.Id())
_ = d.Set("apps", convertStringSliceToSetNullable(apps))
return nil
}

func resourcePolicyProfileEnrollmentAppsUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
oldApps, newApps := d.GetChange("apps")
oldSet := oldApps.(*schema.Set)
newSet := newApps.(*schema.Set)
appsToAdd := convertInterfaceArrToStringArr(newSet.Difference(oldSet).List())
appsToRemove := convertInterfaceArrToStringArr(oldSet.Difference(newSet).List())

client := getSupplementFromMetadata(m)
policyID := d.Get("policy_id").(string)

for i := range appsToAdd {
body := sdk.AddAppToEnrollmentPolicyRequest{
ResourceType: "APP",
ResourceId: appsToAdd[i],
}
_, _, err := client.AddAppToEnrollmentPolicy(ctx, policyID, body)
if err != nil {
return diag.Errorf("failed to add an app to the policy, %v", err)
}
}

defaultPolicyID := d.Get("default_policy_id").(string)

for i := range appsToRemove {
body := sdk.AddAppToEnrollmentPolicyRequest{
ResourceType: "APP",
ResourceId: appsToRemove[i],
}
_, _, err := client.AddAppToEnrollmentPolicy(ctx, defaultPolicyID, body)
if err != nil {
return diag.Errorf("failed to add reassign app to the default policy, %v", err)
}
}

return nil
}

func resourcePolicyProfileEnrollmentAppsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
defaultPolicyID := d.Get("default_policy_id").(string)
apps := convertInterfaceToStringSetNullable(d.Get("apps"))
client := getSupplementFromMetadata(m)

for i := range apps {
body := sdk.AddAppToEnrollmentPolicyRequest{
ResourceType: "APP",
ResourceId: apps[i],
}
_, _, err := client.AddAppToEnrollmentPolicy(ctx, defaultPolicyID, body)
if err != nil {
return diag.Errorf("failed to add reassign app to the default policy, %v", err)
}
}

return nil
}

func listPolicyEnrollmentAppIDs(ctx context.Context, client *sdk.APISupplement, policyID string) ([]string, error) {
apps, resp, err := client.ListEnrollmentPolicyApps(ctx, policyID, &query.Params{Limit: defaultPaginationLimit})
if err != nil {
return nil, err
}
appIDs := make([]string, len(apps))
for i := range apps {
appIDs[i] = apps[i].Id
}
for resp.HasNextPage() {
var nextApps []*okta.Application
resp, err = resp.Next(ctx, &nextApps)
if err != nil {
return nil, err
}
for i := range nextApps {
appIDs = append(appIDs, nextApps[i].Id)
}
}
return appIDs, nil
}

func setDefaultPolicyID(ctx context.Context, d *schema.ResourceData, m interface{}) error {
policy, err := findPolicy(ctx, m, "Default Policy", sdk.ProfileEnrollmentPolicyType)
if err != nil {
return err
}
policyID := d.Get("policy_id").(string)
if policyID == policy.Id {
return errors.New("default enrollment policy cannot be used here, since it is used as a policy to re-assign apps to when they are unassigned from this one")
}
_ = d.Set("default_policy_id", policy.Id)
return nil
}
43 changes: 43 additions & 0 deletions okta/resource_okta_policy_profile_enrollment_apps_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package okta

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccOktaPolicyProfileEnrollmentApps(t *testing.T) {
ri := acctest.RandInt()
mgr := newFixtureManager(policyProfileEnrollmentApps)
config := mgr.GetFixtures("basic.tf", ri, t)
updatedConfig := mgr.GetFixtures("basic_updated.tf", ri, t)
resourceName := fmt.Sprintf("%s.test", policyProfileEnrollmentApps)
resourceName2 := fmt.Sprintf("%s.test_2", policyProfileEnrollmentApps)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProvidersFactories,
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
ensurePolicyExists(resourceName),
ensurePolicyExists(resourceName2),
resource.TestCheckResourceAttr(resourceName, "apps.#", "1"),
resource.TestCheckResourceAttr(resourceName2, "apps.#", "0"),
),
},
{
Config: updatedConfig,
Check: resource.ComposeTestCheckFunc(
ensurePolicyExists(resourceName),
ensurePolicyExists(resourceName2),
resource.TestCheckResourceAttr(resourceName, "apps.#", "0"),
resource.TestCheckResourceAttr(resourceName2, "apps.#", "1"),
),
},
},
})
}
55 changes: 55 additions & 0 deletions sdk/policy_enrollment_apps.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package sdk

import (
"context"
"fmt"
"net/http"

"github.com/okta/okta-sdk-golang/v2/okta/query"

"github.com/okta/okta-sdk-golang/v2/okta"
)

type AddAppToEnrollmentPolicyRequest struct {
ResourceType string `json:"resourceType"`
ResourceId string `json:"resourceId"`
}

type AddAppToEnrollmentPolicyResponse struct {
Id string `json:"id"`
Links interface{} `json:"_links,omitempty"`
}

// AddAppToEnrollmentPolicy adds an app to the policy
func (m *APISupplement) AddAppToEnrollmentPolicy(ctx context.Context, policyID string, body AddAppToEnrollmentPolicyRequest) (*AddAppToEnrollmentPolicyResponse, *okta.Response, error) {
url := fmt.Sprintf("/api/v1/policies/%s/mappings?forceCreate=true", policyID)
re := m.cloneRequestExecutor()
req, err := re.WithAccept("application/json").WithContentType("application/json").NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, nil, err
}
var response *AddAppToEnrollmentPolicyResponse
resp, err := re.Do(ctx, req, &response)
if err != nil {
return nil, resp, err
}
return response, resp, nil
}

func (m *APISupplement) ListEnrollmentPolicyApps(ctx context.Context, policyID string, qp *query.Params) ([]*okta.Application, *okta.Response, error) {
url := fmt.Sprintf("/api/v1/policies/%s/app", policyID)
if qp != nil {
url += qp.String()
}
re := m.cloneRequestExecutor()
req, err := re.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, nil, err
}
var applications []*okta.Application
resp, err := re.Do(ctx, req, &applications)
if err != nil {
return nil, resp, err
}
return applications, resp, nil
}
58 changes: 58 additions & 0 deletions website/docs/r/policy_profile_enrollment_apps.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
layout: 'okta'
page_title: 'Okta: okta_policy_profile_enrollment_apps'
sidebar_current: 'docs-okta-resource-policy-profile-enrollment-apps'
description: |-
Manages Profile Enrollment Policy Apps
---

# okta_policy_profile_enrollment_apps

~> **WARNING:** This feature is only available as a part of the Identity Engine. [Contact support](mailto:dev-inquiries@okta.com) for further information.

This resource allows you to manage the apps in the Profile Enrollment Policy.

**Important Notes:**
- Default Enrollment Policy can not be used in this resource since it is used as a policy to re-assign apps to when they are unassigned from this one.
- When re-assigning the app to another policy, please use `depends_on` in the policy to which the app will be assigned. This is necessary to avoid
unexpected behavior, since if the app is unassigned from the policy it is just assigned to the `Default` one.

## Example Usage

```hcl
data "okta_policy" "example" {
name = "My Policy"
type = "PROFILE_ENROLLMENT"
}
data "okta_app" "test" {
label = "My App"
}
resource "okta_policy_profile_enrollment_apps" "example" {
policy_id = okta_policy.example.id
apps = [data.okta_app.id]
}
```

## Argument Reference

The following arguments are supported:

- `policy_id` - (Required) ID of the enrollment policy.

- `apps` - (Optional) List of app IDs to be added to this policy.

## Attributes Reference

- `id` - ID of the enrollment policy.

- `default_policy_id` - ID of the default enrollment policy.

## Import

A Profile Enrollment Policy Apps can be imported via the Okta ID.

```
$ terraform import okta_policy_profile_enrollment_apps.example <policy id>
```
2 changes: 2 additions & 0 deletions website/docs/r/profile_mapping.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ The following arguments are supported:
- `push_status` - (Optional) Whether to update target properties on user create & update or just on create.

- `always_apply` (Optional) Whether apply the changes to all users with this profile after updating or creating the these mappings.

~> **WARNING**: `always_apply` is available only when using api token in the provider config.

## Attributes Reference

Expand Down
Loading

0 comments on commit 819df0a

Please sign in to comment.