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

#7741: Pinpoint App - Added resource tag support #9460

Merged
merged 3 commits into from
Jul 31, 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
20 changes: 20 additions & 0 deletions aws/resource_aws_pinpoint_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ func resourceAwsPinpointApp() *schema.Resource {
},
},
},
"arn": {
Copy link
Contributor

Choose a reason for hiding this comment

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

This new attribute is missing documentation in website/docs/r/pinpoint_app.html.markdown, e.g. (under ## Attributes)

* `arn` - Amazon Resource Name (ARN) of the PinPoint Application

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added 👍

Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
Copy link
Contributor

Choose a reason for hiding this comment

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

This new argument is missing documentation in website/docs/r/pinpoint_app.html.markdown, e.g. (under ## Arguments)

* `tags` - (Optional) Key-value mapping of resource tags

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added 👍

},
}
}
Expand All @@ -136,6 +141,7 @@ func resourceAwsPinpointAppCreate(d *schema.ResourceData, meta interface{}) erro
pinpointconn := meta.(*AWSClient).pinpointconn

var name string

if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
Expand All @@ -152,12 +158,17 @@ func resourceAwsPinpointAppCreate(d *schema.ResourceData, meta interface{}) erro
},
}

if v, ok := d.GetOk("tags"); ok {
req.CreateApplicationRequest.Tags = tagsFromMapPinPointApp(v.(map[string]interface{}))
}

output, err := pinpointconn.CreateApp(req)
if err != nil {
return fmt.Errorf("error creating Pinpoint app: %s", err)
}

d.SetId(*output.ApplicationResponse.Id)
d.Set("arn", output.ApplicationResponse.Arn)

return resourceAwsPinpointAppUpdate(d, meta)
}
Expand Down Expand Up @@ -193,6 +204,10 @@ func resourceAwsPinpointAppUpdate(d *schema.ResourceData, meta interface{}) erro
return err
}

if err := setTagsPinPointApp(conn, d); err != nil {
return fmt.Errorf("error updating PinPoint Application (%s) tags: %s", d.Id(), err)
}

return resourceAwsPinpointAppRead(d, meta)
}

Expand Down Expand Up @@ -229,6 +244,7 @@ func resourceAwsPinpointAppRead(d *schema.ResourceData, meta interface{}) error

d.Set("name", app.ApplicationResponse.Name)
d.Set("application_id", app.ApplicationResponse.Id)
d.Set("arn", app.ApplicationResponse.Arn)

if err := d.Set("campaign_hook", flattenPinpointCampaignHook(settings.ApplicationSettingsResource.CampaignHook)); err != nil {
return fmt.Errorf("error setting campaign_hook: %s", err)
Expand All @@ -240,6 +256,10 @@ func resourceAwsPinpointAppRead(d *schema.ResourceData, meta interface{}) error
return fmt.Errorf("error setting quiet_time: %s", err)
}

if err := getTagsPinPointApp(conn, d); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}

return nil
}

Expand Down
78 changes: 78 additions & 0 deletions aws/resource_aws_pinpoint_app_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/pinpoint"

"github.com/aws/aws-sdk-go/aws"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
Expand Down Expand Up @@ -136,6 +137,54 @@ func TestAccAWSPinpointApp_QuietTime(t *testing.T) {
})
}

func TestAccAWSPinpointApp_Tags(t *testing.T) {
oldDefaultRegion := os.Getenv("AWS_DEFAULT_REGION")
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
defer os.Setenv("AWS_DEFAULT_REGION", oldDefaultRegion)

var application pinpoint.ApplicationResponse
resourceName := "aws_pinpoint_app.test_app"
shareName := fmt.Sprintf("tf-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsRamResourceShareDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSPinpointAppConfig_Tag1(shareName, "key1", "value1"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSPinpointAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAWSPinpointAppConfig_Tag2(shareName, "key1", "value1updated", "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSPinpointAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"),
resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"),
),
},
{
Config: testAccAWSPinpointAppConfig_Tag1(shareName, "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSPinpointAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"),
),
},
},
})
}

