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

Add compute instance group data source #267

Merged
merged 2 commits into from
Aug 11, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
87 changes: 87 additions & 0 deletions google/data_source_google_compute_instance_group_instances.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package google

import (
"log"
"sort"
"strings"
"time"

compute "google.golang.org/api/compute/v1"

"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceGoogleComputeInstanceGroupInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceGoogleComputeInstanceGroupInstancesRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"zone": {
Type: schema.TypeString,
Required: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

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

name := d.Get("name").(string)
zone := d.Get("zone").(string)

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

resp, err := config.clientCompute.InstanceGroups.ListInstances(project, zone, name, nil).Do()
if err != nil {
return err
}

instances := flattenInstanceGroupInstances(resp.Items, false)
instanceNames := flattenInstanceGroupInstances(resp.Items, true)
log.Printf("[DEBUG] Received Google Compute Instance Group List Instances: %q", instances)

d.Set("instances", instances)
d.Set("names", instanceNames)
d.SetId(time.Now().UTC().String())

return nil
}

func flattenInstanceGroupInstances(instances []*compute.InstanceWithNamedPorts, extractName bool) []string {
result := make([]string, len(instances), len(instances))
for i, instance := range instances {
if extractName {
result[i] = extractInstanceNameFromURL(instance.Instance)
} else {
result[i] = instance.Instance
}
}
sort.Strings(result)
return result
}

func extractInstanceNameFromURL(instanceURL string) string {
paths := strings.Split(instanceURL, "/")
return paths[len(paths)-1]
}
120 changes: 120 additions & 0 deletions google/data_source_google_compute_instance_group_instances_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package google

import (
"errors"
"fmt"
"strconv"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccGoogleComputeInstanceGroupInstances_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckGoogleComputeInstanceGroupInstancesConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleComputeInstanceGroupInstances("data.google_compute_instance_group_instances.all"),
),
},
},
})
}

func testAccCheckGoogleComputeInstanceGroupInstances(dataSourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
ds, ok := s.RootModule().Resources[dataSourceName]
if !ok {
return fmt.Errorf("Can't find instance group instances data source: %s", dataSourceName)
}

if ds.Primary.ID == "" {
return fmt.Errorf("%s data source ID not set", dataSourceName)
}

dsAttrs := ds.Primary.Attributes

countInstances, ok := dsAttrs["instances.#"]
if !ok {
return errors.New("can't find 'instances' attribute")
}

nOfInstances, err := strconv.Atoi(countInstances)
if err != nil {
return errors.New("failed to read number of instances")
}

countNames, ok := dsAttrs["names.#"]
if !ok {
return errors.New("can't find 'names' attribute")
}

nOfNames, err := strconv.Atoi(countNames)
if err != nil {
return errors.New("failed to read number of instances")
}

for i := 0; i < nOfInstances; i++ {
idx := "instances." + strconv.Itoa(i)
v, ok := dsAttrs[idx]
if !ok {
return fmt.Errorf("instance list is corrupt (%q not found), this is definitely a bug", idx)
}
if len(v) < 1 {
return fmt.Errorf("Empty instance value (%q), this is definitely a bug", idx)
}
}

for i := 0; i < nOfNames; i++ {
idx := "names." + strconv.Itoa(i)
v, ok := dsAttrs[idx]
if !ok {
return fmt.Errorf("name list is corrupt (%q not found), this is definitely a bug", idx)
}
if len(v) < 1 {
return fmt.Errorf("Empty name value (%q), this is definitely a bug", idx)
}
}

return nil
}
}

var testAccCheckGoogleComputeInstanceGroupInstancesConfig = fmt.Sprintf(`
resource "google_compute_instance" "test" {
name = "tf-test-%s"
machine_type = "n1-standard-1"
zone = "us-central1-a"

disk {
image = "debian-cloud/debian-8"
}

network_interface {
network = "default"

access_config {
// Ephemeral IP
}
}
}

resource "google_compute_instance_group" "test" {
name = "tf-test-%s"
zone = "${google_compute_instance.test.zone}"

instances = [
"${google_compute_instance.test.self_link}",
]
}

data "google_compute_instance_group_instances" "all" {
name = "${google_compute_instance_group.test.name}"
zone = "${google_compute_instance_group.test.zone}"
}
`, acctest.RandString(10), acctest.RandString(10))
13 changes: 7 additions & 6 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,13 @@ func Provider() terraform.ResourceProvider {
},

DataSourcesMap: map[string]*schema.Resource{
"google_compute_network": dataSourceGoogleComputeNetwork(),
"google_compute_subnetwork": dataSourceGoogleComputeSubnetwork(),
"google_compute_zones": dataSourceGoogleComputeZones(),
"google_container_engine_versions": dataSourceGoogleContainerEngineVersions(),
"google_iam_policy": dataSourceGoogleIamPolicy(),
"google_storage_object_signed_url": dataSourceGoogleSignedUrl(),
"google_compute_network": dataSourceGoogleComputeNetwork(),
"google_compute_subnetwork": dataSourceGoogleComputeSubnetwork(),
"google_compute_zones": dataSourceGoogleComputeZones(),
"google_compute_instance_group_instances": dataSourceGoogleComputeInstanceGroupInstances(),
"google_container_engine_versions": dataSourceGoogleContainerEngineVersions(),
"google_iam_policy": dataSourceGoogleIamPolicy(),
"google_storage_object_signed_url": dataSourceGoogleSignedUrl(),
},

ResourcesMap: map[string]*schema.Resource{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
layout: "google"
page_title: "Google: google_compute_instance_group_instances"
sidebar_current: "docs-google-datasource-compute-instance-group-instances"
Copy link
Contributor

Choose a reason for hiding this comment

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

Don't forget to update this file to include your new docs page in the sidebar menu

description: |-
Provides a list of Google Compute Instance Group Instances
---

# google\_compute\_instance\_group\_instances

Get a instances within GCE from instance group name and its zone.

```
data "google_compute_instance_group_instances" "all" {
name = "instance-group-name"
zone = "us-central1-a"
}
```

## Argument Reference

The following arguments are supported:

* `name` - The name of the instance group.

* `zone` - The zone of the instance group.

- - -

* `project` - (Optional) The project in which the resource belongs. If it
is not provided, the provider project is used.

## Attributes Reference

The following attributes are exported:

* `instances` - A list of instance urls in the given instance group

* `names` - A list of instance names in the given instance group