Skip to content

Commit

Permalink
Merge pull request #11770 from Ricool06/f-sns-subscription-redrive-po…
Browse files Browse the repository at this point in the history
…licy

resource/aws_sns_topic_subscription: Add redrive_policy argument fixes #10931
  • Loading branch information
anGie44 committed Feb 6, 2021
2 parents a080b4e + 4ac0362 commit 3f0a76b
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .changelog/11770.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:enhancement
resource/aws_sns_topic_subscription: Add `redrive_policy` argument
```
29 changes: 29 additions & 0 deletions aws/resource_aws_sns_topic_subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ func resourceAwsSnsTopicSubscription() *schema.Resource {
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: suppressEquivalentSnsTopicSubscriptionDeliveryPolicy,
},
"redrive_policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: suppressEquivalentJsonDiffs,
},
"raw_message_delivery": {
Type: schema.TypeBool,
Optional: true,
Expand Down Expand Up @@ -147,6 +153,12 @@ func resourceAwsSnsTopicSubscriptionUpdate(d *schema.ResourceData, meta interfac
}
}

if d.HasChange("redrive_policy") {
if err := snsSubscriptionAttributeUpdate(snsconn, d.Id(), "RedrivePolicy", d.Get("redrive_policy").(string)); err != nil {
return err
}
}

return resourceAwsSnsTopicSubscriptionRead(d, meta)
}

Expand Down Expand Up @@ -184,6 +196,7 @@ func resourceAwsSnsTopicSubscriptionRead(d *schema.ResourceData, meta interface{
d.Set("raw_message_delivery", true)
}

d.Set("redrive_policy", attributeOutput.Attributes["RedrivePolicy"])
d.Set("topic_arn", attributeOutput.Attributes["TopicArn"])

return nil
Expand All @@ -205,6 +218,7 @@ func getResourceAttributes(d *schema.ResourceData) (output map[string]*string) {
delivery_policy := d.Get("delivery_policy").(string)
filter_policy := d.Get("filter_policy").(string)
raw_message_delivery := d.Get("raw_message_delivery").(bool)
redrive_policy := d.Get("redrive_policy").(string)

// Collect attributes if available
attributes := map[string]*string{}
Expand All @@ -221,6 +235,10 @@ func getResourceAttributes(d *schema.ResourceData) (output map[string]*string) {
attributes["RawMessageDelivery"] = aws.String(fmt.Sprintf("%t", raw_message_delivery))
}

if redrive_policy != "" {
attributes["RedrivePolicy"] = aws.String(redrive_policy)
}

return attributes
}

Expand Down Expand Up @@ -373,6 +391,13 @@ func snsSubscriptionAttributeUpdate(snsconn *sns.SNS, subscriptionArn, attribute
AttributeName: aws.String(attributeName),
AttributeValue: aws.String(attributeValue),
}

// The AWS API requires a non-empty string value or nil for the RedrivePolicy attribute,
// else throws an InvalidParameter error
if attributeName == "RedrivePolicy" && attributeValue == "" {
req.AttributeValue = nil
}

_, err := snsconn.SetSubscriptionAttributes(req)

if err != nil {
Expand Down Expand Up @@ -444,6 +469,10 @@ func (s snsTopicSubscriptionDeliveryPolicyThrottlePolicy) GoString() string {
return s.String()
}

type snsTopicSubscriptionRedrivePolicy struct {
DeadLetterTargetArn string `json:"deadLetterTargetArn,omitempty"`
}

func suppressEquivalentSnsTopicSubscriptionDeliveryPolicy(k, old, new string, d *schema.ResourceData) bool {
var deliveryPolicy snsTopicSubscriptionDeliveryPolicy

Expand Down
112 changes: 112 additions & 0 deletions aws/resource_aws_sns_topic_subscription_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
Expand Down Expand Up @@ -199,6 +200,63 @@ func TestAccAWSSNSTopicSubscription_deliveryPolicy(t *testing.T) {
})
}

func TestAccAWSSNSTopicSubscription_redrivePolicy(t *testing.T) {
attributes := make(map[string]string)
resourceName := "aws_sns_topic_subscription.test_subscription"
ri := acctest.RandInt()
dlqName := fmt.Sprintf("tf-acc-test-queue-dlq-%d", ri)
updatedDlqName := fmt.Sprintf("tf-acc-test-queue-dlq-update-%d", ri)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSNSTopicSubscriptionDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSSNSTopicSubscriptionConfig_redrivePolicy(ri, dlqName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicSubscriptionExists(resourceName, attributes),
testAccCheckAWSSNSTopicSubscriptionRedrivePolicyAttribute(attributes, dlqName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{
"confirmation_timeout_in_minutes",
"endpoint_auto_confirms",
},
},
// Test attribute update
{
Config: testAccAWSSNSTopicSubscriptionConfig_redrivePolicy(ri, updatedDlqName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicSubscriptionExists(resourceName, attributes),
testAccCheckAWSSNSTopicSubscriptionRedrivePolicyAttribute(attributes, updatedDlqName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{
"confirmation_timeout_in_minutes",
"endpoint_auto_confirms",
},
},
// Test attribute removal
{
Config: testAccAWSSNSTopicSubscriptionConfig(ri),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSNSTopicSubscriptionExists(resourceName, attributes),
resource.TestCheckResourceAttr(resourceName, "redrive_policy", ""),
),
},
},
})
}

func TestAccAWSSNSTopicSubscription_rawMessageDelivery(t *testing.T) {
attributes := make(map[string]string)
resourceName := "aws_sns_topic_subscription.test_subscription"
Expand Down Expand Up @@ -379,6 +437,37 @@ func testAccCheckAWSSNSTopicSubscriptionDeliveryPolicyAttribute(attributes map[s
}
}

func testAccCheckAWSSNSTopicSubscriptionRedrivePolicyAttribute(attributes map[string]string, expectedRedrivePolicyResource string) resource.TestCheckFunc {
return func(s *terraform.State) error {
apiRedrivePolicyJSONString, ok := attributes["RedrivePolicy"]

if !ok {
return fmt.Errorf("RedrivePolicy attribute not found in attributes: %s", attributes)
}

var apiRedrivePolicy snsTopicSubscriptionRedrivePolicy
if err := json.Unmarshal([]byte(apiRedrivePolicyJSONString), &apiRedrivePolicy); err != nil {
return fmt.Errorf("unable to unmarshal SNS Topic Subscription redrive policy JSON (%s): %s", apiRedrivePolicyJSONString, err)
}

expectedRedrivePolicy := snsTopicSubscriptionRedrivePolicy{
DeadLetterTargetArn: arn.ARN{
AccountID: testAccGetAccountID(),
Partition: testAccGetPartition(),
Region: testAccGetRegion(),
Resource: expectedRedrivePolicyResource,
Service: "sqs",
}.String(),
}

if reflect.DeepEqual(apiRedrivePolicy, expectedRedrivePolicy) {
return nil
}

return fmt.Errorf("SNS Topic Subscription redrive policy did not match:\n\nReceived\n\n%s\n\nExpected\n\n%s\n\n", apiRedrivePolicy, expectedRedrivePolicy)
}
}

func TestObfuscateEndpointPassword(t *testing.T) {
checks := map[string]string{
"https://example.com/myroute": "https://example.com/myroute",
Expand Down Expand Up @@ -450,6 +539,29 @@ resource "aws_sns_topic_subscription" "test_subscription" {
`, i, i, policy)
}

