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_account: Add tags argument #9202

Merged
merged 2 commits into from
Jul 8, 2019
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
65 changes: 65 additions & 0 deletions aws/resource_aws_organizations_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func resourceAwsOrganizationsAccount() *schema.Resource {
Optional: true,
ValidateFunc: validateAwsOrganizationsAccountRoleName,
},
"tags": tagsSchema(),
},
}
}
Expand Down Expand Up @@ -162,6 +163,19 @@ func resourceAwsOrganizationsAccountCreate(d *schema.ResourceData, meta interfac
}
}

if tags := tagsFromMapOrganizations(d.Get("tags").(map[string]interface{})); len(tags) > 0 {
input := &organizations.TagResourceInput{
ResourceId: aws.String(d.Id()),
Tags: tags,
}

log.Printf("[DEBUG] Adding Organizations Account (%s) tags: %s", d.Id(), input)

if _, err := conn.TagResource(input); err != nil {
return fmt.Errorf("error updating Organizations Account (%s) tags: %s", d.Id(), err)
}
}

return resourceAwsOrganizationsAccountRead(d, meta)
}

Expand Down Expand Up @@ -194,6 +208,20 @@ func resourceAwsOrganizationsAccountRead(d *schema.ResourceData, meta interface{
return fmt.Errorf("error getting AWS Organizations Account (%s) parent: %s", d.Id(), err)
}

tagsInput := &organizations.ListTagsForResourceInput{
ResourceId: aws.String(d.Id()),
}

tagsOutput, err := conn.ListTagsForResource(tagsInput)

if err != nil {
return fmt.Errorf("error reading Organizations Account (%s) tags: %s", d.Id(), err)
}

if tagsOutput == nil {
return fmt.Errorf("error reading Organizations Account (%s) tags: empty result", d.Id())
}

d.Set("arn", account.Arn)
d.Set("email", account.Email)
d.Set("joined_method", account.JoinedMethod)
Expand All @@ -202,6 +230,10 @@ func resourceAwsOrganizationsAccountRead(d *schema.ResourceData, meta interface{
d.Set("parent_id", parentId)
d.Set("status", account.Status)

if err := d.Set("tags", tagsToMapOrganizations(tagsOutput.Tags)); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}

return nil
}

Expand All @@ -222,6 +254,39 @@ func resourceAwsOrganizationsAccountUpdate(d *schema.ResourceData, meta interfac
}
}

if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTagsOrganizations(tagsFromMapOrganizations(o), tagsFromMapOrganizations(n))

// Set tags
if len(remove) > 0 {
input := &organizations.UntagResourceInput{
ResourceId: aws.String(d.Id()),
TagKeys: remove,
}

log.Printf("[DEBUG] Removing Organizations Account (%s) tags: %s", d.Id(), input)

if _, err := conn.UntagResource(input); err != nil {
return fmt.Errorf("error removing Organizations Account (%s) tags: %s", d.Id(), err)
}
}
if len(create) > 0 {
input := &organizations.TagResourceInput{
ResourceId: aws.String(d.Id()),
Tags: create,
}

log.Printf("[DEBUG] Adding Organizations Account (%s) tags: %s", d.Id(), input)

if _, err := conn.TagResource(input); err != nil {
return fmt.Errorf("error updating Organizations Account (%s) tags: %s", d.Id(), err)
}
}
}

return resourceAwsOrganizationsAccountRead(d, meta)
}

Expand Down
86 changes: 86 additions & 0 deletions aws/resource_aws_organizations_account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func testAccAwsOrganizationsAccount_basic(t *testing.T) {
resource.TestCheckResourceAttr("aws_organizations_account.test", "name", name),
resource.TestCheckResourceAttr("aws_organizations_account.test", "email", email),
resource.TestCheckResourceAttrSet("aws_organizations_account.test", "status"),
resource.TestCheckResourceAttr("aws_organizations_account.test", "tags.%", "0"),
),
},
{
Expand Down Expand Up @@ -99,6 +100,60 @@ func testAccAwsOrganizationsAccount_ParentId(t *testing.T) {
})
}

