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

compute_snapshot datasource added #6527

Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<% autogen_exception -%>
package google

import (
"fmt"
"log"
"sort"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
<% if version == "ga" -%>
"google.golang.org/api/compute/v1"
rileykarson marked this conversation as resolved.
Show resolved Hide resolved
<% else -%>
"google.golang.org/api/compute/v0.beta"
<% end -%>
)

func dataSourceGoogleComputeSnapshot() *schema.Resource {

dsSchema := datasourceSchemaFromResourceSchema(resourceComputeSnapshot().Schema)

dsSchema["filter"] = &schema.Schema{
rileykarson marked this conversation as resolved.
Show resolved Hide resolved
Type: schema.TypeString,
Optional: true,
}
dsSchema["most_recent"] = &schema.Schema{
Type: schema.TypeBool,
Optional: true,
}

addOptionalFieldsToSchema(dsSchema, "name", "filter", "most_recent", "project")

dsSchema["name"].ExactlyOneOf = []string{"name", "filter"}
dsSchema["filter"].ExactlyOneOf = []string{"name", "filter"}

return &schema.Resource{
Read: dataSourceGoogleComputeSnapshotRead,
Schema: dsSchema,
}
}

func dataSourceGoogleComputeSnapshotRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

project, err := getProject(d, config)
if err != nil {
return err
}

if v, ok := d.GetOk("name"); ok {
return retrieveSnapshot(d, meta, project, v.(string))
}

if v, ok := d.GetOk("filter"); ok {
log.Printf("snapshots: %v", v)
rileykarson marked this conversation as resolved.
Show resolved Hide resolved

rileykarson marked this conversation as resolved.
Show resolved Hide resolved
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}

snapshots, err := config.NewComputeClient(userAgent).Snapshots.List(project).Filter(v.(string)).Do()
rileykarson marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return fmt.Errorf("error retrieving list of instance snapshots: %s", err)
}

mostRecent := d.Get("most_recent").(bool)
rileykarson marked this conversation as resolved.
Show resolved Hide resolved
if mostRecent {
sort.Sort(ByCreationTimestampOfSnapshot(snapshots.Items))
}

count := len(snapshots.Items)
if count == 1 || count > 1 && mostRecent {
return retrieveSnapshot(d, meta, project, snapshots.Items[0].Name)
}

return fmt.Errorf("your filter has returned %d instance snapshot(s). Please refine your filter or set most_recent to return exactly one instance snapshot", len(snapshots.Items))

}

return fmt.Errorf("one of name or filter must be set")

}

func retrieveSnapshot(d *schema.ResourceData, meta interface{}, project, name string) error {
d.SetId("projects/" + project + "/global/snapshots/" + name)
d.Set("name", name)
return resourceComputeSnapshotRead(d, meta)
}

// ByCreationTimestamp implements sort.Interface for []*Snapshot based on
// the CreationTimestamp field.
type ByCreationTimestampOfSnapshot []*compute.Snapshot

func (a ByCreationTimestampOfSnapshot) Len() int { return len(a) }
func (a ByCreationTimestampOfSnapshot) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByCreationTimestampOfSnapshot) Less(i, j int) bool {
return a[i].CreationTimestamp > a[j].CreationTimestamp
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
package google

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

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

vcrTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccSnapshot_name(getTestProjectFromEnv(), randString(t, 10)),
Check: resource.ComposeTestCheckFunc(
checkDataSourceStateMatchesResourceStateWithIgnores(
"data.google_compute_snapshot.default",
"google_compute_snapshot.default",
map[string]struct{}{"zone": {}},
),
),
},
},
})
}

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

vcrTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccSnapshot_filter(getTestProjectFromEnv(), randString(t, 10)),
Check: resource.ComposeTestCheckFunc(
checkDataSourceStateMatchesResourceStateWithIgnores(
"data.google_compute_snapshot.default",
"google_compute_snapshot.c",
map[string]struct{}{"zone": {}},
),
),
},
},
})
}

