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

Support import for google_compute_instance_group #201

Merged
merged 4 commits into from
Jul 20, 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
28 changes: 28 additions & 0 deletions google/import_compute_instance_group_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package google

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"testing"
)

func TestAccComputeInstanceGroup_import(t *testing.T) {
instanceName := fmt.Sprintf("instancegroup-test-%s", acctest.RandString(10))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccComputeInstanceGroup_destroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccComputeInstanceGroup_basic(instanceName),
},
resource.TestStep{
ResourceName: "google_compute_instance_group.basic",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
59 changes: 43 additions & 16 deletions google/resource_compute_instance_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ func resourceComputeInstanceGroup() *schema.Resource {
Read: resourceComputeInstanceGroupRead,
Update: resourceComputeInstanceGroupUpdate,
Delete: resourceComputeInstanceGroupDelete,
Importer: &schema.ResourceImporter{
State: resourceComputeInstanceGroupImportState,
},

SchemaVersion: 1,

Expand Down Expand Up @@ -117,9 +120,12 @@ func resourceComputeInstanceGroupCreate(d *schema.ResourceData, meta interface{}
return err
}

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

// Build the parameter
instanceGroup := &compute.InstanceGroup{
Name: d.Get("name").(string),
Name: name,
}

// Set optional fields
Expand All @@ -137,17 +143,18 @@ func resourceComputeInstanceGroupCreate(d *schema.ResourceData, meta interface{}

log.Printf("[DEBUG] InstanceGroup insert request: %#v", instanceGroup)
op, err := config.clientCompute.InstanceGroups.Insert(
project, d.Get("zone").(string), instanceGroup).Do()
project, zone, instanceGroup).Do()
if err != nil {
return fmt.Errorf("Error creating InstanceGroup: %s", err)
}

// It probably maybe worked, so store the ID now
d.SetId(instanceGroup.Name)
d.SetId(fmt.Sprintf("%s/%s", zone, name))

// Wait for the operation to complete
err = computeOperationWaitZone(config, op, project, d.Get("zone").(string), "Creating InstanceGroup")
err = computeOperationWaitZone(config, op, project, zone, "Creating InstanceGroup")
if err != nil {
d.SetId("")
return err
}

Expand All @@ -163,13 +170,13 @@ func resourceComputeInstanceGroupCreate(d *schema.ResourceData, meta interface{}

log.Printf("[DEBUG] InstanceGroup add instances request: %#v", addInstanceReq)
op, err := config.clientCompute.InstanceGroups.AddInstances(
project, d.Get("zone").(string), d.Id(), addInstanceReq).Do()
project, zone, name, addInstanceReq).Do()
if err != nil {
return fmt.Errorf("Error adding instances to InstanceGroup: %s", err)
}

// Wait for the operation to complete
err = computeOperationWaitZone(config, op, project, d.Get("zone").(string), "Adding instances to InstanceGroup")
err = computeOperationWaitZone(config, op, project, zone, "Adding instances to InstanceGroup")
if err != nil {
return err
}
Expand All @@ -186,17 +193,20 @@ func resourceComputeInstanceGroupRead(d *schema.ResourceData, meta interface{})
return err
}

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

// retrieve instance group
instanceGroup, err := config.clientCompute.InstanceGroups.Get(
project, d.Get("zone").(string), d.Id()).Do()
project, zone, name).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Instance Group %q", d.Get("name").(string)))
return handleNotFoundError(err, d, fmt.Sprintf("Instance Group %q", name))
}

// retrieve instance group members
var memberUrls []string
members, err := config.clientCompute.InstanceGroups.ListInstances(
project, d.Get("zone").(string), d.Id(), &compute.InstanceGroupsListInstancesRequest{
project, zone, name, &compute.InstanceGroupsListInstancesRequest{
InstanceState: "ALL",
}).Do()
if err != nil {
Expand All @@ -216,6 +226,7 @@ func resourceComputeInstanceGroupRead(d *schema.ResourceData, meta interface{})
}

d.Set("named_port", flattenNamedPorts(instanceGroup.NamedPorts))
d.Set("description", instanceGroup.Description)

// Set computed fields
d.Set("network", instanceGroup.Network)
Expand All @@ -232,6 +243,9 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}
return err
}

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

d.Partial(true)

if d.HasChange("instances") {
Expand All @@ -257,7 +271,7 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}

log.Printf("[DEBUG] InstanceGroup remove instances request: %#v", removeReq)
removeOp, err := config.clientCompute.InstanceGroups.RemoveInstances(
project, d.Get("zone").(string), d.Id(), removeReq).Do()
project, zone, name, removeReq).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
log.Printf("[WARN] Instances already removed from InstanceGroup: %s", remove)
Expand All @@ -266,7 +280,7 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}
}
} else {
// Wait for the operation to complete
err = computeOperationWaitZone(config, removeOp, project, d.Get("zone").(string), "Updating InstanceGroup")
err = computeOperationWaitZone(config, removeOp, project, zone, "Updating InstanceGroup")
if err != nil {
return err
}
Expand All @@ -281,13 +295,13 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}

log.Printf("[DEBUG] InstanceGroup adding instances request: %#v", addReq)
addOp, err := config.clientCompute.InstanceGroups.AddInstances(
project, d.Get("zone").(string), d.Id(), addReq).Do()
project, zone, name, addReq).Do()
if err != nil {
return fmt.Errorf("Error adding instances from InstanceGroup: %s", err)
}

