From 6c27f175b5832eb57a5d021a38fd605771090ce3 Mon Sep 17 00:00:00 2001 From: Krzysztof Wilczynski Date: Wed, 14 Sep 2016 17:18:16 +0100 Subject: [PATCH] Add JSON validation to the aws_sns_topic resource. This commit adds support for new helper function which is used to normalise and validate JSON string. This commit also removes unnecessary code from the StateFunc function, and reduces it so that it only uses the normalizeJsonString helper. Signed-off-by: Krzysztof Wilczynski --- .../providers/aws/resource_aws_sns_topic.go | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/builtin/providers/aws/resource_aws_sns_topic.go b/builtin/providers/aws/resource_aws_sns_topic.go index c994b98add..f3320866a3 100644 --- a/builtin/providers/aws/resource_aws_sns_topic.go +++ b/builtin/providers/aws/resource_aws_sns_topic.go @@ -1,19 +1,17 @@ package aws import ( - "bytes" - "encoding/json" "fmt" "log" "strings" "time" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/sns" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" ) // Mutable attributes @@ -49,21 +47,11 @@ func resourceAwsSnsTopic() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, + ValidateFunc: validateJsonString, DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs, StateFunc: func(v interface{}) string { - s, ok := v.(string) - if !ok || s == "" { - return "" - } - jsonb := []byte(s) - buffer := new(bytes.Buffer) - if err := json.Compact(buffer, jsonb); err != nil { - log.Printf("[WARN] Error compacting JSON for Policy in SNS Topic") - return "" - } - value := normalizeJson(buffer.String()) - log.Printf("[DEBUG] topic policy before save: %s", value) - return value + json, _ := normalizeJsonString(v) + return json }, }, "delivery_policy": &schema.Schema{ @@ -191,7 +179,10 @@ func resourceAwsSnsTopicRead(d *schema.ResourceData, meta interface{}) error { if resource.Schema[iKey] != nil { var value string if iKey == "policy" { - value = normalizeJson(*attrmap[oKey]) + value, err = normalizeJsonString(*attrmap[oKey]) + if err != nil { + return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err) + } } else { value = *attrmap[oKey] }