func testAccAWSSNSTopicSubscriptionConfig_redrivePolicy(i int, dlqName string) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test_topic" {
name = "terraform-test-topic-%[1]d"
}
resource "aws_sqs_queue" "test_queue" {
name = "terraform-subscription-test-queue-%[1]d"
}
resource "aws_sqs_queue" "test_queue_dlq" {
name = "%s"
}
resource "aws_sns_topic_subscription" "test_subscription" {
redrive_policy = jsonencode({ deadLetterTargetArn : aws_sqs_queue.test_queue_dlq.arn })
endpoint = aws_sqs_queue.test_queue.arn
protocol = "sqs"
topic_arn = aws_sns_topic.test_topic.arn
}
`, i, dlqName)
}

func testAccAWSSNSTopicSubscriptionConfig_rawMessageDelivery(i int, rawMessageDelivery bool) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test_topic" {
Expand Down
1 change: 1 addition & 0 deletions website/docs/r/sns_topic_subscription.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ The following arguments are supported:
* `raw_message_delivery` - (Optional) Boolean indicating whether or not to enable raw message delivery (the original message is directly passed, not wrapped in JSON with the original message in the message property) (default is false).
* `filter_policy` - (Optional) JSON String with the filter policy that will be used in the subscription to filter messages seen by the target resource. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/message-filtering.html) for more details.
* `delivery_policy` - (Optional) JSON String with the delivery policy (retries, backoff, etc.) that will be used in the subscription - this only applies to HTTP/S subscriptions. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) for more details.
* `redrive_policy` - (Optional) JSON String with the redrive policy that will be used in the subscription. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/sns-dead-letter-queues.html#how-messages-moved-into-dead-letter-queue) for more details.

### Protocols supported

Expand Down

0 comments on commit 3f0a76b

Please sign in to comment.