Skip to content

Commit

Permalink
Merge pull request #2911 from bflad/f-aws_guardduty_member
Browse files Browse the repository at this point in the history
New Resource: aws_guardduty_member
  • Loading branch information
bflad authored Jan 11, 2018
2 parents cdc0146 + c3ab8de commit d811d63
Show file tree
Hide file tree
Showing 6 changed files with 332 additions and 0 deletions.
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@ func Provider() terraform.ResourceProvider {
"aws_glacier_vault": resourceAwsGlacierVault(),
"aws_glue_catalog_database": resourceAwsGlueCatalogDatabase(),
"aws_guardduty_detector": resourceAwsGuardDutyDetector(),
"aws_guardduty_member": resourceAwsGuardDutyMember(),
"aws_iam_access_key": resourceAwsIamAccessKey(),
"aws_iam_account_alias": resourceAwsIamAccountAlias(),
"aws_iam_account_password_policy": resourceAwsIamAccountPasswordPolicy(),
Expand Down
134 changes: 134 additions & 0 deletions aws/resource_aws_guardduty_member.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package aws

import (
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/guardduty"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsGuardDutyMember() *schema.Resource {
return &schema.Resource{
Create: resourceAwsGuardDutyMemberCreate,
Read: resourceAwsGuardDutyMemberRead,
Delete: resourceAwsGuardDutyMemberDelete,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAwsAccountId,
},
"detector_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"email": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}

func resourceAwsGuardDutyMemberCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).guarddutyconn
accountID := d.Get("account_id").(string)
detectorID := d.Get("detector_id").(string)

input := guardduty.CreateMembersInput{
AccountDetails: []*guardduty.AccountDetail{{
AccountId: aws.String(accountID),
Email: aws.String(d.Get("email").(string)),
}},
DetectorId: aws.String(detectorID),
}

log.Printf("[DEBUG] Creating GuardDuty Member: %s", input)
_, err := conn.CreateMembers(&input)
if err != nil {
return fmt.Errorf("Creating GuardDuty Member failed: %s", err.Error())
}
d.SetId(fmt.Sprintf("%s:%s", detectorID, accountID))

return resourceAwsGuardDutyMemberRead(d, meta)
}

func resourceAwsGuardDutyMemberRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).guarddutyconn

accountID, detectorID, err := decodeGuardDutyMemberID(d.Id())
if err != nil {
return err
}

input := guardduty.GetMembersInput{
AccountIds: []*string{aws.String(accountID)},
DetectorId: aws.String(detectorID),
}

log.Printf("[DEBUG] Reading GuardDuty Member: %s", input)
gmo, err := conn.GetMembers(&input)
if err != nil {
if isAWSErr(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") {
log.Printf("[WARN] GuardDuty detector %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Reading GuardDuty Member '%s' failed: %s", d.Id(), err.Error())
}

if gmo.Members == nil || (len(gmo.Members) < 1) {
log.Printf("[WARN] GuardDuty Member %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
member := gmo.Members[0]
d.Set("account_id", member.AccountId)
d.Set("detector_id", detectorID)
d.Set("email", member.Email)

return nil
}

func resourceAwsGuardDutyMemberDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).guarddutyconn

accountID, detectorID, err := decodeGuardDutyMemberID(d.Id())
if err != nil {
return err
}

input := guardduty.DeleteMembersInput{
AccountIds: []*string{aws.String(accountID)},
DetectorId: aws.String(detectorID),
}

log.Printf("[DEBUG] Delete GuardDuty Member: %s", input)
_, err = conn.DeleteMembers(&input)
if err != nil {
return fmt.Errorf("Deleting GuardDuty Member '%s' failed: %s", d.Id(), err.Error())
}
return nil
}

func decodeGuardDutyMemberID(id string) (accountID, detectorID string, err error) {
parts := strings.Split(id, ":")
if len(parts) != 2 {
err = fmt.Errorf("GuardDuty Member ID must be of the form <Detector ID>:<Member AWS Account ID>, was provided: %s", id)
return
}
accountID = parts[1]
detectorID = parts[0]
return
}
134 changes: 134 additions & 0 deletions aws/resource_aws_guardduty_member_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/guardduty"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func testAccAwsGuardDutyMember_basic(t *testing.T) {
resourceName := "aws_guardduty_member.test"
accountID := "111111111111"
email := "required@example.com"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsGuardDutyMemberDestroy,
Steps: []resource.TestStep{
{
Config: testAccGuardDutyMemberConfig_basic(accountID, email),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsGuardDutyMemberExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "account_id", accountID),
resource.TestCheckResourceAttrSet(resourceName, "detector_id"),
resource.TestCheckResourceAttr(resourceName, "email", email),
),
},
},
})
}

