Skip to content

Commit

Permalink
Add support for configuring disk resource policies for google_compute…
Browse files Browse the repository at this point in the history
…_instance_template. (#8237)

* Add support for configuring disk resource policies for google_compute_instance_template.

Fixes #6719

* Document resource_policies field for instance template disks.

* Update resource_policies docs and example to use .id rather than .self_link.
  • Loading branch information
rayward committed Feb 1, 2021
1 parent 4eee7bf commit d34040d
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 12 deletions.
19 changes: 19 additions & 0 deletions google/resource_compute_instance_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,18 @@ func resourceComputeInstanceTemplate() *schema.Resource {
},
},
},

"resource_policies": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: `A list (short name or id) of resource policies to attach to this disk. Currently a max of 1 resource policy is supported.`,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: compareResourceNames,
},
},
},
},
},
Expand Down Expand Up @@ -757,6 +769,11 @@ func buildDisks(d *schema.ResourceData, config *Config) ([]*computeBeta.Attached
}

disk.InitializeParams.Labels = expandStringMap(d, prefix+".labels")

if _, ok := d.GetOk(prefix + ".resource_policies"); ok {
// instance template only supports a resource name here (not uri)
disk.InitializeParams.ResourcePolicies = convertAndMapStringArr(d.Get(prefix+".resource_policies").([]interface{}), GetResourceNameFromSelfLink)
}
}

if v, ok := d.GetOk(prefix + ".interface"); ok {
Expand Down Expand Up @@ -951,6 +968,8 @@ func flattenDisk(disk *computeBeta.AttachedDisk, defaultProject string) (map[str
} else {
diskMap["disk_size_gb"] = disk.InitializeParams.DiskSizeGb
}

diskMap["resource_policies"] = disk.InitializeParams.ResourcePolicies
}

if disk.DiskEncryptionKey != nil {
Expand Down
87 changes: 85 additions & 2 deletions google/resource_compute_instance_template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,33 @@ func TestAccComputeInstanceTemplate_imageResourceTest(t *testing.T) {
})
}

