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

New resource for Macie2 Organization Admin Account #19303

Merged
merged 5 commits into from
May 14, 2021
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
3 changes: 3 additions & 0 deletions .changelog/19303.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_macie2_organization_admin_account
```
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,7 @@ func Provider() *schema.Provider {
"aws_macie2_classification_job": resourceAwsMacie2ClassificationJob(),
"aws_macie2_custom_data_identifier": resourceAwsMacie2CustomDataIdentifier(),
"aws_macie2_findings_filter": resourceAwsMacie2FindingsFilter(),
"aws_macie2_organization_admin_account": resourceAwsMacie2OrganizationAdminAccount(),
"aws_macie_member_account_association": resourceAwsMacieMemberAccountAssociation(),
"aws_macie_s3_bucket_association": resourceAwsMacieS3BucketAssociation(),
"aws_main_route_table_association": resourceAwsMainRouteTableAssociation(),
Expand Down
140 changes: 140 additions & 0 deletions aws/resource_aws_macie2_organization_admin_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package aws

import (
"context"
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/macie2"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourceAwsMacie2OrganizationAdminAccount() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceMacie2OrganizationAdminAccountCreate,
ReadWithoutTimeout: resourceMacie2OrganizationAdminAccountRead,
DeleteWithoutTimeout: resourceMacie2OrganizationAdminAccountDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"admin_account_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}

func resourceMacie2OrganizationAdminAccountCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).macie2conn
adminAccountID := d.Get("admin_account_id").(string)
input := &macie2.EnableOrganizationAdminAccountInput{
AdminAccountId: aws.String(adminAccountID),
ClientToken: aws.String(resource.UniqueId()),
}

var err error
err = resource.RetryContext(ctx, 4*time.Minute, func() *resource.RetryError {
_, err := conn.EnableOrganizationAdminAccountWithContext(ctx, input)

if tfawserr.ErrCodeEquals(err, macie2.ErrorCodeClientError) {
return resource.RetryableError(err)
}

if err != nil {
return resource.NonRetryableError(err)
}

return nil
})

if isResourceTimeoutError(err) {
_, err = conn.EnableOrganizationAdminAccountWithContext(ctx, input)
}

if err != nil {
return diag.FromErr(fmt.Errorf("error creating Macie OrganizationAdminAccount: %w", err))
}

d.SetId(adminAccountID)

return resourceMacie2OrganizationAdminAccountRead(ctx, d, meta)
}

func resourceMacie2OrganizationAdminAccountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).macie2conn

var err error

res, err := getMacie2OrganizationAdminAccount(conn, d.Id())

if err != nil {
if tfawserr.ErrCodeEquals(err, macie2.ErrCodeResourceNotFoundException) ||
tfawserr.ErrMessageContains(err, macie2.ErrCodeAccessDeniedException, "Macie is not enabled") {
log.Printf("[WARN] Macie OrganizationAdminAccount (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return diag.FromErr(fmt.Errorf("error reading Macie OrganizationAdminAccount (%s): %w", d.Id(), err))
}

if res == nil {
log.Printf("[WARN] Macie OrganizationAdminAccount (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

d.Set("admin_account_id", res.AccountId)

return nil
}

func resourceMacie2OrganizationAdminAccountDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).macie2conn

input := &macie2.DisableOrganizationAdminAccountInput{
AdminAccountId: aws.String(d.Id()),
}

_, err := conn.DisableOrganizationAdminAccountWithContext(ctx, input)
if err != nil {
if tfawserr.ErrCodeEquals(err, macie2.ErrCodeResourceNotFoundException) ||
tfawserr.ErrMessageContains(err, macie2.ErrCodeAccessDeniedException, "Macie is not enabled") {
return nil
}
return diag.FromErr(fmt.Errorf("error deleting Macie OrganizationAdminAccount (%s): %w", d.Id(), err))
}
return nil
}

func getMacie2OrganizationAdminAccount(conn *macie2.Macie2, adminAccountID string) (*macie2.AdminAccount, error) {
var res *macie2.AdminAccount

err := conn.ListOrganizationAdminAccountsPages(&macie2.ListOrganizationAdminAccountsInput{}, func(page *macie2.ListOrganizationAdminAccountsOutput, lastPage bool) bool {
if page == nil {
return !lastPage
}

for _, adminAccount := range page.AdminAccounts {
if adminAccount == nil {
continue
}

if aws.StringValue(adminAccount.AccountId) == adminAccountID {
res = adminAccount
return false
}
}

return !lastPage
})

return res, err
}
123 changes: 123 additions & 0 deletions aws/resource_aws_macie2_organization_admin_account_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/macie2"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func testAccAwsMacie2OrganizationAdminAccount_basic(t *testing.T) {
resourceName := "aws_macie2_organization_admin_account.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Copy link
Contributor

Choose a reason for hiding this comment

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

Because we're creating an Organization, we have to add a PreCheck that ensures we're not already in an Organization account

Suggested change
PreCheck: func() { testAccPreCheck(t) },
PreCheck: func() {
testAccPreCheck(t)
testAccOrganizationsAccountPreCheck(t)
},

ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccCheckAwsMacie2OrganizationAdminAccountDestroy,
ErrorCheck: testAccErrorCheck(t, macie2.EndpointsID),
Copy link
Contributor

Choose a reason for hiding this comment

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

The Organization Admin Account tests fail if they are run in an AWS Organization member (non management) account with the error AccessDeniedException: The request failed because you must be a user of the management account for your AWS organization to perform this operation.

You can add a custom ErrorCheck function for this resource that tests for that error message, e.g.

Suggested change
ErrorCheck: testAccErrorCheck(t, macie2.EndpointsID),
ErrorCheck: testAccErrorCheckSkipMacie2OrganizationAdminAccount(t),

and

func testAccErrorCheckSkipMacie2OrganizationAdminAccount(t *testing.T) resource.ErrorCheckFunc {
	return testAccErrorCheckSkipMessagesContaining(t,
		"AccessDeniedException: The request failed because you must be a user of the management account for your AWS organization to perform this operation",
	)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Understood, thank you for the suggestion, graham 👍

Steps: []resource.TestStep{
{
Config: testAccAwsMacieOrganizationAdminAccountConfigBasic(),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsMacie2OrganizationAdminAccountExists(resourceName),
testAccCheckResourceAttrAccountID(resourceName, "admin_account_id"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccAwsMacie2OrganizationAdminAccount_disappears(t *testing.T) {
resourceName := "aws_macie2_organization_admin_account.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccCheckAwsMacie2OrganizationAdminAccountDestroy,
ErrorCheck: testAccErrorCheck(t, macie2.EndpointsID),
Steps: []resource.TestStep{
{
Config: testAccAwsMacieOrganizationAdminAccountConfigBasic(),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsMacie2OrganizationAdminAccountExists(resourceName),
testAccCheckResourceDisappears(testAccProvider, resourceAwsMacie2Account(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckAwsMacie2OrganizationAdminAccountExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

conn := testAccProvider.Meta().(*AWSClient).macie2conn

adminAccount, err := getMacie2OrganizationAdminAccount(conn, rs.Primary.ID)

if err != nil {
return err
}

if adminAccount == nil {
return fmt.Errorf("macie OrganizationAdminAccount (%s) not found", rs.Primary.ID)
}

return nil
}
}

func testAccCheckAwsMacie2OrganizationAdminAccountDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).macie2conn

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

adminAccount, err := getMacie2OrganizationAdminAccount(conn, rs.Primary.ID)

if tfawserr.ErrCodeEquals(err, macie2.ErrCodeResourceNotFoundException) ||
tfawserr.ErrMessageContains(err, macie2.ErrCodeAccessDeniedException, "Macie is not enabled") {
continue
}

if adminAccount == nil {
continue
}

if err != nil {
return err
}

return fmt.Errorf("macie OrganizationAdminAccount %q still exists", rs.Primary.ID)
}

return nil

}

func testAccAwsMacieOrganizationAdminAccountConfigBasic() string {
return `
data "aws_caller_identity" "current" {}

