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 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
25 changes: 25 additions & 0 deletions aws/resource_aws_pinpoint_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ 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,
Optional: true,
Copy link
Contributor

Choose a reason for hiding this comment

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

The ARN of the PinPoint Application cannot be set by the operator, so Optional: true should be removed. 👍

Suggested change
Optional: true,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed.

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 +142,8 @@ func resourceAwsPinpointAppCreate(d *schema.ResourceData, meta interface{}) erro
pinpointconn := meta.(*AWSClient).pinpointconn

var name string
var tags = make(map[string]*string)

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

log.Printf("[DEBUG] Pinpoint create app: %s", name)

if v, ok := d.GetOk("tags"); ok {
tags = tagsFromMapPinPointApp(v.(map[string]interface{}))
Copy link
Contributor

Choose a reason for hiding this comment

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

Instead of creating a new variable to store the tags, this logic can be moved below the CreateAppInput declaration and call req.CreateApplicationRequest.Tags = directly.

	req := &pinpoint.CreateAppInput{
		CreateApplicationRequest: &pinpoint.CreateApplicationRequest{
			Name: aws.String(name),
		},
	}

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Make sense, Implemented 👍

}

req := &pinpoint.CreateAppInput{
CreateApplicationRequest: &pinpoint.CreateApplicationRequest{
Name: aws.String(name),
Tags: tags,
},
}

Expand All @@ -158,6 +171,7 @@ func resourceAwsPinpointAppCreate(d *schema.ResourceData, meta interface{}) erro
}

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

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

if err := setTagsPinPointApp(conn, d); err != nil {
return fmt.Errorf(
"Error Updating PinPoint App tags: \"%s\"\n%s",
Copy link
Contributor

Choose a reason for hiding this comment

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

We prefer to not introduce extra newlines into our error messaging:

		return fmt.Errorf("error updating PinPoint Application (%s) tags: %s", d.Id(), err)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Make sense, Implemented 👍

d.Get("name").(string), err)
}

return resourceAwsPinpointAppRead(d, meta)
}

Expand Down Expand Up @@ -229,6 +249,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 +261,10 @@ func resourceAwsPinpointAppRead(d *schema.ResourceData, meta interface{}) error
return fmt.Errorf("error setting quiet_time: %s", err)
}

if err := getTagsPinPointApp(conn, d, *app.ApplicationResponse.Name); 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 @@ -2,6 +2,7 @@ package aws

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: Go imports should be formatted as stdlib imports, new line, third party imports with each section alphabetically sorted. Tooling like goimports can help do this automatically in editors. 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Didn't know that, Move to correct position based on other files 👍

"os"
"testing"

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, sn string) error {
Copy link
Contributor

Choose a reason for hiding this comment

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

The sn parameter to this function appears to be unused and should be removed.

Suggested change
func getTagsPinPointApp(conn *pinpoint.Pinpoint, d *schema.ResourceData, sn string) error {
func getTagsPinPointApp(conn *pinpoint.Pinpoint, d *schema.ResourceData) error {

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nice catch, Removed and updated function call.

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