func testAccAwsOrganizationsAccount_Tags(t *testing.T) {
t.Skip("AWS Organizations Account testing is not currently automated due to manual account deletion steps.")

var account organizations.Account

orgsEmailDomain, ok := os.LookupEnv("TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN")

if !ok {
t.Skip("'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.")
}

rInt := acctest.RandInt()
name := fmt.Sprintf("tf_acctest_%d", rInt)
email := fmt.Sprintf("tf-acctest+%d@%s", rInt, orgsEmailDomain)
resourceName := "aws_organizations_account.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsOrganizationsAccountDestroy,
Steps: []resource.TestStep{
{
Config: testAccAwsOrganizationsAccountConfigTags1(name, email, "key1", "value1"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsAccountExists(resourceName, &account),
resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAwsOrganizationsAccountConfigTags2(name, email, "key1", "value1updated", "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsAccountExists(resourceName, &account),
resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"),
resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"),
),
},
{
Config: testAccAwsOrganizationsAccountConfig(name, email),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsOrganizationsAccountExists("aws_organizations_account.test", &account),
resource.TestCheckResourceAttr("aws_organizations_account.test", "tags.%", "0"),
),
},
},
})
}

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

Expand Down Expand Up @@ -210,3 +265,34 @@ resource "aws_organizations_account" "test" {
}
`, name, email)
}

func testAccAwsOrganizationsAccountConfigTags1(name, email, tagKey1, tagValue1 string) string {
return fmt.Sprintf(`
resource "aws_organizations_organization" "test" {}

resource "aws_organizations_account" "test" {
name = %[1]q
email = %[2]q

tags = {
%[3]q = %[4]q
}
}
`, name, email, tagKey1, tagValue1)
}

func testAccAwsOrganizationsAccountConfigTags2(name, email, tagKey1, tagValue1, tagKey2, tagValue2 string) string {
return fmt.Sprintf(`
resource "aws_organizations_organization" "test" {}

resource "aws_organizations_account" "test" {
name = %[1]q
email = %[2]q

tags = {
%[3]q = %[4]q
%[5]q = %[6]q
}
}
`, name, email, tagKey1, tagValue1, tagKey2, tagValue2)
}
1 change: 1 addition & 0 deletions aws/resource_aws_organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func TestAccAWSOrganizations(t *testing.T) {
"Account": {
"basic": testAccAwsOrganizationsAccount_basic,
"ParentId": testAccAwsOrganizationsAccount_ParentId,
"Tags": testAccAwsOrganizationsAccount_Tags,
},
"OrganizationalUnit": {
"basic": testAccAwsOrganizationsOrganizationalUnit_basic,
Expand Down
77 changes: 77 additions & 0 deletions aws/tagsOrganizations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package aws

import (
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/organizations"
)

// diffTags takes our tags locally and the ones remotely and returns
// the set of tags that must be created, and the set of tags that must
// be destroyed.
func diffTagsOrganizations(oldTags, newTags []*organizations.Tag) ([]*organizations.Tag, []*string) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[aws.StringValue(t.Key)] = aws.StringValue(t.Value)
}

// Build the list of what to remove
var remove []*string
for _, t := range oldTags {
old, ok := create[aws.StringValue(t.Key)]
if !ok || old != aws.StringValue(t.Value) {
remove = append(remove, t.Key)
} else if ok {
// already present so remove from new
delete(create, aws.StringValue(t.Key))
}
}

return tagsFromMapOrganizations(create), remove
}

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapOrganizations(m map[string]interface{}) []*organizations.Tag {
var result []*organizations.Tag
for k, v := range m {
t := &organizations.Tag{
Key: aws.String(k),
Value: aws.String(v.(string)),
}
if !tagIgnoredOrganizations(t) {
result = append(result, t)
}
}

return result
}

// tagsToMap turns the list of tags into a map.
func tagsToMapOrganizations(ts []*organizations.Tag) map[string]string {
result := make(map[string]string)
for _, t := range ts {
if !tagIgnoredOrganizations(t) {
result[aws.StringValue(t.Key)] = aws.StringValue(t.Value)
}
}

return result
}

// compare a tag against a list of strings and checks if it should
// be ignored or not
func tagIgnoredOrganizations(t *organizations.Tag) bool {
filter := []string{"^aws:"}
for _, v := range filter {
log.Printf("[DEBUG] Matching %v with %v\n", v, aws.StringValue(t.Key))
r, _ := regexp.MatchString(v, aws.StringValue(t.Key))
if r {
log.Printf("[DEBUG] Found AWS specific tag %s (val: %s), ignoring.\n", aws.StringValue(t.Key), aws.StringValue(t.Value))
return true
}
}
return false
}
Loading