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

sns/topic: Fix diffs with policies #22213

Merged
merged 3 commits into from
Dec 15, 2021
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
7 changes: 7 additions & 0 deletions .changelog/22213.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
```release-note:bug
resource/aws_sns_topic: Fix erroneous diffs in `policy` when no changes made or policies are equivalent
```

```release-note:bug
resource/aws_sns_topic_policy: Fix erroneous diffs in `policy` when no changes made or policies are equivalent
```
36 changes: 31 additions & 5 deletions internal/service/sns/topic.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
awspolicy "github.com/hashicorp/awspolicyequivalence"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure"
Expand Down Expand Up @@ -287,7 +288,14 @@ func resourceTopicCreate(d *schema.ResourceData, meta interface{}) error {
}
if d.HasChange("policy") {
_, v := d.GetChange("policy")
if err := updateTopicAttribute(d.Id(), "Policy", v, conn); err != nil {

policy, err := structure.NormalizeJsonString(v.(string))

if err != nil {
return fmt.Errorf("policy (%s) is invalid JSON: %w", v.(string), err)
}

if err := updateTopicAttribute(d.Id(), "Policy", policy, conn); err != nil {
return err
}
}
Expand Down Expand Up @@ -419,12 +427,23 @@ func resourceTopicUpdate(d *schema.ResourceData, meta interface{}) error {
return err
}
}

