github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/aws/resource_aws_s3_bucket_policy.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "time" 7 8 "github.com/aws/aws-sdk-go/aws" 9 "github.com/aws/aws-sdk-go/aws/awserr" 10 "github.com/aws/aws-sdk-go/service/s3" 11 "github.com/hashicorp/terraform/helper/resource" 12 "github.com/hashicorp/terraform/helper/schema" 13 ) 14 15 func resourceAwsS3BucketPolicy() *schema.Resource { 16 return &schema.Resource{ 17 Create: resourceAwsS3BucketPolicyPut, 18 Read: resourceAwsS3BucketPolicyRead, 19 Update: resourceAwsS3BucketPolicyPut, 20 Delete: resourceAwsS3BucketPolicyDelete, 21 22 Schema: map[string]*schema.Schema{ 23 "bucket": { 24 Type: schema.TypeString, 25 Required: true, 26 ForceNew: true, 27 }, 28 29 "policy": { 30 Type: schema.TypeString, 31 Required: true, 32 ValidateFunc: validateJsonString, 33 DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs, 34 }, 35 }, 36 } 37 } 38 39 func resourceAwsS3BucketPolicyPut(d *schema.ResourceData, meta interface{}) error { 40 s3conn := meta.(*AWSClient).s3conn 41 42 bucket := d.Get("bucket").(string) 43 policy := d.Get("policy").(string) 44 45 d.SetId(bucket) 46 47 log.Printf("[DEBUG] S3 bucket: %s, put policy: %s", bucket, policy) 48 49 params := &s3.PutBucketPolicyInput{ 50 Bucket: aws.String(bucket), 51 Policy: aws.String(policy), 52 } 53 54 err := resource.Retry(1*time.Minute, func() *resource.RetryError { 55 if _, err := s3conn.PutBucketPolicy(params); err != nil { 56 if awserr, ok := err.(awserr.Error); ok { 57 if awserr.Code() == "MalformedPolicy" { 58 return resource.RetryableError(awserr) 59 } 60 } 61 return resource.NonRetryableError(err) 62 } 63 return nil 64 }) 65 66 if err != nil { 67 return fmt.Errorf("Error putting S3 policy: %s", err) 68 } 69 70 return nil 71 } 72 73 func resourceAwsS3BucketPolicyRead(d *schema.ResourceData, meta interface{}) error { 74 s3conn := meta.(*AWSClient).s3conn 75 76 log.Printf("[DEBUG] S3 bucket policy, read for bucket: %s", d.Id()) 77 pol, err := s3conn.GetBucketPolicy(&s3.GetBucketPolicyInput{ 78 Bucket: aws.String(d.Id()), 79 }) 80 81 v := "" 82 if err == nil && pol.Policy != nil { 83 v = *pol.Policy 84 } 85 if err := d.Set("policy", v); err != nil { 86 return err 87 } 88 89 return nil 90 } 91 92 func resourceAwsS3BucketPolicyDelete(d *schema.ResourceData, meta interface{}) error { 93 s3conn := meta.(*AWSClient).s3conn 94 95 bucket := d.Get("bucket").(string) 96 97 log.Printf("[DEBUG] S3 bucket: %s, delete policy", bucket) 98 _, err := s3conn.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{ 99 Bucket: aws.String(bucket), 100 }) 101 102 if err != nil { 103 if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchBucket" { 104 return nil 105 } 106 return fmt.Errorf("Error deleting S3 policy: %s", err) 107 } 108 109 return nil 110 }