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"
@ -32,8 +33,9 @@ func resourceAwsS3Bucket() *schema.Resource {
},
"policy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
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

View File

@ -271,7 +271,7 @@ func testAccCheckAWSS3BucketWebsite(n string, indexDoc string, errorDoc string,
// within AWS
var randInt = rand.New(rand.NewSource(time.Now().UnixNano())).Int()
var testAccWebsiteEndpoint = fmt.Sprintf("tf-test-bucket-%d.s3-website-us-west-2.amazonaws.com", randInt)
var testAccAWSS3BucketPolicy = fmt.Sprintf(`{"Version":"2008-10-17","Statement":[{"Sid":"","Effect":"Allow","Principal":{"AWS":"*"},"Action":"s3:GetObject","Resource":"arn:aws:s3:::tf-test-bucket-%d/*"}]}`, randInt)
var testAccAWSS3BucketPolicy = fmt.Sprintf(`{ "Version": "2008-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::tf-test-bucket-%d/*" } ] }`, randInt)
var testAccAWSS3BucketConfig = fmt.Sprintf(`
resource "aws_s3_bucket" "bucket" {