provider/aws: Import S3 bucket policy as a separate resource

This commit is contained in:
Radek Simko 2016-09-19 08:28:45 +01:00
parent 59a7a5ca27
commit f17fdc76fa
No known key found for this signature in database
GPG Key ID: 6823F3DCCE01BB19
3 changed files with 85 additions and 1 deletions

View File

@ -0,0 +1,39 @@
package aws
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsS3BucketImportState(
d *schema.ResourceData,
meta interface{}) ([]*schema.ResourceData, error) {
results := make([]*schema.ResourceData, 1, 1)
results[0] = d
conn := meta.(*AWSClient).s3conn
pol, err := conn.GetBucketPolicy(&s3.GetBucketPolicyInput{
Bucket: aws.String(d.Id()),
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchBucketPolicy" {
// Bucket without policy
return results, nil
}
return nil, errwrap.Wrapf("Error importing AWS S3 bucket policy: {{err}}", err)
}
policy := resourceAwsS3BucketPolicy()
pData := policy.Data(nil)
pData.SetId(d.Id())
pData.SetType("aws_s3_bucket_policy")
pData.Set("bucket", d.Id())
pData.Set("policy", pol)
results = append(results, pData)
return results, nil
}

View File

@ -1,10 +1,12 @@
package aws
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSS3Bucket_importBasic(t *testing.T) {
@ -30,3 +32,46 @@ func TestAccAWSS3Bucket_importBasic(t *testing.T) {
},
})
}
func TestAccAWSS3Bucket_importWithPolicy(t *testing.T) {
rInt := acctest.RandInt()
checkFn := func(s []*terraform.InstanceState) error {
// Expect 2: bucket + policy
if len(s) != 2 {
return fmt.Errorf("expected 2 states: %#v", s)
}
bucketState, policyState := s[0], s[1]
expectedBucketId := fmt.Sprintf("tf-test-bucket-%d", rInt)
if bucketState.ID != expectedBucketId {
return fmt.Errorf("expected bucket of ID %s, %s received",
expectedBucketId, bucketState.ID)
}
if policyState.ID != expectedBucketId {
return fmt.Errorf("expected policy of ID %s, %s received",
expectedBucketId, bucketState.ID)
}
return nil
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSS3BucketDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSS3BucketConfigWithPolicy(rInt),
},
resource.TestStep{
ResourceName: "aws_s3_bucket.bucket",
ImportState: true,
ImportStateCheck: checkFn,
},
},
})
}

View File

@ -23,7 +23,7 @@ func resourceAwsS3Bucket() *schema.Resource {
Update: resourceAwsS3BucketUpdate,
Delete: resourceAwsS3BucketDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
State: resourceAwsS3BucketImportState,
},
Schema: map[string]*schema.Schema{