func testAccCheckAWSPinpointAppExists(n string, application *pinpoint.ApplicationResponse) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down Expand Up @@ -261,6 +310,35 @@ resource "aws_pinpoint_app" "test_app" {
}
`

func testAccAWSPinpointAppConfig_Tag1(shareName, tagKey1, tagValue1 string) string {
return fmt.Sprintf(`
provider "aws" {
region = "us-east-1"
}
resource "aws_pinpoint_app" "test_app" {
name = %q
tags = {
%q = %q
}
}
`, shareName, tagKey1, tagValue1)
}

func testAccAWSPinpointAppConfig_Tag2(shareName, tagKey1, tagValue1, tagKey2, tagValue2 string) string {
return fmt.Sprintf(`
provider "aws" {
region = "us-east-1"
}
resource "aws_pinpoint_app" "test_app" {
name = %q
tags = {
%q = %q
%q = %q
}
}
`, shareName, tagKey1, tagValue1, tagKey2, tagValue2)
}

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

Expand Down
133 changes: 133 additions & 0 deletions aws/tagsPinPointApp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package aws

import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/pinpoint"
"github.com/hashicorp/terraform/helper/schema"
"log"
"regexp"
)

// getTags is a helper to get the tags for a resource. It expects the
// tags field to be named "tags"
func getTagsPinPointApp(conn *pinpoint.Pinpoint, d *schema.ResourceData) error {
resp, err := conn.ListTagsForResource(&pinpoint.ListTagsForResourceInput{
ResourceArn: aws.String(d.Get("arn").(string)),
})
if err != nil {
return err
}

if err := d.Set("tags", tagsToMapPinPointApp(resp.TagsModel)); err != nil {
return err
}

return nil
}

// tagsToMap turns the list of tags into a map.
func tagsToMapPinPointApp(tm *pinpoint.TagsModel) map[string]string {
result := make(map[string]string)
for key, value := range tm.Tags {
if !tagIgnoredPinPointApp(key, *value) {
result[key] = aws.StringValue(value)
}
}

return result
}

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

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapPinPointApp(m map[string]interface{}) map[string]*string {
result := make(map[string]*string)
for k, v := range m {
if !tagIgnoredPinPointApp(k, v.(string)) {
result[k] = aws.String(v.(string))
}
}

return result
}

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTagsPinPointApp(conn *pinpoint.Pinpoint, d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTagsPinPointApp(tagsFromMapPinPointApp(o), tagsFromMapPinPointApp(n))

// Set tags
if len(remove) > 0 {
log.Printf("[DEBUG] Removing tags: %#v", remove)
k := make([]*string, 0, len(remove))
for i := range remove {
k = append(k, &i)
}

log.Printf("[DEBUG] Removing old tags: %#v", k)
log.Printf("[DEBUG] Removing for arn: %#v", aws.String(d.Get("arn").(string)))

_, err := conn.UntagResource(&pinpoint.UntagResourceInput{
ResourceArn: aws.String(d.Get("arn").(string)),
TagKeys: k,
})
if err != nil {
return err
}
}
if len(create) > 0 {
log.Printf("[DEBUG] Creating tags: %#v", create)
_, err := conn.TagResource(&pinpoint.TagResourceInput{
ResourceArn: aws.String(d.Get("arn").(string)),
TagsModel: &pinpoint.TagsModel{Tags: create},
})
if err != nil {
return err
}
}
}

return nil
}

// 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 diffTagsPinPointApp(oldTags, newTags map[string]*string) (map[string]*string, map[string]*string) {
// First, we're creating everything we have
create := make(map[string]interface{})
for k, v := range newTags {
create[k] = aws.StringValue(v)
}

// Build the list of what to remove
var remove = make(map[string]*string)
for k, v := range oldTags {
old, ok := create[k]
if !ok || old != aws.StringValue(v) {
// Delete it!
remove[k] = v
} else if ok {
delete(create, k)
}
}

return tagsFromMapPinPointApp(create), remove
}
Loading