if d.HasChange("policy") {
_, v := d.GetChange("policy")
if err := updateTopicAttribute(d.Id(), "Policy", v, conn); err != nil {
return err
o, n := d.GetChange("policy")

if equivalent, err := awspolicy.PoliciesAreEquivalent(o.(string), n.(string)); err != nil || !equivalent {
policy, err := structure.NormalizeJsonString(n.(string))

if err != nil {
return fmt.Errorf("policy contains an invalid JSON: %s", err)
}

if err := updateTopicAttribute(d.Id(), "Policy", policy, conn); err != nil {
return err
}
}
}

if d.HasChange("sqs_failure_feedback_role_arn") {
_, v := d.GetChange("sqs_failure_feedback_role_arn")
if err := updateTopicAttribute(d.Id(), "SQSFailureFeedbackRoleArn", v, conn); err != nil {
Expand Down Expand Up @@ -525,13 +544,20 @@ func resourceTopicRead(d *schema.ResourceData, meta interface{}) error {
d.Set("kms_master_key_id", attributeOutput.Attributes["KmsMasterKeyId"])
d.Set("lambda_failure_feedback_role_arn", attributeOutput.Attributes["LambdaFailureFeedbackRoleArn"])
d.Set("lambda_success_feedback_role_arn", attributeOutput.Attributes["LambdaSuccessFeedbackRoleArn"])
d.Set("policy", attributeOutput.Attributes["Policy"])
d.Set("sqs_failure_feedback_role_arn", attributeOutput.Attributes["SQSFailureFeedbackRoleArn"])
d.Set("sqs_success_feedback_role_arn", attributeOutput.Attributes["SQSSuccessFeedbackRoleArn"])
d.Set("firehose_success_feedback_role_arn", attributeOutput.Attributes["FirehoseSuccessFeedbackRoleArn"])
d.Set("firehose_failure_feedback_role_arn", attributeOutput.Attributes["FirehoseFailureFeedbackRoleArn"])
d.Set("owner", attributeOutput.Attributes["Owner"])

policyToSet, policyErr := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(attributeOutput.Attributes["Policy"]))

if policyErr != nil {
return err
}

d.Set("policy", policyToSet)

// set the boolean values
if v, ok := attributeOutput.Attributes["FifoTopic"]; ok && aws.StringValue(v) == "true" {
fifoTopic = true
Expand Down
25 changes: 22 additions & 3 deletions internal/service/sns/topic_policy.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/sns"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
Expand Down Expand Up @@ -36,6 +37,10 @@ func ResourceTopicPolicy() *schema.Resource {
Required: true,
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: verify.SuppressEquivalentPolicyDiffs,
StateFunc: func(v interface{}) string {
json, _ := structure.NormalizeJsonString(v)
return json
},
},
"owner": {
Type: schema.TypeString,
Expand All @@ -47,10 +52,17 @@ func ResourceTopicPolicy() *schema.Resource {

func resourceTopicPolicyUpsert(d *schema.ResourceData, meta interface{}) error {
arn := d.Get("arn").(string)

policy, err := structure.NormalizeJsonString(d.Get("policy").(string))

if err != nil {
return fmt.Errorf("policy (%s) is invalid JSON: %w", d.Get("policy").(string), err)
}

req := sns.SetTopicAttributesInput{
TopicArn: aws.String(arn),
AttributeName: aws.String("Policy"),
AttributeValue: aws.String(d.Get("policy").(string)),
AttributeValue: aws.String(policy),
}

d.SetId(arn)
Expand All @@ -59,7 +71,7 @@ func resourceTopicPolicyUpsert(d *schema.ResourceData, meta interface{}) error {
// error, where say an IAM resource is successfully created but not
// actually available. See https://github.com/hashicorp/terraform/issues/3660
conn := meta.(*conns.AWSClient).SNSConn
_, err := verify.RetryOnAWSCode("InvalidParameter", func() (interface{}, error) {
_, err = verify.RetryOnAWSCode("InvalidParameter", func() (interface{}, error) {
return conn.SetTopicAttributes(&req)
})
if err != nil {
Expand Down Expand Up @@ -99,7 +111,14 @@ func resourceTopicPolicyRead(d *schema.ResourceData, meta interface{}) error {
return nil
}

d.Set("policy", policy)
policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(policy))

if err != nil {
return err
}

d.Set("policy", policyToSet)

d.Set("arn", attrmap["TopicArn"])
d.Set("owner", attrmap["Owner"])

Expand Down
91 changes: 91 additions & 0 deletions internal/service/sns/topic_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,35 @@ func TestAccSNSTopicPolicy_disappears(t *testing.T) {
})
}

func TestAccSNSTopicPolicy_ignoreEquivalent(t *testing.T) {
attributes := make(map[string]string)
resourceName := "aws_sns_topic_policy.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, sns.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckTopicPolicyDestroy,
Steps: []resource.TestStep{
{
Config: testAccTopicPolicyEquivalentConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckTopicExists("aws_sns_topic.test", attributes),
resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_sns_topic.test", "arn"),
resource.TestMatchResourceAttr(resourceName, "policy",
regexp.MustCompile(fmt.Sprintf("\"Sid\":\"%[1]s\"", rName))),
acctest.CheckResourceAttrAccountID(resourceName, "owner"),
),
},
{
Config: testAccTopicPolicyEquivalent2Config(rName),
PlanOnly: true,
},
},
})
}

func testAccCheckTopicPolicyDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).SNSConn

Expand Down Expand Up @@ -223,3 +252,65 @@ POLICY
}
`, rName)
}

func testAccTopicPolicyEquivalentConfig(rName string) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test" {
name = %[1]q
}

resource "aws_sns_topic_policy" "test" {
arn = aws_sns_topic.test.arn
policy = jsonencode({
Version = "2012-10-17"
Id = "default"
Statement = [{
Sid = %[1]q
Effect = "Allow"
Principal = {
AWS = "*"
}
Action = [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
]
Resource = aws_sns_topic.test.arn
}]
})
}
`, rName)
}

func testAccTopicPolicyEquivalent2Config(rName string) string {
return fmt.Sprintf(`
resource "aws_sns_topic" "test" {
name = %[1]q
}

resource "aws_sns_topic_policy" "test" {
arn = aws_sns_topic.test.arn
policy = jsonencode({
Version = "2012-10-17"
Id = "default"
Statement = [{
Sid = %[1]q
Effect = "Allow"
Principal = {
AWS = ["*"]
}
Action = [
"SNS:SetTopicAttributes",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:AddPermission",
"SNS:GetTopicAttributes",
]
Resource = [aws_sns_topic.test.arn]
}]
})
}
`, rName)
}