func TestAccSnapshotDatasource_filter_mostRecent(t *testing.T) {
rileykarson marked this conversation as resolved.
Show resolved Hide resolved
t.Parallel()

vcrTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccSnapshot_filter_mostRecent(getTestProjectFromEnv(), randString(t, 10)),
Check: resource.ComposeTestCheckFunc(
checkDataSourceStateMatchesResourceStateWithIgnores(
"data.google_compute_snapshot.default",
"google_compute_snapshot.c",
map[string]struct{}{"zone": {}},
),
),
},
},
})
}

func testAccSnapshot_name(project, suffix string) string {
return Nprintf(`
data "google_compute_image" "tf-test-image" {
family = "debian-11"
project = "debian-cloud"
}
resource "google_compute_disk" "tf-test-disk" {
name = "debian-disk-%{suffix}"
image = data.google_compute_image.tf-test-image.self_link
size = 10
type = "pd-ssd"
zone = "us-central1-a"
}

resource "google_compute_snapshot" "default" {
name = "tf-test-snapshot-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "value"
}
storage_locations = ["us-central1"]
}
data "google_compute_snapshot" "default" {
project = "%{project}"
name = google_compute_snapshot.default.name
}

`, map[string]interface{}{"project": project, "suffix": suffix})
}

func testAccSnapshot_filter(project, suffix string) string {
return Nprintf(`
data "google_compute_image" "tf-test-image" {
family = "debian-11"
project = "debian-cloud"
}
resource "google_compute_disk" "tf-test-disk" {
name = "debian-disk-%{suffix}"
image = data.google_compute_image.tf-test-image.self_link
size = 10
type = "pd-ssd"
zone = "us-central1-a"
}
resource "google_compute_snapshot" "a" {
name = "tf-test-snapshot-a-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "a"
}
storage_locations = ["us-central1"]
}
resource "google_compute_snapshot" "b" {
name = "tf-test-snapshot-b-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "b"
}
storage_locations = ["us-central1"]
}
resource "google_compute_snapshot" "c" {
name = "tf-test-snapshot-c-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "c"
}
storage_locations = ["us-central1"]
}
data "google_compute_snapshot" "default" {
project = "%{project}"
filter = "name = tf-test-snapshot-c-%{suffix}"
depends_on = [google_compute_snapshot.c]
}
`, map[string]interface{}{"project": project, "suffix": suffix})
}

func testAccSnapshot_filter_mostRecent(project, suffix string) string {
return Nprintf(`
data "google_compute_image" "tf-test-image" {
family = "debian-11"
project = "debian-cloud"
}
resource "google_compute_disk" "tf-test-disk" {
name = "debian-disk-%{suffix}"
image = data.google_compute_image.tf-test-image.self_link
size = 10
type = "pd-ssd"
zone = "us-central1-a"
}
resource "google_compute_snapshot" "a" {
name = "tf-test-snapshot-a-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "a"
}
storage_locations = ["us-central1"]
}
resource "google_compute_snapshot" "b" {
name = "tf-test-snapshot-b-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "b"
}
storage_locations = ["us-central1"]
}
resource "google_compute_snapshot" "c" {
name = "tf-test-snapshot-c-%{suffix}"
description = "Example snapshot."
source_disk = google_compute_disk.tf-test-disk.id
zone = "us-central1-a"
labels = {
my_label = "c"
}
storage_locations = ["us-central1"]
}
data "google_compute_snapshot" "default" {
project = "%{project}"
most_recent = true
filter = "name = tf-test-snapshot-c-%{suffix}"
depends_on = [google_compute_snapshot.c]
}
`, map[string]interface{}{"project": project, "suffix": suffix})
}
1 change: 1 addition & 0 deletions mmv1/third_party/terraform/utils/provider.go.erb
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ func Provider() *schema.Provider {
"google_compute_resource_policy": dataSourceGoogleComputeResourcePolicy(),
"google_compute_router": dataSourceGoogleComputeRouter(),
"google_compute_router_status": dataSourceGoogleComputeRouterStatus(),
"google_compute_snapshot": dataSourceGoogleComputeSnapshot(),
Copy link
Member

Choose a reason for hiding this comment

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

nit: The spacing here uses tabs rather than 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.

fixed

"google_compute_ssl_certificate": dataSourceGoogleComputeSslCertificate(),
"google_compute_ssl_policy": dataSourceGoogleComputeSslPolicy(),
"google_compute_subnetwork": dataSourceGoogleComputeSubnetwork(),
Expand Down