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

resource/aws_organizations_organization: Add enabled_policy_types argument #8588

Merged
merged 3 commits into from
May 10, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
163 changes: 163 additions & 0 deletions aws/resource_aws_organizations_organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ package aws
import (
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/organizations"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)

const organizationsPolicyTypeStatusDisabled = "DISABLED"

func resourceAwsOrganizationsOrganization() *schema.Resource {
return &schema.Resource{
Create: resourceAwsOrganizationsOrganizationCreate,
Expand Down Expand Up @@ -78,6 +82,16 @@ func resourceAwsOrganizationsOrganization() *schema.Resource {
},
},
},
"enabled_policy_types": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
organizations.PolicyTypeServiceControlPolicy,
}, false),
},
},
"feature_set": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -123,6 +137,32 @@ func resourceAwsOrganizationsOrganizationCreate(d *schema.ResourceData, meta int
}
}

enabledPolicyTypes := d.Get("enabled_policy_types").(*schema.Set).List()

if len(enabledPolicyTypes) > 0 {
defaultRoot, err := getOrganizationDefaultRoot(conn)

if err != nil {
return fmt.Errorf("error getting AWS Organization (%s) default root: %s", d.Id(), err)
}

for _, v := range enabledPolicyTypes {
enabledPolicyType := v.(string)
input := &organizations.EnablePolicyTypeInput{
PolicyType: aws.String(enabledPolicyType),
RootId: defaultRoot.Id,
}

if _, err := conn.EnablePolicyType(input); err != nil {
return fmt.Errorf("error enabling policy type (%s) in Organization (%s): %s", enabledPolicyType, d.Id(), err)
}

if err := waitForOrganizationDefaultRootPolicyTypeEnable(conn, enabledPolicyType); err != nil {
return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s): %s", enabledPolicyType, d.Id(), err)
}
}
}

return resourceAwsOrganizationsOrganizationRead(d, meta)
}

Expand Down Expand Up @@ -181,6 +221,18 @@ func resourceAwsOrganizationsOrganizationRead(d *schema.ResourceData, meta inter
return fmt.Errorf("error setting aws_service_access_principals: %s", err)
}

enabledPolicyTypes := make([]string, 0)

for _, policyType := range roots[0].PolicyTypes {
if aws.StringValue(policyType.Status) == organizations.PolicyTypeStatusEnabled || aws.StringValue(policyType.Status) == organizations.PolicyTypeStatusPendingEnable {
Copy link
Contributor

Choose a reason for hiding this comment

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

should we be returning that it's active when it's still potentially Pending here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

A lot of the AWS resources currently treat pending statuses similar to their end state during read to account for scenarios where changes might have occurred outside Terraform or for eventual consistency reasons. This one was a holdout before I implemented the waiter functions as during my local testing of this it didn't appear to display any eventual consistency issues. I'll remove it and verify everything still looks okay. 👍

enabledPolicyTypes = append(enabledPolicyTypes, aws.StringValue(policyType.Type))
}
}

if err := d.Set("enabled_policy_types", enabledPolicyTypes); err != nil {
return fmt.Errorf("error setting enabled_policy_types: %s", err)
}

return nil
}

Expand Down Expand Up @@ -221,6 +273,47 @@ func resourceAwsOrganizationsOrganizationUpdate(d *schema.ResourceData, meta int
}
}

if d.HasChange("enabled_policy_types") {
defaultRootID := d.Get("roots.0.id").(string)
o, n := d.GetChange("enabled_policy_types")
oldSet := o.(*schema.Set)
newSet := n.(*schema.Set)

for _, v := range oldSet.Difference(newSet).List() {
policyType := v.(string)
input := &organizations.DisablePolicyTypeInput{
PolicyType: aws.String(policyType),
RootId: aws.String(defaultRootID),
}

log.Printf("[DEBUG] Disabling Policy Type in Organization: %s", input)
if _, err := conn.DisablePolicyType(input); err != nil {
return fmt.Errorf("error disabling policy type (%s) in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err)
}

if err := waitForOrganizationDefaultRootPolicyTypeDisable(conn, policyType); err != nil {
return fmt.Errorf("error waiting for policy type (%s) disabling in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err)
}
}

for _, v := range newSet.Difference(oldSet).List() {
policyType := v.(string)
input := &organizations.EnablePolicyTypeInput{
PolicyType: aws.String(policyType),
RootId: aws.String(d.Get("roots.0.id").(string)),
Copy link
Contributor

Choose a reason for hiding this comment

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

minor we can use defaultRootID here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes we can! Thanks!

}

log.Printf("[DEBUG] Enabling Policy Type in Organization: %s", input)
if _, err := conn.EnablePolicyType(input); err != nil {
return fmt.Errorf("error enabling policy type (%s) in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err)
}

if err := waitForOrganizationDefaultRootPolicyTypeEnable(conn, policyType); err != nil {
return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err)
}
}
}

return resourceAwsOrganizationsOrganizationRead(d, meta)
}

Expand Down Expand Up @@ -266,3 +359,73 @@ func flattenOrganizationsRootPolicyTypeSummaries(summaries []*organizations.Poli
}
return result
}