// Wait for the operation to complete
err = computeOperationWaitZone(config, addOp, project, d.Get("zone").(string), "Updating InstanceGroup")
err = computeOperationWaitZone(config, addOp, project, zone, "Updating InstanceGroup")
if err != nil {
return err
}
Expand All @@ -305,12 +319,12 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}

log.Printf("[DEBUG] InstanceGroup updating named ports request: %#v", namedPortsReq)
op, err := config.clientCompute.InstanceGroups.SetNamedPorts(
project, d.Get("zone").(string), d.Id(), namedPortsReq).Do()
project, zone, name, namedPortsReq).Do()
if err != nil {
return fmt.Errorf("Error updating named ports for InstanceGroup: %s", err)
}

err = computeOperationWaitZone(config, op, project, d.Get("zone").(string), "Updating InstanceGroup")
err = computeOperationWaitZone(config, op, project, zone, "Updating InstanceGroup")
if err != nil {
return err
}
Expand All @@ -331,7 +345,8 @@ func resourceComputeInstanceGroupDelete(d *schema.ResourceData, meta interface{}
}

zone := d.Get("zone").(string)
op, err := config.clientCompute.InstanceGroups.Delete(project, zone, d.Id()).Do()
name := d.Get("name").(string)
op, err := config.clientCompute.InstanceGroups.Delete(project, zone, name).Do()
if err != nil {
return fmt.Errorf("Error deleting InstanceGroup: %s", err)
}
Expand All @@ -344,3 +359,15 @@ func resourceComputeInstanceGroupDelete(d *schema.ResourceData, meta interface{}
d.SetId("")
return nil
}

func resourceComputeInstanceGroupImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 {
return nil, fmt.Errorf("Invalid compute instance group specifier. Expecting {zone}/{name}")
}

d.Set("zone", parts[0])
d.Set("name", parts[1])

return []*schema.ResourceData{d}, nil
}
14 changes: 5 additions & 9 deletions google/resource_compute_instance_group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func testAccComputeInstanceGroup_destroy(s *terraform.State) error {
continue
}
_, err := config.clientCompute.InstanceGroups.Get(
config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID).Do()
config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do()
if err == nil {
return fmt.Errorf("InstanceGroup still exists")
}
Expand All @@ -147,15 +147,11 @@ func testAccComputeInstanceGroup_exists(n string, instanceGroup *compute.Instanc
config := testAccProvider.Meta().(*Config)

found, err := config.clientCompute.InstanceGroups.Get(
config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID).Do()
config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do()
if err != nil {
return err
}

if found.Name != rs.Primary.ID {
return fmt.Errorf("InstanceGroup not found")
}

*instanceGroup = *found

return nil
Expand All @@ -176,7 +172,7 @@ func testAccComputeInstanceGroup_updated(n string, size int64, instanceGroup *co
config := testAccProvider.Meta().(*Config)

instanceGroup, err := config.clientCompute.InstanceGroups.Get(
config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID).Do()
config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do()
if err != nil {
return err
}
Expand Down Expand Up @@ -205,7 +201,7 @@ func testAccComputeInstanceGroup_named_ports(n string, np map[string]int64, inst
config := testAccProvider.Meta().(*Config)

instanceGroup, err := config.clientCompute.InstanceGroups.Get(
config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID).Do()
config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do()
if err != nil {
return err
}
Expand Down Expand Up @@ -239,7 +235,7 @@ func testAccComputeInstanceGroup_hasCorrectNetwork(nInstanceGroup string, nNetwo
return fmt.Errorf("No ID is set")
}
instanceGroup, err := config.clientCompute.InstanceGroups.Get(
config.Project, rsInstanceGroup.Primary.Attributes["zone"], rsInstanceGroup.Primary.ID).Do()
config.Project, rsInstanceGroup.Primary.Attributes["zone"], rsInstanceGroup.Primary.Attributes["name"]).Do()
if err != nil {
return err
}
Expand Down
8 changes: 8 additions & 0 deletions website/docs/r/compute_instance_group.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,11 @@ exported:
* `self_link` - The URI of the created resource.

* `size` - The number of instances in the group.

## Import

Instance group can be imported using the `zone` and `name`, e.g.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Just wondering if you and @danawillow have talked about what we want to do for region and zone across all importable resources - we've checked against the provider region, or against all the provider region's zones in the past to find objects by Id alone.

I like this approach a lot - it means we don't clutter read with parsing logic by using an import func, we don't need to write migration functions, and it lets users import resources from more than 1 region/1 set of zones inside a single provider. Are we going to use the same approach across all importable resources going forward and do we have a plan to bring it to older ones?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I decided to import using zone/name because it is a valid case to have multiple instance groups with the same name across different zones.

I will sync up with @danawillow to ensure consistency on our approach for all importable resources.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

After talking with @danawillow and Evan, we decided that import method should:

  • Always supports the fully specified resource identifier (implemented in this PR).
  • For convenience, we can add support for partial specification by name only if guessing the other parameters is feasible. The logic for guessing should be in the ImportFunc and not the read method to avoid polluting the read method's logic. If more than one resource match the name (e.g. two instance groups in two different zones), fail with an error message to avoid surprising behavior.
  • We will go ahead and submit this PR as is. I will add support for the convenient import by name only in a separate PR.
  • We should update the import method for all the other resources to support the fully specified resource. Otherwise, in the case where two resources have the same name in two different zones or regions, the user cannot import the resource.

Copy link
Collaborator

Choose a reason for hiding this comment

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

SGTM! 👍

Thanks for taking the time to flesh out a concrete plan for this.


```
$ terraform import google_compute_instance_group.webservers us-central1-a/terraform-webservers
```