resource "aws_macie2_account" "test" {}

gdavison marked this conversation as resolved.
Show resolved Hide resolved
resource "aws_macie2_organization_admin_account" "test" {
admin_account_id = data.aws_caller_identity.current.account_id
depends_on = [aws_macie2_account.test]
}
`
}
4 changes: 4 additions & 0 deletions aws/resource_aws_macie2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ func TestAccAWSMacie2_serial(t *testing.T) {
"number": testAccAwsMacie2FindingsFilter_WithNumber,
"tags": testAccAwsMacie2FindingsFilter_withTags,
},
"OrganizationAdminAccount": {
"basic": testAccAwsMacie2OrganizationAdminAccount_basic,
"disappears": testAccAwsMacie2OrganizationAdminAccount_disappears,
},
}

for group, m := range testCases {
Expand Down
42 changes: 42 additions & 0 deletions website/docs/r/macie2_organization_admin_account.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
subcategory: "Macie"
layout: "aws"
page_title: "AWS: aws_macie2_organization_admin_account"
description: |-
Provides a resource to manage an Amazon Macie Organization Admin Account.
---

# Resource: aws_macie2_organization_admin_account

Provides a resource to manage an [Amazon Macie Organization Admin Account](https://docs.aws.amazon.com/macie/latest/APIReference/admin.html).

## Example Usage

```terraform
resource "aws_macie2_account" "example" {}

resource "aws_macie2_organization_admin_account" "test" {
admin_account_id = "ID OF THE ADMIN ACCOUNT"
depends_on = [aws_macie2_account.test]
}
```

## Argument Reference

The following arguments are supported:

* `admin_account_id` - (Required) The AWS account ID for the account to designate as the delegated Amazon Macie administrator account for the organization.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `id` - The unique identifier (ID) of the macie organization admin account.

## Import

`aws_macie2_organization_admin_account` can be imported using the id, e.g.

```
$ terraform import aws_macie2_organization_admin_account.example abcd1
```