From 44c6bb21c4d200a99d1abafbfce2983b9cc7c7da Mon Sep 17 00:00:00 2001 From: Chris Sng Date: Wed, 18 Sep 2019 15:25:13 +0000 Subject: [PATCH] Allow updating of resource policies in compute_disk Signed-off-by: Modular Magician --- google-beta/provider.go | 5 +- google-beta/resource_compute_disk.go | 1 + ...compute_disk_resource_policy_attachment.go | 336 ++++++++++++++++++ ...te_disk_resource_policy_attachment_test.go | 80 +++++ ..._compute_resource_policy_generated_test.go | 26 +- ...k_resource_policy_attachment.html.markdown | 81 +++++ .../r/compute_resource_policy.html.markdown | 22 +- 7 files changed, 517 insertions(+), 34 deletions(-) create mode 100644 google-beta/resource_compute_disk_resource_policy_attachment.go create mode 100644 google-beta/resource_compute_disk_resource_policy_attachment_test.go create mode 100644 website/docs/r/compute_disk_resource_policy_attachment.html.markdown diff --git a/google-beta/provider.go b/google-beta/provider.go index e32fe923ff..740807efbb 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -464,9 +464,9 @@ func Provider() terraform.ResourceProvider { return provider } -// Generated resources: 97 +// Generated resources: 98 // Generated IAM resources: 21 -// Total generated resources: 118 +// Total generated resources: 119 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -500,6 +500,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_backend_service": resourceComputeBackendService(), "google_compute_region_backend_service": resourceComputeRegionBackendService(), "google_compute_backend_service_signed_url_key": resourceComputeBackendServiceSignedUrlKey(), + "google_compute_disk_resource_policy_attachment": resourceComputeDiskResourcePolicyAttachment(), "google_compute_disk": resourceComputeDisk(), "google_compute_firewall": resourceComputeFirewall(), "google_compute_forwarding_rule": resourceComputeForwardingRule(), diff --git a/google-beta/resource_compute_disk.go b/google-beta/resource_compute_disk.go index e50b2aa196..fc20fd8d21 100644 --- a/google-beta/resource_compute_disk.go +++ b/google-beta/resource_compute_disk.go @@ -298,6 +298,7 @@ func resourceComputeDisk() *schema.Resource { }, "resource_policies": { Type: schema.TypeList, + Computed: true, Optional: true, ForceNew: true, Elem: &schema.Schema{ diff --git a/google-beta/resource_compute_disk_resource_policy_attachment.go b/google-beta/resource_compute_disk_resource_policy_attachment.go new file mode 100644 index 0000000000..fa8f92c80b --- /dev/null +++ b/google-beta/resource_compute_disk_resource_policy_attachment.go @@ -0,0 +1,336 @@ +// ---------------------------------------------------------------------------- +// +// *** 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/helper/schema" + "google.golang.org/api/compute/v1" +) + +func resourceComputeDiskResourcePolicyAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceComputeDiskResourcePolicyAttachmentCreate, + Read: resourceComputeDiskResourcePolicyAttachmentRead, + Delete: resourceComputeDiskResourcePolicyAttachmentDelete, + + Importer: &schema.ResourceImporter{ + State: resourceComputeDiskResourcePolicyAttachmentImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "disk": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "zone": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + } +} + +func resourceComputeDiskResourcePolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + obj := make(map[string]interface{}) + nameProp, err := expandComputeDiskResourcePolicyAttachmentName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp + } + + obj, err = resourceComputeDiskResourcePolicyAttachmentEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/disks/{{disk}}/addResourcePolicies") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new DiskResourcePolicyAttachment: %#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 DiskResourcePolicyAttachment: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "{{project}}/{{zone}}/{{disk}}/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + op := &compute.Operation{} + err = Convert(res, op) + if err != nil { + return err + } + + waitErr := computeOperationWaitTime( + config.clientCompute, op, project, "Creating DiskResourcePolicyAttachment", + int(d.Timeout(schema.TimeoutCreate).Minutes())) + + if waitErr != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create DiskResourcePolicyAttachment: %s", waitErr) + } + + log.Printf("[DEBUG] Finished creating DiskResourcePolicyAttachment %q: %#v", d.Id(), res) + + return resourceComputeDiskResourcePolicyAttachmentRead(d, meta) +} + +func resourceComputeDiskResourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/disks/{{disk}}") + 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("ComputeDiskResourcePolicyAttachment %q", d.Id())) + } + + res, err = flattenNestedComputeDiskResourcePolicyAttachment(d, meta, res) + if err != nil { + return err + } + + if res == nil { + // Object isn't there any more - remove it from the state. + log.Printf("[DEBUG] Removing ComputeDiskResourcePolicyAttachment because it couldn't be matched.") + d.SetId("") + return nil + } + + res, err = resourceComputeDiskResourcePolicyAttachmentDecoder(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 ComputeDiskResourcePolicyAttachment because it no longer exists.") + d.SetId("") + return nil + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading DiskResourcePolicyAttachment: %s", err) + } + + if err := d.Set("name", flattenComputeDiskResourcePolicyAttachmentName(res["name"], d)); err != nil { + return fmt.Errorf("Error reading DiskResourcePolicyAttachment: %s", err) + } + + return nil +} + +func resourceComputeDiskResourcePolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/disks/{{disk}}/removeResourcePolicies") + if err != nil { + return err + } + + var obj map[string]interface{} + obj = make(map[string]interface{}) + + // projects/{project}/regions/{region}/resourcePolicies/{resourceId} + region := getRegionFromZone(d.Get("zone").(string)) + + name, err := expandComputeDiskResourcePolicyAttachmentName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(name)) && (ok || !reflect.DeepEqual(v, name)) { + obj["resourcePolicies"] = []interface{}{fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", project, region, name)} + } + log.Printf("[DEBUG] Deleting DiskResourcePolicyAttachment %q", d.Id()) + + res, err := sendRequestWithTimeout(config, "POST", project, url, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "DiskResourcePolicyAttachment") + } + + op := &compute.Operation{} + err = Convert(res, op) + if err != nil { + return err + } + + err = computeOperationWaitTime( + config.clientCompute, op, project, "Deleting DiskResourcePolicyAttachment", + int(d.Timeout(schema.TimeoutDelete).Minutes())) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting DiskResourcePolicyAttachment %q: %#v", d.Id(), res) + return nil +} + +func resourceComputeDiskResourcePolicyAttachmentImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/zones/(?P[^/]+)/disks/(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "{{project}}/{{zone}}/{{disk}}/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenComputeDiskResourcePolicyAttachmentName(v interface{}, d *schema.ResourceData) interface{} { + return v +} + +func expandComputeDiskResourcePolicyAttachmentName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func resourceComputeDiskResourcePolicyAttachmentEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { + config := meta.(*Config) + project, err := getProject(d, config) + if err != nil { + return nil, err + } + + region := getRegionFromZone(d.Get("zone").(string)) + + obj["resourcePolicies"] = []interface{}{fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", project, region, obj["name"])} + delete(obj, "name") + return obj, nil +} + +func flattenNestedComputeDiskResourcePolicyAttachment(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + var v interface{} + var ok bool + + v, ok = res["resourcePolicies"] + if !ok || v == nil { + return nil, nil + } + + switch v.(type) { + case []interface{}: + break + case map[string]interface{}: + // Construct list out of single nested resource + v = []interface{}{v} + default: + return nil, fmt.Errorf("expected list or map for value resourcePolicies. Actual value: %v", v) + } + + _, item, err := resourceComputeDiskResourcePolicyAttachmentFindNestedObjectInList(d, meta, v.([]interface{})) + if err != nil { + return nil, err + } + return item, nil +} + +func resourceComputeDiskResourcePolicyAttachmentFindNestedObjectInList(d *schema.ResourceData, meta interface{}, items []interface{}) (index int, item map[string]interface{}, err error) { + expectedName, err := expandComputeDiskResourcePolicyAttachmentName(d.Get("name"), d, meta.(*Config)) + if err != nil { + return -1, nil, err + } + + // Search list for this resource. + for idx, itemRaw := range items { + if itemRaw == nil { + continue + } + // List response only contains the ID - construct a response object. + item := map[string]interface{}{ + "name": itemRaw, + } + + // Decode list item before comparing. + item, err := resourceComputeDiskResourcePolicyAttachmentDecoder(d, meta, item) + if err != nil { + return -1, nil, err + } + + itemName := flattenComputeDiskResourcePolicyAttachmentName(item["name"], d) + if !reflect.DeepEqual(itemName, expectedName) { + log.Printf("[DEBUG] Skipping item with name= %#v, looking for %#v)", itemName, expectedName) + continue + } + log.Printf("[DEBUG] Found item for resource %q: %#v)", d.Id(), item) + return idx, item, nil + } + return -1, nil, nil +} +func resourceComputeDiskResourcePolicyAttachmentDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + res["name"] = GetResourceNameFromSelfLink(res["name"].(string)) + return res, nil +} diff --git a/google-beta/resource_compute_disk_resource_policy_attachment_test.go b/google-beta/resource_compute_disk_resource_policy_attachment_test.go new file mode 100644 index 0000000000..fbfbeab071 --- /dev/null +++ b/google-beta/resource_compute_disk_resource_policy_attachment_test.go @@ -0,0 +1,80 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeDiskResourcePolicyAttachment_basic(t *testing.T) { + t.Parallel() + + diskName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + policyName := fmt.Sprintf("tf-test-policy-%s", acctest.RandString(10)) + policyName2 := fmt.Sprintf("tf-test-policy-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccComputeDiskResourcePolicyAttachment_basic(diskName, policyName), + }, + { + ResourceName: "google_compute_disk_resource_policy_attachment.foobar", + // ImportStateId: fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", getTestProjectFromEnv(), "us-central1", policyName), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeDiskResourcePolicyAttachment_basic(diskName, policyName2), + }, + { + ResourceName: "google_compute_disk_resource_policy_attachment.foobar", + // ImportStateId: fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", getTestProjectFromEnv(), "us-central1", policyName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccComputeDiskResourcePolicyAttachment_basic(diskName, policyName string) string { + return fmt.Sprintf(` +data "google_compute_image" "my_image" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "foobar" { + name = "%s" + image = "${data.google_compute_image.my_image.self_link}" + size = 50 + type = "pd-ssd" + zone = "us-central1-a" + labels = { + my-label = "my-label-value" + } +} + +resource "google_compute_resource_policy" "foobar" { + name = "%s" + region = "us-central1" + snapshot_schedule_policy { + schedule { + daily_schedule { + days_in_cycle = 1 + start_time = "04:00" + } + } + } +} + +resource "google_compute_disk_resource_policy_attachment" "foobar" { + name = google_compute_resource_policy.foobar.name + disk = google_compute_disk.foobar.name + zone = "us-central1-a" +}`, diskName, policyName) +} diff --git a/google-beta/resource_compute_resource_policy_generated_test.go b/google-beta/resource_compute_resource_policy_generated_test.go index 990265236d..91ee4b8c23 100644 --- a/google-beta/resource_compute_resource_policy_generated_test.go +++ b/google-beta/resource_compute_resource_policy_generated_test.go @@ -33,25 +33,24 @@ func TestAccComputeResourcePolicy_resourcePolicyBasicExample(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProvidersOiCS, + Providers: testAccProviders, CheckDestroy: testAccCheckComputeResourcePolicyDestroy, Steps: []resource.TestStep{ { Config: testAccComputeResourcePolicy_resourcePolicyBasicExample(context), }, + { + ResourceName: "google_compute_resource_policy.foo", + ImportState: true, + ImportStateVerify: true, + }, }, }) } func testAccComputeResourcePolicy_resourcePolicyBasicExample(context map[string]interface{}) string { return Nprintf(` -provider "google-beta" { - region = "us-central1" - zone = "us-central1-a" -} - resource "google_compute_resource_policy" "foo" { - provider = "google-beta" name = "policy%{random_suffix}" region = "us-central1" snapshot_schedule_policy { @@ -75,25 +74,24 @@ func TestAccComputeResourcePolicy_resourcePolicyFullExample(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProvidersOiCS, + Providers: testAccProviders, CheckDestroy: testAccCheckComputeResourcePolicyDestroy, Steps: []resource.TestStep{ { Config: testAccComputeResourcePolicy_resourcePolicyFullExample(context), }, + { + ResourceName: "google_compute_resource_policy.bar", + ImportState: true, + ImportStateVerify: true, + }, }, }) } func testAccComputeResourcePolicy_resourcePolicyFullExample(context map[string]interface{}) string { return Nprintf(` -provider "google-beta" { - region = "us-central1" - zone = "us-central1-a" -} - resource "google_compute_resource_policy" "bar" { - provider = "google-beta" name = "policy%{random_suffix}" region = "us-central1" snapshot_schedule_policy { diff --git a/website/docs/r/compute_disk_resource_policy_attachment.html.markdown b/website/docs/r/compute_disk_resource_policy_attachment.html.markdown new file mode 100644 index 0000000000..965952ad4e --- /dev/null +++ b/website/docs/r/compute_disk_resource_policy_attachment.html.markdown @@ -0,0 +1,81 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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. +# +# ---------------------------------------------------------------------------- +layout: "google" +page_title: "Google: google_compute_disk_resource_policy_attachment" +sidebar_current: "docs-google-compute-disk-resource-policy-attachment" +description: |- + Disk resource policies define a schedule for taking snapshots and a + retention period for these snapshots. +--- + +# google\_compute\_disk\_resource\_policy\_attachment + +Disk resource policies define a schedule for taking snapshots and a +retention period for these snapshots. + + + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + The resource policy to be attached to the disk for scheduling snapshot + creation. Do not specify the self link. + +* `disk` - + (Required) + The name of the disk in which the resource policies are attached to. + + +- - - + + +* `zone` - + (Optional) + A reference to the zone where the disk resides. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + +DiskResourcePolicyAttachment can be imported using any of these accepted formats: + +``` +$ terraform import google_compute_disk_resource_policy_attachment.default projects/{{project}}/zones/{{zone}}/disks/{{disk}}/{{name}} +$ terraform import google_compute_disk_resource_policy_attachment.default {{project}}/{{zone}}/{{disk}}/{{name}} +$ terraform import google_compute_disk_resource_policy_attachment.default {{zone}}/{{disk}}/{{name}} +$ terraform import google_compute_disk_resource_policy_attachment.default {{disk}}/{{name}} +``` + +-> 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/provider_reference.html#user_project_override). diff --git a/website/docs/r/compute_resource_policy.html.markdown b/website/docs/r/compute_resource_policy.html.markdown index 0ca5a3febf..f1a647ddc9 100644 --- a/website/docs/r/compute_resource_policy.html.markdown +++ b/website/docs/r/compute_resource_policy.html.markdown @@ -23,8 +23,6 @@ description: |- A policy that can be attached to a resource to specify or schedule actions on that resource. -~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. -See [Provider Versions](https://terraform.io/docs/providers/google/provider_versions.html) for more details on beta resources.
@@ -36,13 +34,7 @@ See [Provider Versions](https://terraform.io/docs/providers/google/provider_vers ```hcl -provider "google-beta" { - region = "us-central1" - zone = "us-central1-a" -} - resource "google_compute_resource_policy" "foo" { - provider = "google-beta" name = "policy" region = "us-central1" snapshot_schedule_policy { @@ -64,13 +56,7 @@ resource "google_compute_resource_policy" "foo" { ```hcl -provider "google-beta" { - region = "us-central1" - zone = "us-central1-a" -} - resource "google_compute_resource_policy" "bar" { - provider = "google-beta" name = "policy" region = "us-central1" snapshot_schedule_policy { @@ -238,10 +224,10 @@ This resource provides the following ResourcePolicy can be imported using any of these accepted formats: ``` -$ terraform import -provider=google-beta google_compute_resource_policy.default projects/{{project}}/regions/{{region}}/resourcePolicies/{{name}} -$ terraform import -provider=google-beta google_compute_resource_policy.default {{project}}/{{region}}/{{name}} -$ terraform import -provider=google-beta google_compute_resource_policy.default {{region}}/{{name}} -$ terraform import -provider=google-beta google_compute_resource_policy.default {{name}} +$ terraform import google_compute_resource_policy.default projects/{{project}}/regions/{{region}}/resourcePolicies/{{name}} +$ terraform import google_compute_resource_policy.default {{project}}/{{region}}/{{name}} +$ terraform import google_compute_resource_policy.default {{region}}/{{name}} +$ terraform import google_compute_resource_policy.default {{name}} ``` -> If you're importing a resource with beta features, make sure to include `-provider=google-beta`