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 support for tags for sns topic #8468

Merged
merged 3 commits into from
May 14, 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
22 changes: 20 additions & 2 deletions aws/resource_aws_sns_topic.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,14 @@ func resourceAwsSnsTopic() *schema.Resource {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}

func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn

tags := tagsFromMapSNS(d.Get("tags").(map[string]interface{}))
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
Expand All @@ -164,6 +165,7 @@ func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error {

req := &sns.CreateTopicInput{
Name: aws.String(name),
Tags: tags,
}

output, err := snsconn.CreateTopic(req)
Expand All @@ -172,7 +174,6 @@ func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error {
}

d.SetId(*output.TopicArn)

return resourceAwsSnsTopicUpdate(d, meta)
}

Expand All @@ -188,6 +189,11 @@ func resourceAwsSnsTopicUpdate(d *schema.ResourceData, meta interface{}) error {
}
}
}
if !d.IsNewResource() {
if err := setTagsSNS(conn, d); err != nil {
return fmt.Errorf("error updating SNS Topic tags for %s: %s", d.Id(), err)
}
}

return resourceAwsSnsTopicRead(d, meta)
}
Expand Down Expand Up @@ -231,6 +237,18 @@ func resourceAwsSnsTopicRead(d *schema.ResourceData, meta interface{}) error {
}
}

// List tags

tagList, err := snsconn.ListTagsForResource(&sns.ListTagsForResourceInput{
ResourceArn: aws.String(d.Id()),
})
if err != nil {
return fmt.Errorf("error listing SNS Topic tags for %s: %s", d.Id(), err)
}
if err := d.Set("tags", tagsToMapSNS(tagList.Tags)); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}

return nil
}

Expand Down
63 changes: 62 additions & 1 deletion aws/resource_aws_sns_topic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/jen20/awspolicyequivalence"
awspolicy "github.com/jen20/awspolicyequivalence"
)

func TestAccAWSSNSTopic_importBasic(t *testing.T) {
Expand Down Expand Up @@ -256,6 +256,46 @@ func TestAccAWSSNSTopic_encryption(t *testing.T) {
})
}

func TestAccAWSSNSTopic_tags(t *testing.T) {
attributes := make(map[string]string)

rName := acctest.RandString(10)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_sns_topic.test_topic",
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSNSTopicDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSSNSTopicConfigTags1(rName, "key1", "value1"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic", attributes),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.%", "1"),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.key1", "value1"),
),
},
{
Config: testAccAWSSNSTopicConfigTags2(rName, "key1", "value1updated", "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic", attributes),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.%", "2"),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.key1", "value1updated"),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.key2", "value2"),
),
},
{
Config: testAccAWSSNSTopicConfigTags1(rName, "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic", attributes),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.%", "1"),
resource.TestCheckResourceAttr("aws_sns_topic.test_topic", "tags.key2", "value2"),
),
},
},
})
}

func testAccCheckAWSNSTopicHasPolicy(n string, expectedPolicyText string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down Expand Up @@ -631,3 +671,24 @@ resource "aws_sns_topic" "test_topic" {
}
`, r)
}

func testAccAWSSNSTopicConfigTags1(r, tag1Key, tag1Value string) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test_topic" {
name = "terraform-test-topic-%s"
tags = {
%q = %q
}
}`, r, tag1Key, tag1Value)
}