func testAccAwsGuardDutyMember_import(t *testing.T) {
resourceName := "aws_guardduty_member.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSesTemplateDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGuardDutyMemberConfig_basic("111111111111", "required@example.com"),
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

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

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

accountID, detectorID, err := decodeGuardDutyMemberID(rs.Primary.ID)
if err != nil {
return err
}

input := &guardduty.GetMembersInput{
AccountIds: []*string{aws.String(accountID)},
DetectorId: aws.String(detectorID),
}

gmo, err := conn.GetMembers(input)
if err != nil {
if isAWSErr(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") {
return nil
}
return err
}

if len(gmo.Members) < 1 {
continue
}

return fmt.Errorf("Expected GuardDuty Detector to be destroyed, %s found", rs.Primary.ID)
}

return nil
}

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

accountID, detectorID, err := decodeGuardDutyMemberID(rs.Primary.ID)
if err != nil {
return err
}

input := &guardduty.GetMembersInput{
AccountIds: []*string{aws.String(accountID)},
DetectorId: aws.String(detectorID),
}

conn := testAccProvider.Meta().(*AWSClient).guarddutyconn
gmo, err := conn.GetMembers(input)
if err != nil {
return err
}

if len(gmo.Members) < 1 {
return fmt.Errorf("Not found: %s", name)
}

return nil
}
}

func testAccGuardDutyMemberConfig_basic(accountID, email string) string {
return fmt.Sprintf(`
%[1]s
resource "aws_guardduty_member" "test" {
account_id = "%[2]s"
detector_id = "${aws_guardduty_detector.test.id}"
email = "%[3]s"
}
`, testAccGuardDutyDetectorConfig_basic1, accountID, email)
}
4 changes: 4 additions & 0 deletions aws/resource_aws_guardduty_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ func TestAccAWSGuardDuty(t *testing.T) {
"basic": testAccAwsGuardDutyDetector_basic,
"import": testAccAwsGuardDutyDetector_import,
},
"Member": {
"basic": testAccAwsGuardDutyMember_basic,
"import": testAccAwsGuardDutyMember_import,
},
}

for group, m := range testCases {
Expand Down
4 changes: 4 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,10 @@
<li<%= sidebar_current("docs-aws-resource-guardduty-detector") %>>
<a href="/docs/providers/aws/r/guardduty_detector.html">aws_guardduty_detector</a>
</li>

<li<%= sidebar_current("docs-aws-resource-guardduty-member") %>>
<a href="/docs/providers/aws/r/guardduty_member.html">aws_guardduty_member</a>
</li>
</ul>
</li>

Expand Down
55 changes: 55 additions & 0 deletions website/docs/r/guardduty_member.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
layout: "aws"
page_title: "AWS: aws_guardduty_member"
sidebar_current: "docs-aws-resource-guardduty-member"
description: |-
Provides a resource to manage a GuardDuty member
---

# aws_guardduty_member

Provides a resource to manage a GuardDuty member.

~> **NOTE:** Currently after using this resource, you must manually invite and accept member account invitations before GuardDuty will begin sending cross-account events. More information for how to accomplish this via the AWS Console or API can be found in the [GuardDuty User Guide](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_accounts.html). Terraform implementation of member invitation and acceptance resources can be tracked in [Github](https://github.com/terraform-providers/terraform-provider-aws/issues/2489).

## Example Usage

```hcl
resource "aws_guardduty_detector" "master" {
enable = true
}
resource "aws_guardduty_detector" "member" {
provider = "aws.dev"
enable = true
}
resource "aws_guardduty_member" "member" {
account_id = "${aws_guardduty_detector.member.account_id}"
detector_id = "${aws_guardduty_detector.master.id}"
email = "required@example.com"
}
```

## Argument Reference

The following arguments are supported:

* `account_id` - (Required) AWS account ID for member account.
* `detector_id` - (Required) The detector ID of the GuardDuty account where you want to create member accounts.
* `email` - (Required) Email address for member account.

## Attributes Reference

The following additional attributes are exported:

* `id` - The ID of the GuardDuty member

## Import

GuardDuty members can be imported using the the master GuardDuty detector ID and member AWS account ID, e.g.

```
$ terraform import aws_guardduty_member.MyMember 00b00fd5aecc0ab60a708659477e9617:123456789012
```

0 comments on commit d811d63

Please sign in to comment.