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

Add account_id for aws_account_alternate_contact to manage member accounts in an AWS organization #21888

Merged
merged 5 commits into from
Dec 1, 2021
Merged
Show file tree
Hide file tree
Changes from all 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/21888.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:enhancement
resource/aws_account_alternate_contact: Add `account_id` argument
```
88 changes: 79 additions & 9 deletions internal/service/account/alternate_contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package account

import (
"context"
"fmt"
"log"
"regexp"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/account"
Expand All @@ -14,6 +16,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)

func ResourceAlternateContact() *schema.Resource {
Expand All @@ -33,6 +36,12 @@ func ResourceAlternateContact() *schema.Resource {
ForceNew: true,
ValidateFunc: validation.StringInSlice(account.AlternateContactType_Values(), false),
},
"account_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: verify.ValidAccountID,
},
"email_address": {
Type: schema.TypeString,
Required: true,
Expand Down Expand Up @@ -69,22 +78,34 @@ func resourceAlternateContactCreate(ctx context.Context, d *schema.ResourceData,
Title: aws.String(d.Get("title").(string)),
}

accountID := d.Get("account_id").(string)
if accountID != "" {
input.AccountId = aws.String(accountID)
}
id := AlternateContactCreateResourceID(accountID, contactType)

log.Printf("[DEBUG] Creating Account Alternate Contact: %s", input)
_, err := conn.PutAlternateContactWithContext(ctx, input)

if err != nil {
return diag.Errorf("error creating Account Alternate Contact (%s): %s", contactType, err)
return diag.Errorf("error creating Account Alternate Contact (%s): %s", id, err)
}

d.SetId(contactType)
d.SetId(id)

return resourceAlternateContactRead(ctx, d, meta)
}

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

output, err := FindAlternateContactByContactType(ctx, conn, d.Id())
accountID, contactType, err := AlternateContactParseResourceID(d.Id())

if err != nil {
return diag.FromErr(err)
}

output, err := FindAlternateContactByAccountIDAndContactType(ctx, conn, accountID, contactType)

if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Account Alternate Contact (%s) not found, removing from state", d.Id())
Expand All @@ -96,6 +117,7 @@ func resourceAlternateContactRead(ctx context.Context, d *schema.ResourceData, m
return diag.Errorf("error reading Account Alternate Contact (%s): %s", d.Id(), err)
}

d.Set("account_id", accountID)
d.Set("alternate_contact_type", output.AlternateContactType)
d.Set("email_address", output.EmailAddress)
d.Set("name", output.Name)
Expand All @@ -108,16 +130,26 @@ func resourceAlternateContactRead(ctx context.Context, d *schema.ResourceData, m
func resourceAlternateContactUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).AccountConn

accountID, contactType, err := AlternateContactParseResourceID(d.Id())

if err != nil {
return diag.FromErr(err)
}

input := &account.PutAlternateContactInput{
AlternateContactType: aws.String(d.Id()),
AlternateContactType: aws.String(contactType),
EmailAddress: aws.String(d.Get("email_address").(string)),
Name: aws.String(d.Get("name").(string)),
PhoneNumber: aws.String(d.Get("phone_number").(string)),
Title: aws.String(d.Get("title").(string)),
}

if accountID != "" {
input.AccountId = aws.String(accountID)
}

log.Printf("[DEBUG] Updating Account Alternate Contact: %s", input)
_, err := conn.PutAlternateContactWithContext(ctx, input)
_, err = conn.PutAlternateContactWithContext(ctx, input)

if err != nil {
return diag.Errorf("error updating Account Alternate Contact (%s): %s", d.Id(), err)
Expand All @@ -129,10 +161,22 @@ func resourceAlternateContactUpdate(ctx context.Context, d *schema.ResourceData,
func resourceAlternateContactDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).AccountConn

accountID, contactType, err := AlternateContactParseResourceID(d.Id())

if err != nil {
return diag.FromErr(err)
}

input := &account.DeleteAlternateContactInput{
AlternateContactType: aws.String(contactType),
}

if accountID != "" {
input.AccountId = aws.String(accountID)
}

log.Printf("[DEBUG] Deleting Account Alternate Contact: %s", d.Id())
_, err := conn.DeleteAlternateContactWithContext(ctx, &account.DeleteAlternateContactInput{
AlternateContactType: aws.String(d.Id()),
})
_, err = conn.DeleteAlternateContactWithContext(ctx, input)

if tfawserr.ErrCodeEquals(err, account.ErrCodeResourceNotFoundException) {
return nil
Expand All @@ -145,11 +189,15 @@ func resourceAlternateContactDelete(ctx context.Context, d *schema.ResourceData,
return nil
}

func FindAlternateContactByContactType(ctx context.Context, conn *account.Account, contactType string) (*account.AlternateContact, error) {
func FindAlternateContactByAccountIDAndContactType(ctx context.Context, conn *account.Account, accountID, contactType string) (*account.AlternateContact, error) {
input := &account.GetAlternateContactInput{
AlternateContactType: aws.String(contactType),
}

if accountID != "" {
input.AccountId = aws.String(accountID)
}

output, err := conn.GetAlternateContactWithContext(ctx, input)

if tfawserr.ErrCodeEquals(err, account.ErrCodeResourceNotFoundException) {
Expand All @@ -169,3 +217,25 @@ func FindAlternateContactByContactType(ctx context.Context, conn *account.Accoun

return output.AlternateContact, nil
}

const alternateContactResourceIDSeparator = "/"

func AlternateContactCreateResourceID(accountID, contactType string) string {
parts := []string{accountID, contactType}
id := strings.Join(parts, alternateContactResourceIDSeparator)

return id
}

func AlternateContactParseResourceID(id string) (string, string, error) {
parts := strings.Split(id, alternateContactResourceIDSeparator)

switch len(parts) {
case 1:
return "", parts[0], nil
case 2:
return parts[0], parts[1], nil
default:
return "", "", fmt.Errorf("unexpected format for ID (%[1]s), expected ContactType or AccountID%[2]sContactType", id, alternateContactResourceIDSeparator)
}
}
92 changes: 89 additions & 3 deletions internal/service/account/alternate_contact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/aws/aws-sdk-go/service/account"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
Expand All @@ -33,6 +34,7 @@ func TestAccAccountAlternateContact_basic(t *testing.T) {
Config: testAccountAlternateContactConfig(rName1, emailAddress1),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAccountAlternateContactExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "account_id", ""),
resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"),
resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress1),
resource.TestCheckResourceAttr(resourceName, "name", rName1),
Expand All @@ -49,6 +51,7 @@ func TestAccAccountAlternateContact_basic(t *testing.T) {
Config: testAccountAlternateContactConfig(rName2, emailAddress2),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAccountAlternateContactExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "account_id", ""),
resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"),
resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress2),
resource.TestCheckResourceAttr(resourceName, "name", rName2),
Expand Down Expand Up @@ -84,6 +87,59 @@ func TestAccAccountAlternateContact_disappears(t *testing.T) {
})
}

func TestAccAccountAlternateContact_accountID(t *testing.T) {
var providers []*schema.Provider
resourceName := "aws_account_alternate_contact.test"
domain := acctest.RandomDomainName()
emailAddress1 := acctest.RandomEmailAddress(domain)
emailAddress2 := acctest.RandomEmailAddress(domain)
rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.Test(t, resource.TestCase{
PreCheck: func() {
acctest.PreCheck(t)
acctest.PreCheckAlternateAccount(t)
acctest.PreCheckOrganizationManagementAccount(t)
testAccPreCheck(t)
},
ErrorCheck: acctest.ErrorCheck(t, account.EndpointsID),
ProviderFactories: acctest.FactoriesAlternate(&providers),
CheckDestroy: testAccountAlternateContactDestroy,
Steps: []resource.TestStep{
{
Config: testAccountAlternateContactOrganizationConfig(rName1, emailAddress1),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAccountAlternateContactExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "account_id"),
resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"),
resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress1),
resource.TestCheckResourceAttr(resourceName, "name", rName1),
resource.TestCheckResourceAttr(resourceName, "phone_number", "+17031235555"),
resource.TestCheckResourceAttr(resourceName, "title", rName1),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccountAlternateContactOrganizationConfig(rName2, emailAddress2),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAccountAlternateContactExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "account_id"),
resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"),
resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress2),
resource.TestCheckResourceAttr(resourceName, "name", rName2),
resource.TestCheckResourceAttr(resourceName, "phone_number", "+17031235555"),
resource.TestCheckResourceAttr(resourceName, "title", rName2),
),
},
},
})
}

func testAccountAlternateContactDestroy(s *terraform.State) error {
ctx := context.TODO()
conn := acctest.Provider.Meta().(*conns.AWSClient).AccountConn
Expand All @@ -93,7 +149,13 @@ func testAccountAlternateContactDestroy(s *terraform.State) error {
continue
}

_, err := tfaccount.FindAlternateContactByContactType(ctx, conn, rs.Primary.ID)
accountID, contactType, err := tfaccount.AlternateContactParseResourceID(rs.Primary.ID)

if err != nil {
return err
}

_, err = tfaccount.FindAlternateContactByAccountIDAndContactType(ctx, conn, accountID, contactType)

if tfresource.NotFound(err) {
continue
Expand Down Expand Up @@ -121,10 +183,16 @@ func testAccCheckAccountAlternateContactExists(n string) resource.TestCheckFunc
return fmt.Errorf("No Account Alternate Contact ID is set")
}

accountID, contactType, err := tfaccount.AlternateContactParseResourceID(rs.Primary.ID)

if err != nil {
return err
}

ctx := context.TODO()
conn := acctest.Provider.Meta().(*conns.AWSClient).AccountConn

_, err := tfaccount.FindAlternateContactByContactType(ctx, conn, rs.Primary.ID)
_, err = tfaccount.FindAlternateContactByAccountIDAndContactType(ctx, conn, accountID, contactType)

if err != nil {
return err
Expand All @@ -147,11 +215,29 @@ resource "aws_account_alternate_contact" "test" {
`, rName, emailAddress)
}