func TestAccComputeInstanceTemplate_resourcePolicies(t *testing.T) {
t.Parallel()

var instanceTemplate computeBeta.InstanceTemplate
policyName := "tf-test-policy-" + randString(t, 10)

vcrTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckComputeInstanceTemplateDestroyProducer(t),
Steps: []resource.TestStep{
{
Config: testAccComputeInstanceTemplate_resourcePolicies(randString(t, 10), policyName),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeInstanceTemplateExists(t, "google_compute_instance_template.foobar", &instanceTemplate),
testAccCheckComputeInstanceTemplateHasDiskResourcePolicy(&instanceTemplate, policyName),
),
},
{
ResourceName: "google_compute_instance_template.foobar",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccCheckComputeInstanceTemplateDestroyProducer(t *testing.T) func(s *terraform.State) error {
return func(s *terraform.State) error {
config := googleProviderConfig(t)
Expand Down Expand Up @@ -1247,6 +1274,17 @@ func testAccCheckComputeInstanceTemplateLacksShieldedVmConfig(instanceTemplate *
}
}

func testAccCheckComputeInstanceTemplateHasDiskResourcePolicy(instanceTemplate *computeBeta.InstanceTemplate, resourcePolicy string) resource.TestCheckFunc {
return func(s *terraform.State) error {
resourcePolicyActual := instanceTemplate.Properties.Disks[0].InitializeParams.ResourcePolicies[0]
if resourcePolicyActual != resourcePolicy {
return fmt.Errorf("Wrong disk resource policy: expected %s, got %s", resourcePolicy, resourcePolicyActual)
}

return nil
}
}

func testAccComputeInstanceTemplate_basic(suffix string) string {
return fmt.Sprintf(`
data "google_compute_image" "my_image" {
Expand Down Expand Up @@ -2200,7 +2238,7 @@ data "google_compute_image" "my_image" {
family = "debian-9"
project = "debian-cloud"
}
resource "google_compute_disk" "my_disk" {
name = "%s"
zone = "us-central1-a"
Expand All @@ -2222,6 +2260,51 @@ resource "google_compute_instance_template" "foobar" {
access_config {}
}
}
`, diskName, imageName, imageDescription)
}

func testAccComputeInstanceTemplate_resourcePolicies(suffix string, policyName string) string {
return fmt.Sprintf(`
data "google_compute_image" "my_image" {
family = "debian-9"
project = "debian-cloud"
}
resource "google_compute_instance_template" "foobar" {
name = "instance-test-%s"
machine_type = "e2-medium"
can_ip_forward = false
disk {
source_image = data.google_compute_image.my_image.self_link
resource_policies = [google_compute_resource_policy.foo.id]
}
network_interface {
network = "default"
}
service_account {
scopes = ["userinfo-email", "compute-ro", "storage-ro"]
}
labels = {
my_label = "foobar"
}
}
resource "google_compute_resource_policy" "foo" {
name = "%s"
region = "us-central1"
snapshot_schedule_policy {
schedule {
daily_schedule {
days_in_cycle = 1
start_time = "04:00"
}
}
}
}
`, suffix, policyName)
}
10 changes: 6 additions & 4 deletions website/docs/d/compute_instance_template.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ The following arguments are supported:

- `name` - (Optional) The name of the instance template. One of `name` or `filter` must be provided.

- `filter` - (Optional) A filter to retrieve the instance templates.
- `filter` - (Optional) A filter to retrieve the instance templates.
See [gcloud topic filters](https://cloud.google.com/sdk/gcloud/reference/topic/filters) for reference.
If multiple instance templates match, either adjust the filter or specify `most_recent`. One of `name` or `filter` must be provided.

Expand Down Expand Up @@ -137,9 +137,9 @@ The `disk` block supports:
`{project}/{image}`, `{family}`, or `{image}`.
~> **Note:** Either `source` or `source_image` is **required** in a disk block unless the disk type is `local-ssd`. Check the API [docs](https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert) for details.

* `interface` - Specifies the disk interface to use for attaching this disk,
which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI
and the request will fail if you attempt to attach a persistent disk in any other format
* `interface` - Specifies the disk interface to use for attaching this disk,
which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI
and the request will fail if you attempt to attach a persistent disk in any other format
than SCSI. Local SSDs can use either NVME or SCSI.

* `mode` - The mode in which to attach this disk, either READ_WRITE
Expand Down Expand Up @@ -170,6 +170,8 @@ The `disk` block supports:

Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group.

* `resource_policies` (Optional) -- A list of short names of resource policies to attach to this disk for automatic snapshot creations. Currently a max of 1 resource policy is supported.

The `disk_encryption_key` block supports:

* `kms_key_self_link` - The self link of the encryption key that is stored in Google Cloud KMS
Expand Down
29 changes: 23 additions & 6 deletions website/docs/r/compute_instance_template.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ resource "google_compute_instance_template" "default" {
// Create a new boot disk from an image
disk {
source_image = "debian-cloud/debian-9"
auto_delete = true
boot = true
source_image = "debian-cloud/debian-9"
auto_delete = true
boot = true
// backup the disk every day
resource_policies = [google_compute_resource_policy.daily_backup.id]
}
// Use an existing disk resource
Expand Down Expand Up @@ -84,6 +86,19 @@ resource "google_compute_disk" "foobar" {
type = "pd-ssd"
zone = "us-central1-a"
}
resource "google_compute_resource_policy" "daily_backup" {
name = "every-day-4am"
region = "us-central1"
snapshot_schedule_policy {
schedule {
daily_schedule {
days_in_cycle = 1
start_time = "04:00"
}
}
}
}
```

## Using with Instance Group Manager
Expand Down Expand Up @@ -278,9 +293,9 @@ The `disk` block supports:
`{project}/{image}`, `{family}`, or `{image}`.
~> **Note:** Either `source` or `source_image` is **required** in a disk block unless the disk type is `local-ssd`. Check the API [docs](https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert) for details.

* `interface` - (Optional) Specifies the disk interface to use for attaching this disk,
which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI
and the request will fail if you attempt to attach a persistent disk in any other format
* `interface` - (Optional) Specifies the disk interface to use for attaching this disk,
which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI
and the request will fail if you attempt to attach a persistent disk in any other format
than SCSI. Local SSDs can use either NVME or SCSI.

* `mode` - (Optional) The mode in which to attach this disk, either READ_WRITE
Expand Down Expand Up @@ -311,6 +326,8 @@ The `disk` block supports:

Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group.

* `resource_policies` (Optional) -- A list (short name or id) of resource policies to attach to this disk for automatic snapshot creations. Currently a max of 1 resource policy is supported.

The `disk_encryption_key` block supports:

* `kms_key_self_link` - (Required) The self link of the encryption key that is stored in Google Cloud KMS
Expand Down

0 comments on commit d34040d

Please sign in to comment.