From a5c8d01bc81b4d47c4f1e5863535a1e1be6e581c Mon Sep 17 00:00:00 2001 From: The Magician Date: Mon, 5 Feb 2024 13:46:29 -0800 Subject: [PATCH] Add fine grained resource for instance group membership (#9891) (#17188) * Add fine-grained resource * Add InstanceGroupMembership resource * add acceptance tests for the resource * Add message to the resource * Fix trailing spaces * Fix trailing spaces * Add zone to test * Add zone to test * Review fixes - change fields labels, update descriptions and indentation * Undo mistake change * Remove flatten from the encoder * Remove "Region" prefix in the test files and decoder, as it could be replaces with the existingfill_to_relative_path custom_flatten [upstream:40e92edbde12b2fe291c50860dfe2f06684d933d] Signed-off-by: Modular Magician --- .changelog/9891.txt | 3 + google/provider/provider_mmv1_resources.go | 5 +- ...ource_compute_instance_group_membership.go | 400 ++++++++++++++++++ ..._compute_instance_group_membership_test.go | 231 ++++++++++ ...te_instance_group_membership.html.markdown | 146 +++++++ 5 files changed, 783 insertions(+), 2 deletions(-) create mode 100644 .changelog/9891.txt create mode 100644 google/services/compute/resource_compute_instance_group_membership.go create mode 100644 google/services/compute/resource_compute_instance_group_membership_test.go create mode 100644 website/docs/r/compute_instance_group_membership.html.markdown diff --git a/.changelog/9891.txt b/.changelog/9891.txt new file mode 100644 index 00000000000..0f979d5b6e1 --- /dev/null +++ b/.changelog/9891.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_compute_instance_group_membership` +``` \ No newline at end of file diff --git a/google/provider/provider_mmv1_resources.go b/google/provider/provider_mmv1_resources.go index ce4a32e7deb..b48eb4a9bc7 100644 --- a/google/provider/provider_mmv1_resources.go +++ b/google/provider/provider_mmv1_resources.go @@ -385,9 +385,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 376 +// Generated resources: 377 // Generated IAM resources: 225 -// Total generated resources: 601 +// Total generated resources: 602 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -559,6 +559,7 @@ var generatedResources = map[string]*schema.Resource{ "google_compute_instance_iam_binding": tpgiamresource.ResourceIamBinding(compute.ComputeInstanceIamSchema, compute.ComputeInstanceIamUpdaterProducer, compute.ComputeInstanceIdParseFunc), "google_compute_instance_iam_member": tpgiamresource.ResourceIamMember(compute.ComputeInstanceIamSchema, compute.ComputeInstanceIamUpdaterProducer, compute.ComputeInstanceIdParseFunc), "google_compute_instance_iam_policy": tpgiamresource.ResourceIamPolicy(compute.ComputeInstanceIamSchema, compute.ComputeInstanceIamUpdaterProducer, compute.ComputeInstanceIdParseFunc), + "google_compute_instance_group_membership": compute.ResourceComputeInstanceGroupMembership(), "google_compute_instance_group_named_port": compute.ResourceComputeInstanceGroupNamedPort(), "google_compute_interconnect_attachment": compute.ResourceComputeInterconnectAttachment(), "google_compute_managed_ssl_certificate": compute.ResourceComputeManagedSslCertificate(), diff --git a/google/services/compute/resource_compute_instance_group_membership.go b/google/services/compute/resource_compute_instance_group_membership.go new file mode 100644 index 00000000000..08ee89fd60a --- /dev/null +++ b/google/services/compute/resource_compute_instance_group_membership.go @@ -0,0 +1,400 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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 compute + +import ( + "fmt" + "log" + "reflect" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func ResourceComputeInstanceGroupMembership() *schema.Resource { + return &schema.Resource{ + Create: resourceComputeInstanceGroupMembershipCreate, + Read: resourceComputeInstanceGroupMembershipRead, + Delete: resourceComputeInstanceGroupMembershipDelete, + + Importer: &schema.ResourceImporter{ + State: resourceComputeInstanceGroupMembershipImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderProject, + ), + + Schema: map[string]*schema.Schema{ + "instance": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, + Description: `An instance being added to the InstanceGroup`, + }, + "instance_group": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: tpgresource.CompareResourceNames, + Description: `Represents an Instance Group resource name that the instance belongs to.`, + }, + "zone": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, + Description: `A reference to the zone where the instance group resides.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceComputeInstanceGroupMembershipCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + instanceProp, err := expandNestedComputeInstanceGroupMembershipInstance(d.Get("instance"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("instance"); !tpgresource.IsEmptyValue(reflect.ValueOf(instanceProp)) && (ok || !reflect.DeepEqual(v, instanceProp)) { + obj["instance"] = instanceProp + } + + obj, err = resourceComputeInstanceGroupMembershipEncoder(d, meta, obj) + if err != nil { + return err + } + + lockName, err := tpgresource.ReplaceVars(d, config, "instanceGroups/{{project}}/zones/{{zone}}/{{instance_group}}") + if err != nil { + return err + } + transport_tpg.MutexStore.Lock(lockName) + defer transport_tpg.MutexStore.Unlock(lockName) + + url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/addInstances") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new InstanceGroupMembership: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for InstanceGroupMembership: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutCreate), + }) + if err != nil { + return fmt.Errorf("Error creating InstanceGroupMembership: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "{{project}}/{{zone}}/{{instance_group}}/{{instance}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = ComputeOperationWaitTime( + config, res, project, "Creating InstanceGroupMembership", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create InstanceGroupMembership: %s", err) + } + + log.Printf("[DEBUG] Finished creating InstanceGroupMembership %q: %#v", d.Id(), res) + + return resourceComputeInstanceGroupMembershipRead(d, meta) +} + +func resourceComputeInstanceGroupMembershipRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/listInstances") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for InstanceGroupMembership: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeInstanceGroupMembership %q", d.Id())) + } + + res, err = flattenNestedComputeInstanceGroupMembership(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 ComputeInstanceGroupMembership because it couldn't be matched.") + d.SetId("") + return nil + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading InstanceGroupMembership: %s", err) + } + + if err := d.Set("instance", flattenNestedComputeInstanceGroupMembershipInstance(res["instance"], d, config)); err != nil { + return fmt.Errorf("Error reading InstanceGroupMembership: %s", err) + } + + return nil +} + +func resourceComputeInstanceGroupMembershipDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for InstanceGroupMembership: %s", err) + } + billingProject = project + + lockName, err := tpgresource.ReplaceVars(d, config, "instanceGroups/{{project}}/zones/{{zone}}/{{instance_group}}") + if err != nil { + return err + } + transport_tpg.MutexStore.Lock(lockName) + defer transport_tpg.MutexStore.Unlock(lockName) + + url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/removeInstances") + if err != nil { + return err + } + + var obj map[string]interface{} + toDelete := make(map[string]interface{}) + + // Instance + instanceProp := flattenNestedComputeInstanceGroupMembershipInstance(d.Get("instance"), d, config) + + if instanceProp != "" { + toDelete["instance"] = instanceProp + } + + obj = map[string]interface{}{ + "instances": []map[string]interface{}{toDelete}, + } + log.Printf("[DEBUG] Deleting InstanceGroupMembership %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutDelete), + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "InstanceGroupMembership") + } + + err = ComputeOperationWaitTime( + config, res, project, "Deleting InstanceGroupMembership", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting InstanceGroupMembership %q: %#v", d.Id(), res) + return nil +} + +func resourceComputeInstanceGroupMembershipImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + + if err := tpgresource.ParseImportId([]string{ + "projects/(?P[^/]+)/zones/(?P[^/]+)/instanceGroups/(?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 := tpgresource.ReplaceVars(d, config, "{{project}}/{{zone}}/{{instance_group}}/{{instance}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenNestedComputeInstanceGroupMembershipInstance(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + relative, err := tpgresource.GetRelativePath(v.(string)) + if err != nil { + return v + } + return relative +} + +func expandNestedComputeInstanceGroupMembershipInstance(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + f, err := tpgresource.ParseZonalFieldValue("instances", v.(string), "project", "zone", d, config, true) + if err != nil { + return nil, fmt.Errorf("Invalid value for instance: %s", err) + } + return f.RelativeLink(), nil +} + +func resourceComputeInstanceGroupMembershipEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { + // Instance Group is a URL parameter only, so replace self-link/path with resource name only. + if err := d.Set("instance_group", tpgresource.GetResourceNameFromSelfLink(d.Get("instance_group").(string))); err != nil { + return nil, fmt.Errorf("Error setting instance_group: %s", err) + } + + wrappedReq := map[string]interface{}{ + "instances": []interface{}{obj}, + } + return wrappedReq, nil +} + +func flattenNestedComputeInstanceGroupMembership(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + var v interface{} + var ok bool + + v, ok = res["items"] + 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 items. Actual value: %v", v) + } + + _, item, err := resourceComputeInstanceGroupMembershipFindNestedObjectInList(d, meta, v.([]interface{})) + if err != nil { + return nil, err + } + return item, nil +} + +func resourceComputeInstanceGroupMembershipFindNestedObjectInList(d *schema.ResourceData, meta interface{}, items []interface{}) (index int, item map[string]interface{}, err error) { + expectedInstance, err := expandNestedComputeInstanceGroupMembershipInstance(d.Get("instance"), d, meta.(*transport_tpg.Config)) + if err != nil { + return -1, nil, err + } + expectedFlattenedInstance := flattenNestedComputeInstanceGroupMembershipInstance(expectedInstance, d, meta.(*transport_tpg.Config)) + + // Search list for this resource. + for idx, itemRaw := range items { + if itemRaw == nil { + continue + } + item := itemRaw.(map[string]interface{}) + + itemInstance := flattenNestedComputeInstanceGroupMembershipInstance(item["instance"], d, meta.(*transport_tpg.Config)) + // IsEmptyValue check so that if one is nil and the other is "", that's considered a match + if !(tpgresource.IsEmptyValue(reflect.ValueOf(itemInstance)) && tpgresource.IsEmptyValue(reflect.ValueOf(expectedFlattenedInstance))) && !reflect.DeepEqual(itemInstance, expectedFlattenedInstance) { + log.Printf("[DEBUG] Skipping item with instance= %#v, looking for %#v)", itemInstance, expectedFlattenedInstance) + continue + } + log.Printf("[DEBUG] Found item for resource %q: %#v)", d.Id(), item) + return idx, item, nil + } + return -1, nil, nil +} diff --git a/google/services/compute/resource_compute_instance_group_membership_test.go b/google/services/compute/resource_compute_instance_group_membership_test.go new file mode 100644 index 00000000000..3a00ff37407 --- /dev/null +++ b/google/services/compute/resource_compute_instance_group_membership_test.go @@ -0,0 +1,231 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package compute_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccComputeInstanceGroupMembership_instanceGroupMembershipBasic(t *testing.T) { + // Multiple fine-grained resources + acctest.SkipIfVcr(t) + t.Parallel() + + suffix := acctest.RandString(t, 10) + context := map[string]interface{}{ + "random_suffix": suffix, + "zone": envvar.GetTestZoneFromEnv(), + } + + igId := fmt.Sprintf("projects/%s/zones/%s/instanceGroups/instance-group-%s", + envvar.GetTestProjectFromEnv(), envvar.GetTestZoneFromEnv(), context["random_suffix"]) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + // Create one membership resource + Config: testAccComputeInstanceGroupMembership_instanceGroupMembershipBasic(context), + }, + { + ResourceName: "google_compute_instance_group_membership.default", + ImportState: true, + ImportStateVerify: true, + }, + { + // Add two new members + Config: testAccComputeInstanceGroupMembership_instanceGroupMembershipAdditional(context), + }, + { + ResourceName: "google_compute_instance_group_membership.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"instance", "zone", "instance_group"}, + }, + { + ResourceName: "google_compute_instance_group_membership.add1", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"instance", "zone", "instance_group"}, + }, + { + ResourceName: "google_compute_instance_group_membership.add2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"instance", "zone", "instance_group"}, + }, + { + // Remove add1 and add2 membership resources + Config: testAccComputeInstanceGroupMembership_instanceGroupMembershipBasic(context), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceGroupMembershipDestroyed( + t, igId, + testAccComputeInstanceGroupMembershipGetInstanceName("add1-instance", suffix), + testAccComputeInstanceGroupMembershipGetInstanceName("add2-instance", suffix), + ), + ), + }, + { + ResourceName: "google_compute_instance_group_membership.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"instance", "zone", "instance_group"}, + }, + { + // Delete all membership resources + Config: testAccComputeInstanceGroupMembership_noInstanceGroupMembership(context), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceGroupMembershipDestroyed( + t, igId, + testAccComputeInstanceGroupMembershipGetInstanceName("default-instance", suffix)), + ), + }, + }, + }) +} + +func testAccComputeInstanceGroupMembership_instanceGroupMembershipBasic(context map[string]interface{}) string { + return acctest.Nprintf(` + resource "google_compute_instance_group_membership" "default" { + zone = "%{zone}" + instance_group = google_compute_instance_group.default.name + instance = google_compute_instance.default.self_link + } + `, context) + testAccComputeInstanceGroupMembership_noInstanceGroupMembership(context) +} + +func testAccComputeInstanceGroupMembership_instanceGroupMembershipAdditional(context map[string]interface{}) string { + return acctest.Nprintf(` + resource "google_compute_instance_group_membership" "add1" { + instance_group = google_compute_instance_group.default.name + instance = google_compute_instance.add1.self_link + } + + resource "google_compute_instance_group_membership" "add2" { + instance_group = google_compute_instance_group.default.name + instance = google_compute_instance.add2.self_link + } + `, context) + testAccComputeInstanceGroupMembership_instanceGroupMembershipBasic(context) +} + +func testAccComputeInstanceGroupMembership_noInstanceGroupMembership(context map[string]interface{}) string { + return acctest.Nprintf(` + resource "google_compute_network" "default-network" { + name = "default-%{random_suffix}" + } + + resource "google_compute_instance" "default" { + name = "default-instance-%{random_suffix}" + machine_type = "e2-medium" + + boot_disk { + initialize_params { + image = "debian-cloud/debian-11" + } + } + + network_interface { + network = google_compute_network.default-network.name + } + } + + resource "google_compute_instance" "add1" { + name = "add1-instance-%{random_suffix}" + machine_type = "e2-medium" + + boot_disk { + initialize_params { + image = "debian-cloud/debian-11" + } + } + + network_interface { + network = google_compute_network.default-network.name + } + } + + resource "google_compute_instance" "add2" { + name = "add2-instance-%{random_suffix}" + machine_type = "e2-medium" + + boot_disk { + initialize_params { + image = "debian-cloud/debian-11" + } + } + + network_interface { + network = google_compute_network.default-network.name + } + } + + resource "google_compute_instance_group" "default" { + name = "instance-group-%{random_suffix}" + } + `, context) +} + +func testAccCheckComputeInstanceGroupMembershipDestroyed(t *testing.T, instanceGroupId string, instances ...string) resource.TestCheckFunc { + return func(s *terraform.State) error { + foundInstances, err := testAccComputeInstanceGroupMembershipListMembership(t, instanceGroupId) + if err != nil { + return fmt.Errorf("unable to confirm instance group members with instances %+v was destroyed: %v", instances, err) + } + for _, p := range instances { + if _, ok := foundInstances[p]; ok { + return fmt.Errorf("instance group with instance %s still exists", p) + } + } + return nil + } +} + +func testAccComputeInstanceGroupMembershipListMembership(t *testing.T, instanceGroupId string) (map[string]struct{}, error) { + config := acctest.GoogleProviderConfig(t) + + url := fmt.Sprintf("https://www.googleapis.com/compute/v1/%s/listInstances", instanceGroupId) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + RawURL: url, + UserAgent: config.UserAgent, + }) + + if err != nil { + return nil, err + } + + v, ok := res["items"] + if !ok || v == nil { + return nil, nil + } + + items := v.([]interface{}) + instances := make(map[string]struct{}) + for _, item := range items { + instanceWithStatus := item.(map[string]interface{}) + v, ok := instanceWithStatus["instance"] + if !ok || v == nil { + continue + } + instance := v.(string) + instances[fmt.Sprintf("%v", instance)] = struct{}{} + } + return instances, nil +} + +func testAccComputeInstanceGroupMembershipGetInstanceName(instanceName string, suffix string) string { + return fmt.Sprintf("projects/%s/zones/%s/instances/%s-%s", + envvar.GetTestProjectFromEnv(), + envvar.GetTestZoneFromEnv(), + instanceName, + suffix) +} diff --git a/website/docs/r/compute_instance_group_membership.html.markdown b/website/docs/r/compute_instance_group_membership.html.markdown new file mode 100644 index 00000000000..dc4b8c786b6 --- /dev/null +++ b/website/docs/r/compute_instance_group_membership.html.markdown @@ -0,0 +1,146 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# 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. +# +# ---------------------------------------------------------------------------- +subcategory: "Compute Engine" +description: |- + Represents the Instance membership to the Instance Group. +--- + +# google\_compute\_instance\_group\_membership + +Represents the Instance membership to the Instance Group. + +**NOTE** You can use this resource instead of the `instances` field in the +`google_compute_instance_group`, however it's not recommended to use it alongside this field. +It might cause inconsistencies, as they can end up competing over control. + +**NOTE** This resource has been added to avoid a situation, where after +Instance is recreated, it's removed from Instance Group and it's needed to +perform `apply` twice. To avoid situations like this, please use this resource +with the lifecycle `update_triggered_by` method, with the passed Instance's ID. + + +To get more information about InstanceGroupMembership, see: + +* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroups) +* How-to Guides + * [Add instances](https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroups/addInstances) + * [Remove instances](https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroups/removeInstances) + * [List instances](https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroups/listInstances) + +## Example Usage - Instance Group Membership + + +```hcl +resource "google_compute_network" "default-network" { + name = "network" +} + +resource "google_compute_instance" "default-instance" { + name = "instance" + machine_type = "e2-medium" + + boot_disk { + initialize_params { + image = "debian-cloud/debian-11" + } + } + + network_interface { + network = google_compute_network.default-network.name + } +} + +resource "google_compute_instance_group" "default-instance-group" { + name = "instance-group" +} + +resource "google_compute_instance_group_membership" "default-ig-membership" { + instance = google_compute_instance.default-instance.self_link + instance_group = google_compute_instance_group.default-instance-group.name +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `instance` - + (Required) + An instance being added to the InstanceGroup + +* `instance_group` - + (Required) + Represents an Instance Group resource name that the instance belongs to. + + +- - - + + +* `zone` - + (Optional) + A reference to the zone where the instance group resides. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{project}}/{{zone}}/{{instance_group}}/{{instance}}` + + +## Timeouts + +This resource provides the following +[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: + +- `create` - Default is 20 minutes. +- `delete` - Default is 20 minutes. + +## Import + + +InstanceGroupMembership can be imported using any of these accepted formats: + +* `projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/{{instance}}` +* `{{project}}/{{zone}}/{{instance_group}}/{{instance}}` +* `{{zone}}/{{instance_group}}/{{instance}}` +* `{{instance_group}}/{{instance}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import InstanceGroupMembership using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/{{instance}}" + to = google_compute_instance_group_membership.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), InstanceGroupMembership can be imported using one of the formats above. For example: + +``` +$ terraform import google_compute_instance_group_membership.default projects/{{project}}/zones/{{zone}}/instanceGroups/{{instance_group}}/{{instance}} +$ terraform import google_compute_instance_group_membership.default {{project}}/{{zone}}/{{instance_group}}/{{instance}} +$ terraform import google_compute_instance_group_membership.default {{zone}}/{{instance_group}}/{{instance}} +$ terraform import google_compute_instance_group_membership.default {{instance_group}}/{{instance}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).