func testAccountAlternateContactOrganizationConfig(rName, emailAddress string) string {
return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(`
data "aws_caller_identity" "test" {
provider = "awsalternate"
}

resource "aws_account_alternate_contact" "test" {
account_id = data.aws_caller_identity.test.account_id
alternate_contact_type = "OPERATIONS"

email_address = %[2]q
name = %[1]q
phone_number = "+17031235555"
title = %[1]q
}
`, rName, emailAddress))
}

func testAccPreCheck(t *testing.T) {
ctx := context.TODO()
conn := acctest.Provider.Meta().(*conns.AWSClient).AccountConn

_, err := tfaccount.FindAlternateContactByContactType(ctx, conn, account.AlternateContactTypeOperations)
_, err := tfaccount.FindAlternateContactByAccountIDAndContactType(ctx, conn, "", account.AlternateContactTypeOperations)

if acctest.PreCheckSkipError(err) {
t.Skipf("skipping acceptance testing: %s", err)
Expand Down
2 changes: 2 additions & 0 deletions website/docs/r/account_alternate_contact.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Manages the specified alternate contact attached to an AWS Account.

```terraform
resource "aws_account_alternate_contact" "operations" {

alternate_contact_type = "OPERATIONS"

name = "Example"
Expand All @@ -27,6 +28,7 @@ resource "aws_account_alternate_contact" "operations" {

The following arguments are supported:

* `account_id` - (Optional) The ID of the target account when managing member accounts. Will manage current user's account by default if omitted.
* `alternate_contact_type` - (Required) The type of the alternate contact. Allowed values are: `BILLING`, `OPERATIONS`, `SECURITY`.
* `email_address` - (Required) An email address for the alternate contact.
* `name` - (Required) The name of the alternate contact.
Expand Down