providers/aws: Normalize S3 bucket policy

AWS always returns a compressed JSON body, without spaces or newlines, so we round-trip the JSON before storing in the state.
This commit is contained in:
Justin Campbell 2015-05-16 06:11:23 -04:00
parent 4b17554993
commit 89f0def721
2 changed files with 20 additions and 5 deletions

View File

@ -1,6 +1,7 @@
package aws
import (
"encoding/json"
"fmt"
"log"
@ -34,6 +35,7 @@ func resourceAwsS3Bucket() *schema.Resource {
"policy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
StateFunc: normalizeJson,
},
"website": &schema.Schema{
@ -161,7 +163,7 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error {
pol, err := s3conn.GetBucketPolicy(&s3.GetBucketPolicyInput{
Bucket: aws.String(d.Id()),
})
log.Printf("[DEBUG] S3 bucket: %s, read policy: %s", d.Id(), pol)
log.Printf("[DEBUG] S3 bucket: %s, read policy: %v", d.Id(), pol)
if err != nil {
if err := d.Set("policy", ""); err != nil {
return err
@ -171,7 +173,7 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error {
if err := d.Set("policy", ""); err != nil {
return err
}
} else if err := d.Set("policy", *v); err != nil {
} else if err := d.Set("policy", normalizeJson(*v)); err != nil {
return err
}
}
@ -387,6 +389,19 @@ func WebsiteEndpointUrl(bucket string, region string) string {
return fmt.Sprintf("%s.s3-website-%s.amazonaws.com", bucket, region)
}
func normalizeJson(jsonString interface{}) string {
if jsonString == nil {
return ""
}
j := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonString.(string)), &j)
if err != nil {
return fmt.Sprintf("Error parsing JSON: %s", err)
}
b, _ := json.Marshal(j)
return string(b[:])
}
func normalizeRegion(region string) string {
// Default to us-east-1 if the bucket doesn't have a region:
// http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html