Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provider/google: Add CORS support for google_storage_bucket. #14695

Merged
merged 5 commits into from
May 31, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions builtin/providers/google/resource_storage_bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,40 @@ func resourceStorageBucket() *schema.Resource {
},
},
},

"cors": &schema.Schema{
Type: schema.TypeSet,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason why this is a set but its contents are lists? (not a criticism, just curious)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No reason really - List semantics weren't important to it, and the first similar block I looked at was a Set. Changed to List for consistency with the rest of the file; it also ends up simplifying a type assertion that way.

Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"origin": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"method": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"response_header": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"max_age_seconds": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
},
},
},
},
},
}
}
Expand Down Expand Up @@ -132,6 +166,10 @@ func resourceStorageBucketCreate(d *schema.ResourceData, meta interface{}) error
}
}

if v, ok := d.GetOk("cors"); ok {
sb.Cors = expandCors(v.(*schema.Set).List())
}

var res *storage.Bucket

err = resource.Retry(1*time.Minute, func() *resource.RetryError {
Expand Down Expand Up @@ -197,6 +235,10 @@ func resourceStorageBucketUpdate(d *schema.ResourceData, meta interface{}) error
}
}

if v, ok := d.GetOk("cors"); ok {
sb.Cors = expandCors(v.(*schema.Set).List())
}

res, err := config.clientStorage.Buckets.Patch(d.Get("name").(string), sb).Do()

if err != nil {
Expand Down Expand Up @@ -230,6 +272,7 @@ func resourceStorageBucketRead(d *schema.ResourceData, meta interface{}) error {
d.Set("url", fmt.Sprintf("gs://%s", bucket))
d.Set("storage_class", res.StorageClass)
d.Set("location", res.Location)
d.Set("cors", flattenCors(res.Cors))
d.SetId(res.Id)
return nil
}
Expand Down Expand Up @@ -295,3 +338,41 @@ func resourceStorageBucketStateImporter(d *schema.ResourceData, meta interface{}
d.Set("name", d.Id())
return []*schema.ResourceData{d}, nil
}

func expandCors(configured []interface{}) []*storage.BucketCors {
corsRules := make([]*storage.BucketCors, 0, len(configured))
for _, raw := range configured {
data := raw.(map[string]interface{})
corsRule := storage.BucketCors{}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style nit: totally just my opinion but I think filling out structs/maps inline looks a bit better:

		corsRule := storage.BucketCors{
			Origin:         convertSchemaArrayToStringArray(data["origin"].([]interface{})),
			Method:         convertSchemaArrayToStringArray(data["method"].([]interface{})),
			ResponseHeader: convertSchemaArrayToStringArray(data["response_header"].([]interface{})),
			MaxAgeSeconds:  int64(data["max_age_seconds"].(int)),
		}

and below:

		data := map[string]interface{}{
			"origin":          corsRule.Origin,
			"method":          corsRule.Method,
			"response_header": corsRule.ResponseHeader,
			"max_age_seconds": corsRule.MaxAgeSeconds,
		}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


corsRule.Origin = convertSchemaArrayToStringArray(data["origin"].([]interface{}))
corsRule.Method = convertSchemaArrayToStringArray(data["method"].([]interface{}))
corsRule.ResponseHeader = convertSchemaArrayToStringArray(data["response_header"].([]interface{}))

corsRule.MaxAgeSeconds = int64(data["max_age_seconds"].(int))
corsRules = append(corsRules, &corsRule)
}
return corsRules
}

func convertSchemaArrayToStringArray(input []interface{}) []string {
output := make([]string, 0, len(input))
for _, val := range input {
output = append(output, val.(string))
}

return output
}

func flattenCors(corsRules []*storage.BucketCors) []map[string]interface{} {
corsRulesSchema := make([]map[string]interface{}, 0, len(corsRules))
for _, corsRule := range corsRules {
data := make(map[string]interface{})
data["origin"] = corsRule.Origin
data["method"] = corsRule.Method
data["response_header"] = corsRule.ResponseHeader
data["max_age_seconds"] = corsRule.MaxAgeSeconds
corsRulesSchema = append(corsRulesSchema, data)
}
return corsRulesSchema
}
33 changes: 33 additions & 0 deletions builtin/providers/google/resource_storage_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,25 @@ func TestAccStorageForceDestroy(t *testing.T) {
})
}

func TestAccStorage_cors(t *testing.T) {
bucketName := fmt.Sprintf("tf-test-acl-bucket-%d", acctest.RandInt())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGoogleStorageDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testGoogleStorageBucketsCors(bucketName),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudStorageBucketExists(
"google_storage_bucket.bucket", bucketName),
),
},
},
})
}

func testAccCheckCloudStorageBucketExists(n string, bucketName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down Expand Up @@ -302,3 +321,17 @@ resource "google_storage_bucket" "bucket" {
}
`, bucketName, storageClass, locationBlock)
}

func testGoogleStorageBucketsCors(bucketName string) string {
return fmt.Sprintf(`
resource "google_storage_bucket" "bucket" {
name = "%s"
cors {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: indentation

Also can you add another cors block?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

origin = ["abc", "def"]
method = ["a1a"]
response_header = ["123", "456", "789"]
max_age_seconds = 10
}
}
`, bucketName)
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ description: |-

# google\_storage\_bucket

Creates a new bucket in Google cloud storage service(GCS). Currently, it will not change location nor ACL once a bucket has been created with Terraform. For more information see [the official documentation](https://cloud.google.com/storage/docs/overview) and [API](https://cloud.google.com/storage/docs/json_api).
Creates a new bucket in Google cloud storage service(GCS). Currently, it will not change location nor ACL once a bucket has been created with Terraform. For more information see [the official documentation](https://cloud.google.com/storage/docs/overview) and [API](https://cloud.google.com/storage/docs/json_api/v1/buckets).


## Example Usage
Expand Down Expand Up @@ -50,15 +50,27 @@ to `google_storage_bucket_acl.predefined_acl`.

* `storage_class` - (Optional) The [Storage Class](https://cloud.google.com/storage/docs/storage-classes) of the new bucket. Supported values include: `MULTI_REGIONAL`, `REGIONAL`, `NEARLINE`, `COLDLINE`.

* `website` - (Optional) Configuration if the bucket acts as a website.
* `website` - (Optional) Configuration if the bucket acts as a website. Structure is documented below.

The optional `website` block supports:
* `cors` - (Optional) The bucket's [Cross-Origin Resource Sharing (CORS)](https://www.w3.org/TR/cors/) configuration. Multiple blocks of this type are permitted. Structure is documented below.

The `website` block supports:

* `main_page_suffix` - (Optional) Behaves as the bucket's directory index where
missing objects are treated as potential directories.

* `not_found_page` - (Optional) The custom object to return when a requested
resource is not found.

The `cors` block supports:

* `origin` - (Optional) The list of [Origins](https://tools.ietf.org/html/rfc6454) eligible to receive CORS response headers. Note: "*" is permitted in the list of origins, and means "any Origin".

* `method` - (Optional) The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list of methods, and means "any method".

* `response_header` - (Optional) The list of HTTP headers other than the [simple response headers](https://www.w3.org/TR/cors/#simple-response-header) to give permission for the user-agent to share across domains.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: too many spaces?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


* `max_age_seconds` - (Optional) The value, in seconds, to return in the [Access-Control-Max-Age header](https://www.w3.org/TR/cors/#access-control-max-age-response-header) used in preflight responses.

## Attributes Reference

Expand Down