diff --git a/.changelog/3084.txt b/.changelog/3084.txt new file mode 100644 index 0000000000..5df488d1cf --- /dev/null +++ b/.changelog/3084.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_storage_hmac_key` +``` diff --git a/google-beta/provider.go b/google-beta/provider.go index 4eb4a2cbcd..02c82d8596 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -554,9 +554,9 @@ func Provider() terraform.ResourceProvider { return provider } -// Generated resources: 118 +// Generated resources: 119 // Generated IAM resources: 54 -// Total generated resources: 172 +// Total generated resources: 173 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -735,6 +735,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_storage_bucket_access_control": resourceStorageBucketAccessControl(), "google_storage_object_access_control": resourceStorageObjectAccessControl(), "google_storage_default_object_access_control": resourceStorageDefaultObjectAccessControl(), + "google_storage_hmac_key": resourceStorageHmacKey(), "google_tpu_node": resourceTPUNode(), "google_vpc_access_connector": resourceVPCAccessConnector(), }, diff --git a/google-beta/resource_storage_hmac_key.go b/google-beta/resource_storage_hmac_key.go new file mode 100644 index 0000000000..674436b05b --- /dev/null +++ b/google-beta/resource_storage_hmac_key.go @@ -0,0 +1,361 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "log" + "reflect" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +func resourceStorageHmacKey() *schema.Resource { + return &schema.Resource{ + Create: resourceStorageHmacKeyCreate, + Read: resourceStorageHmacKeyRead, + Update: resourceStorageHmacKeyUpdate, + Delete: resourceStorageHmacKeyDelete, + + Importer: &schema.ResourceImporter{ + State: resourceStorageHmacKeyImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Update: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "service_account_email": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The email address of the key's associated service account.`, + }, + "state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "INACTIVE", ""}, false), + Description: `The state of the key. Can be set to one of ACTIVE, INACTIVE.`, + Default: "ACTIVE", + }, + "access_id": { + Type: schema.TypeString, + Computed: true, + Description: `The access ID of the HMAC Key.`, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + Description: `HMAC secret key material.`, + Sensitive: true, + }, + "time_created": { + Type: schema.TypeString, + Computed: true, + Description: `'The creation time of the HMAC key in RFC 3339 format. '`, + }, + "updated": { + Type: schema.TypeString, + Computed: true, + Description: `'The last modification time of the HMAC key metadata in RFC 3339 format.'`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + } +} + +func resourceStorageHmacKeyCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + obj := make(map[string]interface{}) + serviceAccountEmailProp, err := expandStorageHmacKeyServiceAccountEmail(d.Get("service_account_email"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("service_account_email"); !isEmptyValue(reflect.ValueOf(serviceAccountEmailProp)) && (ok || !reflect.DeepEqual(v, serviceAccountEmailProp)) { + obj["serviceAccountEmail"] = serviceAccountEmailProp + } + stateProp, err := expandStorageHmacKeyState(d.Get("state"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("state"); !isEmptyValue(reflect.ValueOf(stateProp)) && (ok || !reflect.DeepEqual(v, stateProp)) { + obj["state"] = stateProp + } + + url, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys?serviceAccountEmail={{service_account_email}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new HmacKey: %#v", obj) + project, err := getProject(d, config) + if err != nil { + return err + } + res, err := sendRequestWithTimeout(config, "POST", project, url, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating HmacKey: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating HmacKey %q: %#v", d.Id(), res) + + // `secret` and `access_id` are generated by the API upon successful CREATE. The following + // ensures terraform has the correct values based on the Projects.hmacKeys response object. + secret, ok := res["secret"].(string) + if !ok { + return fmt.Errorf("The response to CREATE was missing an expected field. Your create did not work.") + } + + d.Set("secret", secret) + + metadata := res["metadata"].(map[string]interface{}) + accessId, ok := metadata["accessId"].(string) + if !ok { + return fmt.Errorf("The response to CREATE was missing an expected field. Your create did not work.") + } + + d.Set("access_id", accessId) + + id, err = replaceVars(d, config, "projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + + d.SetId(id) + + return resourceStorageHmacKeyRead(d, meta) +} + +func resourceStorageHmacKeyRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + url, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + + project, err := getProject(d, config) + if err != nil { + return err + } + res, err := sendRequest(config, "GET", project, url, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("StorageHmacKey %q", d.Id())) + } + + res, err = resourceStorageHmacKeyDecoder(d, meta, res) + if err != nil { + return err + } + + if res == nil { + // Decoding the object has resulted in it being gone. It may be marked deleted + log.Printf("[DEBUG] Removing StorageHmacKey because it no longer exists.") + d.SetId("") + return nil + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + + if err := d.Set("service_account_email", flattenStorageHmacKeyServiceAccountEmail(res["serviceAccountEmail"], d, config)); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + if err := d.Set("state", flattenStorageHmacKeyState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + if err := d.Set("access_id", flattenStorageHmacKeyAccessId(res["accessId"], d, config)); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + if err := d.Set("time_created", flattenStorageHmacKeyTimeCreated(res["timeCreated"], d, config)); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + if err := d.Set("updated", flattenStorageHmacKeyUpdated(res["updated"], d, config)); err != nil { + return fmt.Errorf("Error reading HmacKey: %s", err) + } + + return nil +} + +func resourceStorageHmacKeyUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + d.Partial(true) + + if d.HasChange("state") { + obj := make(map[string]interface{}) + + getUrl, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + getRes, err := sendRequest(config, "GET", project, getUrl, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("StorageHmacKey %q", d.Id())) + } + + obj["etag"] = getRes["etag"] + + stateProp, err := expandStorageHmacKeyState(d.Get("state"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("state"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, stateProp)) { + obj["state"] = stateProp + } + + url, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + _, err = sendRequestWithTimeout(config, "PUT", project, url, obj, d.Timeout(schema.TimeoutUpdate)) + if err != nil { + return fmt.Errorf("Error updating HmacKey %q: %s", d.Id(), err) + } + + d.SetPartial("state") + } + + d.Partial(false) + + return resourceStorageHmacKeyRead(d, meta) +} + +func resourceStorageHmacKeyDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + + var obj map[string]interface{} + getUrl, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + + getRes, err := sendRequest(config, "GET", project, getUrl, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("StorageHmacKey %q", d.Id())) + } + + // HmacKeys need to be INACTIVE to be deleted and the API doesn't accept noop + // updates + if v := getRes["state"]; v == "ACTIVE" { + getRes["state"] = "INACTIVE" + updateUrl, err := replaceVars(d, config, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Deactivating HmacKey %q: %#v", d.Id(), getRes) + _, err = sendRequestWithTimeout(config, "PUT", project, updateUrl, getRes, d.Timeout(schema.TimeoutUpdate)) + if err != nil { + return fmt.Errorf("Error deactivating HmacKey %q: %s", d.Id(), err) + } + } + log.Printf("[DEBUG] Deleting HmacKey %q", d.Id()) + + res, err := sendRequestWithTimeout(config, "DELETE", project, url, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "HmacKey") + } + + log.Printf("[DEBUG] Finished deleting HmacKey %q: %#v", d.Id(), res) + return nil +} + +func resourceStorageHmacKeyImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/hmacKeys/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenStorageHmacKeyServiceAccountEmail(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenStorageHmacKeyState(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenStorageHmacKeyAccessId(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenStorageHmacKeyTimeCreated(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenStorageHmacKeyUpdated(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandStorageHmacKeyServiceAccountEmail(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandStorageHmacKeyState(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func resourceStorageHmacKeyDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + if v := res["state"]; v == "DELETED" { + return nil, nil + } + + return res, nil +} diff --git a/google-beta/resource_storage_hmac_key_generated_test.go b/google-beta/resource_storage_hmac_key_generated_test.go new file mode 100644 index 0000000000..42ee1e3049 --- /dev/null +++ b/google-beta/resource_storage_hmac_key_generated_test.go @@ -0,0 +1,93 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" +) + +func TestAccStorageHmacKey_storageHmacKeyExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(10), + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckStorageHmacKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccStorageHmacKey_storageHmacKeyExample(context), + }, + { + ResourceName: "google_storage_hmac_key.key", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"secret"}, + }, + }, + }) +} + +func testAccStorageHmacKey_storageHmacKeyExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_service_account" "service_account" { + account_id = "tf-test-my-svc-acc%{random_suffix}" +} + +resource "google_storage_hmac_key" "key" { + service_account_email = google_service_account.service_account.email +} +`, context) +} + +func testAccCheckStorageHmacKeyDestroy(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_storage_hmac_key" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := testAccProvider.Meta().(*Config) + + url, err := replaceVarsForTest(config, rs, "{{StorageBasePath}}projects/{{project}}/hmacKeys/{{access_id}}") + if err != nil { + return err + } + + res, err := sendRequest(config, "GET", "", url, nil) + if err != nil { + return nil + } + + if v := res["state"]; v == "DELETED" { + return nil + } + + return fmt.Errorf("StorageHmacKey still exists at %s", url) + } + + return nil +} diff --git a/google-beta/resource_storage_hmac_key_test.go b/google-beta/resource_storage_hmac_key_test.go new file mode 100644 index 0000000000..7e28c89657 --- /dev/null +++ b/google-beta/resource_storage_hmac_key_test.go @@ -0,0 +1,53 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccStorageHmacKey_update(t *testing.T) { + t.Parallel() + + saName := fmt.Sprintf("%v%v", "service-account", acctest.RandString(10)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckStorageHmacKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGoogleStorageHmacKeyBasic(saName, "ACTIVE"), + }, + { + ResourceName: "google_storage_hmac_key.key", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"secret"}, + }, + { + Config: testAccGoogleStorageHmacKeyBasic(saName, "INACTIVE"), + }, + { + ResourceName: "google_storage_hmac_key.key", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"secret"}, + }, + }, + }) +} + +func testAccGoogleStorageHmacKeyBasic(saName, state string) string { + return fmt.Sprintf(` +resource "google_service_account" "service_account" { + account_id = "%s" +} + +resource "google_storage_hmac_key" "key" { + service_account_email = google_service_account.service_account.email + state = "%s" +} +`, saName, state) +} diff --git a/website/docs/r/storage_hmac_key.html.markdown b/website/docs/r/storage_hmac_key.html.markdown new file mode 100644 index 0000000000..af2e690343 --- /dev/null +++ b/website/docs/r/storage_hmac_key.html.markdown @@ -0,0 +1,122 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Cloud Storage" +layout: "google" +page_title: "Google: google_storage_hmac_key" +sidebar_current: "docs-google-storage-hmac-key" +description: |- + The hmacKeys resource represents an HMAC key within Cloud Storage. +--- + +# google\_storage\_hmac\_key + +The hmacKeys resource represents an HMAC key within Cloud Storage. The resource +consists of a secret and HMAC key metadata. HMAC keys can be used as credentials +for service accounts. + + +To get more information about HmacKey, see: + +* [API documentation](https://cloud.google.com/storage/docs/json_api/v1/projects/hmacKeys) +* How-to Guides + * [Official Documentation](https://cloud.google.com/storage/docs/authentication/managing-hmackeys) + +~> **Warning:** All arguments including the `secret` value will be stored in the raw +state as plain-text. [Read more about sensitive data in state](/docs/state/sensitive-data.html). +On import, the `secret` value will not be retrieved. + + +## Example Usage - Storage Hmac Key + + +```hcl +resource "google_service_account" "service_account" { + account_id = "my-svc-acc" +} + +resource "google_storage_hmac_key" "key" { + service_account_email = google_service_account.service_account.email +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `service_account_email` - + (Required) + The email address of the key's associated service account. + + +- - - + + +* `state` - + (Optional) + The state of the key. Can be set to one of ACTIVE, INACTIVE. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `projects/{{project}}/hmacKeys/{{access_id}}` + +* `secret` - + HMAC secret key material. + +* `access_id` - + The access ID of the HMAC Key. + +* `time_created` - + 'The creation time of the HMAC key in RFC 3339 format. ' + +* `updated` - + 'The last modification time of the HMAC key metadata in RFC 3339 format.' + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `update` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + +HmacKey can be imported using any of these accepted formats: + +``` +$ terraform import google_storage_hmac_key.default projects/{{project}}/hmacKeys/{{access_id}} +$ terraform import google_storage_hmac_key.default {{project}}/{{access_id}} +$ terraform import google_storage_hmac_key.default {{access_id}} +``` + +-> If you're importing a resource with beta features, make sure to include `-provider=google-beta` +as an argument so that Terraform uses the correct provider to import your resource. + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/google.erb b/website/google.erb index b69afcc5ba..f0d56d9711 100644 --- a/website/google.erb +++ b/website/google.erb @@ -1453,6 +1453,10 @@ google_storage_default_object_acl + > + google_storage_hmac_key + + > google_storage_notification