func testAccAWSSNSTopicConfigTags2(r, tag1Key, tag1Value, tag2Key, tag2Value string) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test_topic" {
name = "terraform-test-topic-%s"
tags = {
%q = %q
%q = %q
}
}`, r, tag1Key, tag1Value, tag2Key, tag2Value)
}
118 changes: 118 additions & 0 deletions aws/tagsSNS.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package aws

import (
"log"
"regexp"

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

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags" and the ARN field to be named "arn".
func setTagsSNS(conn *sns.SNS, 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 := diffTagsSNS(tagsFromMapSNS(o), tagsFromMapSNS(n))

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

_, err := conn.UntagResource(&sns.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(&sns.TagResourceInput{
ResourceArn: aws.String(d.Get("arn").(string)),
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 diffTagsSNS(oldTags, newTags []*sns.Tag) ([]*sns.Tag, []*sns.Tag) {
// 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 []*sns.Tag
for _, t := range oldTags {
old, ok := create[aws.StringValue(t.Key)]
if !ok || old != aws.StringValue(t.Value) {
remove = append(remove, t)
} else if ok {
// already present so remove from new
delete(create, aws.StringValue(t.Key))
}
}

return tagsFromMapSNS(create), remove
}

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapSNS(m map[string]interface{}) []*sns.Tag {
result := make([]*sns.Tag, 0, len(m))
for k, v := range m {
t := &sns.Tag{
Key: aws.String(k),
Value: aws.String(v.(string)),
}
if !tagIgnoredSNS(t) {
result = append(result, t)
}
}

return result
}

// tagsToMap turns the list of tags into a map.
func tagsToMapSNS(ts []*sns.Tag) map[string]string {
result := make(map[string]string)
for _, t := range ts {
if !tagIgnoredSNS(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 tagIgnoredSNS(t *sns.Tag) bool {
filter := []string{"^aws:"}
for _, v := range filter {
log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key)
r, _ := regexp.MatchString(v, *t.Key)
if r {
log.Printf("[DEBUG] Found AWS specific tag %s (val: %s), ignoring.\n", *t.Key, *t.Value)
return true
}
}
return false
}
110 changes: 110 additions & 0 deletions aws/tagsSNS_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package aws

import (
"reflect"
"testing"

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

func TestDiffSNSTags(t *testing.T) {
cases := []struct {
Old, New map[string]interface{}
Create, Remove map[string]string
}{
// Add
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"foo": "bar",
"bar": "baz",
},
Create: map[string]string{
"bar": "baz",
},
Remove: map[string]string{},
},

// Modify
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"foo": "baz",
},
Create: map[string]string{
"foo": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},

// Overlap
{
Old: map[string]interface{}{
"foo": "bar",
"hello": "world",
},
New: map[string]interface{}{
"foo": "baz",
"hello": "world",
},
Create: map[string]string{
"foo": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},

// Remove
{
Old: map[string]interface{}{
"foo": "bar",
"bar": "baz",
},
New: map[string]interface{}{
"foo": "bar",
},
Create: map[string]string{},
Remove: map[string]string{
"bar": "baz",
},
},
}

for i, tc := range cases {
c, r := diffTagsSNS(tagsFromMapSNS(tc.Old), tagsFromMapSNS(tc.New))
cm := tagsToMapSNS(c)
rm := tagsToMapSNS(r)
if !reflect.DeepEqual(cm, tc.Create) {
t.Fatalf("%d: bad create: %#v", i, cm)
}
if !reflect.DeepEqual(rm, tc.Remove) {
t.Fatalf("%d: bad remove: %#v", i, rm)
}
}
}

func TestIgnoringTagsSNS(t *testing.T) {
ignoredTags := []*sns.Tag{
{
Key: aws.String("aws:cloudformation:logical-id"),
Value: aws.String("foo"),
},
{
Key: aws.String("aws:foo:bar"),
Value: aws.String("baz"),
},
}
for _, tag := range ignoredTags {
if !tagIgnoredSNS(tag) {
t.Fatalf("Tag %v with value %v not ignored, but should be!", *tag.Key, *tag.Value)
}
}
}
1 change: 1 addition & 0 deletions website/docs/r/sns_topic.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ The following arguments are supported:
* `sqs_success_feedback_role_arn` - (Optional) The IAM role permitted to receive success feedback for this topic
* `sqs_success_feedback_sample_rate` - (Optional) Percentage of success to sample
* `sqs_failure_feedback_role_arn` - (Optional) IAM role for failure feedback
* `tags` - (Optional) Key-value mapping of resource tags

## Attributes Reference

Expand Down