func getOrganizationDefaultRoot(conn *organizations.Organizations) (*organizations.Root, error) {
var roots []*organizations.Root

err := conn.ListRootsPages(&organizations.ListRootsInput{}, func(page *organizations.ListRootsOutput, lastPage bool) bool {
roots = append(roots, page.Roots...)

return !lastPage
})

if err != nil {
return nil, err
}

if len(roots) == 0 {
return nil, fmt.Errorf("no roots found")
}

return roots[0], nil
}

func getOrganizationDefaultRootPolicyTypeRefreshFunc(conn *organizations.Organizations, policyType string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
defaultRoot, err := getOrganizationDefaultRoot(conn)

if err != nil {
return nil, "", fmt.Errorf("error getting default root: %s", err)
}

for _, pt := range defaultRoot.PolicyTypes {
if aws.StringValue(pt.Type) == policyType {
return pt, aws.StringValue(pt.Status), nil
}
}

return &organizations.PolicyTypeSummary{}, organizationsPolicyTypeStatusDisabled, nil
}
}

func waitForOrganizationDefaultRootPolicyTypeDisable(conn *organizations.Organizations, policyType string) error {
stateConf := &resource.StateChangeConf{
Pending: []string{
organizations.PolicyTypeStatusEnabled,
organizations.PolicyTypeStatusPendingDisable,
},
Target: []string{organizationsPolicyTypeStatusDisabled},
Refresh: getOrganizationDefaultRootPolicyTypeRefreshFunc(conn, policyType),
Timeout: 5 * time.Minute,
}

_, err := stateConf.WaitForState()

return err
}

func waitForOrganizationDefaultRootPolicyTypeEnable(conn *organizations.Organizations, policyType string) error {
stateConf := &resource.StateChangeConf{
Pending: []string{
organizationsPolicyTypeStatusDisabled,
organizations.PolicyTypeStatusPendingEnable,
},
Target: []string{organizations.PolicyTypeStatusEnabled},
Refresh: getOrganizationDefaultRootPolicyTypeRefreshFunc(conn, policyType),
Timeout: 5 * time.Minute,
}

_, err := stateConf.WaitForState()

return err
}
52 changes: 50 additions & 2 deletions aws/resource_aws_organizations_organization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package aws

import (
"fmt"
"regexp"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/organizations"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"regexp"
"testing"
)

func testAccAwsOrganizationsOrganization_basic(t *testing.T) {
Expand Down Expand Up @@ -88,6 +89,45 @@ func testAccAwsOrganizationsOrganization_AwsServiceAccessPrincipals(t *testing.T
})
}

func testAccAwsOrganizationsOrganization_EnabledPolicyTypes(t *testing.T) {
var organization organizations.Organization
resourceName := "aws_organizations_organization.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsOrganizationsOrganizationDestroy,
Steps: []resource.TestStep{
{
Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeServiceControlPolicy),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization),
resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAwsOrganizationsOrganizationConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization),
resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "0"),
),
},
{
Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeServiceControlPolicy),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization),
resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"),
),
},
},
})
}

func testAccAwsOrganizationsOrganization_FeatureSet(t *testing.T) {
var organization organizations.Organization
resourceName := "aws_organizations_organization.test"
Expand Down Expand Up @@ -189,6 +229,14 @@ resource "aws_organizations_organization" "test" {
`, principal1, principal2)
}

func testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(policyType1 string) string {
return fmt.Sprintf(`
resource "aws_organizations_organization" "test" {
enabled_policy_types = [%[1]q]
}
`, policyType1)
}

func testAccAwsOrganizationsOrganizationConfigFeatureSet(featureSet string) string {
return fmt.Sprintf(`
resource "aws_organizations_organization" "test" {
Expand Down
Loading