diff --git a/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl b/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl index 3863236b923a..c900e5126db1 100644 --- a/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "google.golang.org/api/googleapi" {{ if eq $.TargetVersionName `ga` }} "google.golang.org/api/compute/v1" @@ -41,13 +40,13 @@ func instanceSchedulingNodeAffinitiesElemSchema() *schema.Resource { } } -func expandAliasIpRanges(ranges []interface{}) []*compute.AliasIpRange { - ipRanges := make([]*compute.AliasIpRange, 0, len(ranges)) +func expandAliasIpRanges(ranges []interface{}) []interface{} { + ipRanges := make([]interface{}, 0, len(ranges)) for _, raw := range ranges { data := raw.(map[string]interface{}) - ipRanges = append(ipRanges, &compute.AliasIpRange{ - IpCidrRange: data["ip_cidr_range"].(string), - SubnetworkRangeName: data["subnetwork_range_name"].(string), + ipRanges = append(ipRanges, map[string]interface{}{ + "ipCidrRange": data["ip_cidr_range"].(string), + "subnetworkRangeName": data["subnetwork_range_name"].(string), }) } return ipRanges @@ -77,19 +76,17 @@ func flattenAliasIpRange(d *schema.ResourceData, ranges []*compute.AliasIpRange, return sorted } -func expandScheduling(v interface{}) (*compute.Scheduling, error) { +func expandScheduling(v interface{}) (map[string]interface{}, error) { if v == nil { - // We can't set default values for lists. - return &compute.Scheduling{ - AutomaticRestart: googleapi.Bool(true), + return map[string]interface{}{ + "automaticRestart": true, }, nil } ls := v.([]interface{}) if len(ls) == 0 { - // We can't set default values for lists - return &compute.Scheduling{ - AutomaticRestart: googleapi.Bool(true), + return map[string]interface{}{ + "automaticRestart": true, }, nil } @@ -98,64 +95,56 @@ func expandScheduling(v interface{}) (*compute.Scheduling, error) { } original := ls[0].(map[string]interface{}) - scheduling := &compute.Scheduling{ - ForceSendFields: make([]string, 0, 4), - } + scheduling := make(map[string]interface{}) if v, ok := original["automatic_restart"]; ok { - scheduling.AutomaticRestart = googleapi.Bool(v.(bool)) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "AutomaticRestart") + scheduling["automaticRestart"] = v.(bool) } if v, ok := original["preemptible"]; ok { - scheduling.Preemptible = v.(bool) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "Preemptible") + scheduling["preemptible"] = v.(bool) } if v, ok := original["on_host_maintenance"]; ok { - scheduling.OnHostMaintenance = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "OnHostMaintenance") + scheduling["onHostMaintenance"] = v.(string) } if v, ok := original["node_affinities"]; ok && v != nil { naSet := v.(*schema.Set).List() - scheduling.NodeAffinities = make([]*compute.SchedulingNodeAffinity, len(ls)) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "NodeAffinities") + nodeAffinities := make([]interface{}, 0, len(naSet)) for _, nodeAffRaw := range naSet { if nodeAffRaw == nil { continue } nodeAff := nodeAffRaw.(map[string]interface{}) - transformed := &compute.SchedulingNodeAffinity{ - Key: nodeAff["key"].(string), - Operator: nodeAff["operator"].(string), - Values: tpgresource.ConvertStringArr(nodeAff["values"].(*schema.Set).List()), + transformed := map[string]interface{}{ + "key": nodeAff["key"].(string), + "operator": nodeAff["operator"].(string), + "values": tpgresource.ConvertStringArr(nodeAff["values"].(*schema.Set).List()), } - scheduling.NodeAffinities = append(scheduling.NodeAffinities, transformed) + nodeAffinities = append(nodeAffinities, transformed) } + scheduling["nodeAffinities"] = nodeAffinities } if v, ok := original["min_node_cpus"]; ok { - scheduling.MinNodeCpus = int64(v.(int)) + scheduling["minNodeCpus"] = int64(v.(int)) } if v, ok := original["provisioning_model"]; ok { - scheduling.ProvisioningModel = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "ProvisioningModel") + scheduling["provisioningModel"] = v.(string) } if v, ok := original["instance_termination_action"]; ok { - scheduling.InstanceTerminationAction = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "InstanceTerminationAction") + scheduling["instanceTerminationAction"] = v.(string) } if v, ok := original["availability_domain"]; ok && v != nil { - scheduling.AvailabilityDomain = int64(v.(int)) + scheduling["availabilityDomain"] = int64(v.(int)) } if v, ok := original["max_run_duration"]; ok { transformedMaxRunDuration, err := expandComputeMaxRunDuration(v) if err != nil { return nil, err } - scheduling.MaxRunDuration = transformedMaxRunDuration - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "MaxRunDuration") + scheduling["maxRunDuration"] = transformedMaxRunDuration } if v, ok := original["on_instance_stop_action"]; ok { @@ -163,23 +152,15 @@ func expandScheduling(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.OnInstanceStopAction = transformedOnInstanceStopAction - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "OnInstanceStopAction") + scheduling["onInstanceStopAction"] = transformedOnInstanceStopAction } {{- if ne $.TargetVersionName "ga" }} if v, ok := original["host_error_timeout_seconds"]; ok { - scheduling.HostErrorTimeoutSeconds = int64(v.(int)) - //host_error_timeout_seconds doesn't get removed correctly due to an API bug on instances.SetScheduling. - //We need to set it to NullFields as a workaround because nil is rounded to 0 - if v == 0 || v == nil { - scheduling.NullFields = append(scheduling.NullFields, "HostErrorTimeoutSeconds") - } else { - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "HostErrorTimeoutSeconds") - } + scheduling["hostErrorTimeoutSeconds"] = int64(v.(int)) } if v, ok := original["maintenance_interval"]; ok { - scheduling.MaintenanceInterval = v.(string) + scheduling["maintenanceInterval"] = v.(string) } if v, ok := original["graceful_shutdown"]; ok { @@ -187,13 +168,11 @@ func expandScheduling(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.GracefulShutdown = transformedGracefulShutdown - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "GracefulShutdown") + scheduling["gracefulShutdown"] = transformedGracefulShutdown } if v, ok := original["skip_guest_os_shutdown"]; ok { - scheduling.SkipGuestOsShutdown = v.(bool) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "SkipGuestOsShutdown") + scheduling["skipGuestOsShutdown"] = v.(bool) } if v, ok := original["preemption_notice_duration"]; ok { @@ -201,8 +180,7 @@ func expandScheduling(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.PreemptionNoticeDuration = transformedPreemptionNoticeDuration - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "PreemptionNoticeDuration") + scheduling["preemptionNoticeDuration"] = transformedPreemptionNoticeDuration } {{- end }} if v, ok := original["local_ssd_recovery_timeout"]; ok { @@ -210,39 +188,39 @@ func expandScheduling(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.LocalSsdRecoveryTimeout = transformedLocalSsdRecoveryTimeout - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "LocalSsdRecoveryTimeout") + scheduling["localSsdRecoveryTimeout"] = transformedLocalSsdRecoveryTimeout } if v, ok := original["termination_time"]; ok { - scheduling.TerminationTime = v.(string) + scheduling["terminationTime"] = v.(string) } return scheduling, nil } -func expandComputeMaxRunDuration(v interface{}) (*compute.Duration, error) { +func expandComputeMaxRunDuration(v interface{}) (map[string]interface{}, error) { l := v.([]interface{}) - duration := compute.Duration{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] original := raw.(map[string]interface{}) + duration := make(map[string]interface{}) + transformedNanos, err := expandComputeMaxRunDurationNanos(original["nanos"]) if err != nil { return nil, err } else if val := reflect.ValueOf(transformedNanos); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Nanos = int64(transformedNanos.(int)) + duration["nanos"] = int64(transformedNanos.(int)) } transformedSeconds, err := expandComputeMaxRunDurationSeconds(original["seconds"]) if err != nil { return nil, err } else if val := reflect.ValueOf(transformedSeconds); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Seconds = int64(transformedSeconds.(int)) + duration["seconds"] = int64(transformedSeconds.(int)) } - return &duration, nil + return duration, nil } func expandComputeMaxRunDurationNanos(v interface{}) (interface{}, error) { @@ -253,47 +231,48 @@ func expandComputeMaxRunDurationSeconds(v interface{}) (interface{}, error) { return v, nil } -func expandComputeOnInstanceStopAction(v interface{}) (*compute.SchedulingOnInstanceStopAction, error){ +func expandComputeOnInstanceStopAction(v interface{}) (map[string]interface{}, error){ l := v.([]interface{}) - onInstanceStopAction := compute.SchedulingOnInstanceStopAction{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] original := raw.(map[string]interface{}) + onInstanceStopAction := make(map[string]interface{}) if d, ok := original["discard_local_ssd"]; ok { - onInstanceStopAction.DiscardLocalSsd = d.(bool) + onInstanceStopAction["discardLocalSsd"] = d.(bool) } else { return nil, nil } - return &onInstanceStopAction, nil + return onInstanceStopAction, nil } -func expandComputeLocalSsdRecoveryTimeout(v interface{}) (*compute.Duration, error) { +func expandComputeLocalSsdRecoveryTimeout(v interface{}) (map[string]interface{}, error) { l := v.([]interface{}) - duration := compute.Duration{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] original := raw.(map[string]interface{}) + duration := make(map[string]interface{}) + transformedNanos, err := expandComputeLocalSsdRecoveryTimeoutNanos(original["nanos"]) if err != nil { return nil, err } else if val := reflect.ValueOf(transformedNanos); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Nanos = int64(transformedNanos.(int)) + duration["nanos"] = int64(transformedNanos.(int)) } transformedSeconds, err := expandComputeLocalSsdRecoveryTimeoutSeconds(original["seconds"]) if err != nil { return nil, err } else if val := reflect.ValueOf(transformedSeconds); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Seconds = int64(transformedSeconds.(int)) + duration["seconds"] = int64(transformedSeconds.(int)) } - return &duration, nil + return duration, nil } func expandComputeLocalSsdRecoveryTimeoutNanos(v interface{}) (interface{}, error) { @@ -305,51 +284,49 @@ func expandComputeLocalSsdRecoveryTimeoutSeconds(v interface{}) (interface{}, er } {{- if ne $.TargetVersionName "ga" }} -func expandGracefulShutdown(v interface{}) (*compute.SchedulingGracefulShutdown, error) { +func expandGracefulShutdown(v interface{}) (map[string]interface{}, error) { l := v.([]interface{}) - gracefulShutdown := compute.SchedulingGracefulShutdown{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] original := raw.(map[string]interface{}) + gracefulShutdown := make(map[string]interface{}) + originalMaxDuration := original["max_duration"].([]interface{}) maxDuration, err := expandGracefulShutdownMaxDuration(originalMaxDuration) if err != nil { return nil, err } if maxDuration != nil { - gracefulShutdown.MaxDuration = maxDuration + gracefulShutdown["maxDuration"] = maxDuration } - gracefulShutdown.Enabled = original["enabled"].(bool) - gracefulShutdown.ForceSendFields = append(gracefulShutdown.ForceSendFields, "Enabled") - return &gracefulShutdown, nil + gracefulShutdown["enabled"] = original["enabled"].(bool) + return gracefulShutdown, nil } -func expandGracefulShutdownMaxDuration(v interface{}) (*compute.Duration, error) { +func expandGracefulShutdownMaxDuration(v interface{}) (map[string]interface{}, error) { l := v.([]interface{}) - duration := compute.Duration{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] + duration := make(map[string]interface{}) maxDurationMap := raw.(map[string]interface{}) transformedNanos := maxDurationMap["nanos"] transformedSeconds := maxDurationMap["seconds"] if val := reflect.ValueOf(transformedNanos); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Nanos = int64(transformedNanos.(int)) + duration["nanos"] = int64(transformedNanos.(int)) } if val := reflect.ValueOf(transformedSeconds); val.IsValid() && !tpgresource.IsEmptyValue(val) { - duration.Seconds = int64(transformedSeconds.(int)) + duration["seconds"] = int64(transformedSeconds.(int)) } - duration.ForceSendFields = append(duration.ForceSendFields, "Seconds") - - return &duration, nil + return duration, nil } {{ end }} @@ -463,24 +440,24 @@ func flattenGracefulShutdownMaxDuration(v *compute.Duration) []interface{} { return []interface{}{transformed} } -func expandComputePreemptionNoticeDuration(v interface{}) (*compute.Duration, error) { +func expandComputePreemptionNoticeDuration(v interface{}) (map[string]interface{}, error) { l := v.([]interface{}) - duration := compute.Duration{} if len(l) == 0 || l[0] == nil { return nil, nil } raw := l[0] original := raw.(map[string]interface{}) + duration := make(map[string]interface{}) if transformedNanos, ok := original["nanos"]; ok && transformedNanos != nil { - duration.Nanos = int64(transformedNanos.(int)) + duration["nanos"] = int64(transformedNanos.(int)) } if transformedSeconds, ok := original["seconds"]; ok && transformedSeconds != nil { - duration.Seconds = int64(transformedSeconds.(int)) + duration["seconds"] = int64(transformedSeconds.(int)) } - return &duration, nil + return duration, nil } func flattenComputePreemptionNoticeDuration(v *compute.Duration) []interface{} { @@ -603,56 +580,58 @@ func flattenNetworkInterfaces(d *schema.ResourceData, config *transport_tpg.Conf return flattened, region, internalIP, externalIP, nil } -func expandAccessConfigs(configs []interface{}) []*compute.AccessConfig { - acs := make([]*compute.AccessConfig, len(configs)) +func expandAccessConfigs(configs []interface{}) []interface{} { + acs := make([]interface{}, len(configs)) for i, raw := range configs { - acs[i] = &compute.AccessConfig{} - acs[i].Type = "ONE_TO_ONE_NAT" + ac := make(map[string]interface{}) + ac["type"] = "ONE_TO_ONE_NAT" if raw != nil { data := raw.(map[string]interface{}) - acs[i].NatIP = data["nat_ip"].(string) - acs[i].NetworkTier = data["network_tier"].(string) + ac["natIP"] = data["nat_ip"].(string) + ac["networkTier"] = data["network_tier"].(string) if ptr, ok := data["public_ptr_domain_name"]; ok && ptr != "" { - acs[i].SetPublicPtr = true - acs[i].PublicPtrDomainName = ptr.(string) + ac["publicPtrDomainName"] = ptr.(string) + ac["setPublicPtr"] = true } } + acs[i] = ac } return acs } -func expandIpv6AccessConfigs(configs []interface{}) []*compute.AccessConfig { - iacs := make([]*compute.AccessConfig, len(configs)) +func expandIpv6AccessConfigs(configs []interface{}) []interface{} { + iacs := make([]interface{}, len(configs)) for i, raw := range configs { - iacs[i] = &compute.AccessConfig{} + iac := make(map[string]interface{}) if raw != nil { data := raw.(map[string]interface{}) - iacs[i].NetworkTier = data["network_tier"].(string) + iac["networkTier"] = data["network_tier"].(string) if ptr, ok := data["public_ptr_domain_name"]; ok && ptr != "" { - iacs[i].PublicPtrDomainName = ptr.(string) + iac["publicPtrDomainName"] = ptr.(string) } if eip, ok := data["external_ipv6"]; ok && eip != "" { - iacs[i].ExternalIpv6 = eip.(string) + iac["externalIpv6"] = eip.(string) } if eipl, ok := data["external_ipv6_prefix_length"]; ok && eipl != "" { if strVal, ok := eipl.(string); ok { if intVal, err := tpgresource.StringToFixed64(strVal); err == nil { - iacs[i].ExternalIpv6PrefixLength = intVal + iac["externalIpv6PrefixLength"] = intVal } } } if name, ok := data["name"]; ok && name != "" { - iacs[i].Name = name.(string) + iac["name"] = name.(string) } - iacs[i].Type = "DIRECT_IPV6" // Currently only type supported + iac["type"] = "DIRECT_IPV6" // Currently only type supported } + iacs[i] = iac } return iacs } -func expandNetworkInterfaces(d tpgresource.TerraformResourceData, config *transport_tpg.Config) ([]*compute.NetworkInterface, error) { +func expandNetworkInterfaces(d tpgresource.TerraformResourceData, config *transport_tpg.Config) ([]interface{}, error) { configs := d.Get("network_interface").([]interface{}) - ifaces := make([]*compute.NetworkInterface, len(configs)) + ifaces := make([]interface{}, len(configs)) for i, raw := range configs { data := raw.(map[string]interface{}) @@ -685,23 +664,23 @@ func expandNetworkInterfaces(d tpgresource.TerraformResourceData, config *transp } {{- end }} - ifaces[i] = &compute.NetworkInterface{ - NetworkIP: data["network_ip"].(string), - Network: nf.RelativeLink(), - NetworkAttachment: networkAttachment, - Vlan: int64(data["vlan"].(int)), - Subnetwork: sf.RelativeLink(), - AccessConfigs: expandAccessConfigs(data["access_config"].([]interface{})), - AliasIpRanges: expandAliasIpRanges(data["alias_ip_range"].([]interface{})), - NicType: data["nic_type"].(string), - StackType: data["stack_type"].(string), - QueueCount: int64(data["queue_count"].(int)), - Ipv6AccessConfigs: expandIpv6AccessConfigs(data["ipv6_access_config"].([]interface{})), - Ipv6Address: data["ipv6_address"].(string), - InternalIpv6PrefixLength: int64(data["internal_ipv6_prefix_length"].(int)), - IgmpQuery: data["igmp_query"].(string), + ifaces[i] = map[string]interface{}{ + "networkIP": data["network_ip"].(string), + "network": nf.RelativeLink(), + "networkAttachment": networkAttachment, + "vlan": int64(data["vlan"].(int)), + "subnetwork": sf.RelativeLink(), + "accessConfigs": expandAccessConfigs(data["access_config"].([]interface{})), + "aliasIpRanges": expandAliasIpRanges(data["alias_ip_range"].([]interface{})), + "nicType": data["nic_type"].(string), + "stackType": data["stack_type"].(string), + "queueCount": int64(data["queue_count"].(int)), + "ipv6AccessConfigs": expandIpv6AccessConfigs(data["ipv6_access_config"].([]interface{})), + "ipv6Address": data["ipv6_address"].(string), + "internalIpv6PrefixLength": int64(data["internal_ipv6_prefix_length"].(int)), + "igmpQuery": data["igmp_query"].(string), {{- if ne $.TargetVersionName "ga" }} - MacAddress: macAddress, + "macAddress": macAddress, {{- end }} } } @@ -719,18 +698,19 @@ func flattenServiceAccounts(serviceAccounts []*compute.ServiceAccount) []map[str return result } -func expandServiceAccounts(configs []interface{}) []*compute.ServiceAccount { - accounts := make([]*compute.ServiceAccount, len(configs)) +func expandServiceAccounts(configs []interface{}) []interface{} { + accounts := make([]interface{}, len(configs)) for i, raw := range configs { data := raw.(map[string]interface{}) - accounts[i] = &compute.ServiceAccount{ - Email: data["email"].(string), - Scopes: tpgresource.CanonicalizeServiceScopes(tpgresource.ConvertStringSet(data["scopes"].(*schema.Set))), + email := data["email"].(string) + if email == "" { + email = "default" } - if accounts[i].Email == "" { - accounts[i].Email = "default" + accounts[i] = map[string]interface{}{ + "email": email, + "scopes": tpgresource.CanonicalizeServiceScopes(tpgresource.ConvertStringSet(data["scopes"].(*schema.Set))), } } return accounts @@ -747,46 +727,45 @@ func flattenGuestAccelerators(accelerators []*compute.AcceleratorConfig) []map[s return acceleratorsSchema } -func resourceInstanceTags(d tpgresource.TerraformResourceData) *compute.Tags { +func resourceInstanceTags(d tpgresource.TerraformResourceData) map[string]interface{} { // Calculate the tags - var tags *compute.Tags + var tags map[string]interface{} if v := d.Get("tags"); v != nil { vs := v.(*schema.Set) - tags = new(compute.Tags) - tags.Items = make([]string, vs.Len()) + tags = make(map[string]interface{}) + items := make([]string, vs.Len()) for i, v := range vs.List() { - tags.Items[i] = v.(string) + items[i] = v.(string) } - - tags.Fingerprint = d.Get("tags_fingerprint").(string) + tags["items"] = items + tags["fingerprint"] = d.Get("tags_fingerprint").(string) } return tags } -func expandShieldedVmConfigs(d tpgresource.TerraformResourceData) *compute.ShieldedInstanceConfig { +func expandShieldedVmConfigs(d tpgresource.TerraformResourceData) map[string]interface{} { if _, ok := d.GetOk("shielded_instance_config"); !ok { return nil } prefix := "shielded_instance_config.0" - return &compute.ShieldedInstanceConfig{ - EnableSecureBoot: d.Get(prefix + ".enable_secure_boot").(bool), - EnableVtpm: d.Get(prefix + ".enable_vtpm").(bool), - EnableIntegrityMonitoring: d.Get(prefix + ".enable_integrity_monitoring").(bool), - ForceSendFields: []string{"EnableSecureBoot", "EnableVtpm", "EnableIntegrityMonitoring"}, + return map[string]interface{}{ + "enableSecureBoot": d.Get(prefix + ".enable_secure_boot").(bool), + "enableVtpm": d.Get(prefix + ".enable_vtpm").(bool), + "enableIntegrityMonitoring": d.Get(prefix + ".enable_integrity_monitoring").(bool), } } -func expandConfidentialInstanceConfig(d tpgresource.TerraformResourceData) *compute.ConfidentialInstanceConfig { +func expandConfidentialInstanceConfig(d tpgresource.TerraformResourceData) map[string]interface{} { if _, ok := d.GetOk("confidential_instance_config"); !ok { return nil } prefix := "confidential_instance_config.0" - return &compute.ConfidentialInstanceConfig{ - EnableConfidentialCompute: d.Get(prefix + ".enable_confidential_compute").(bool), - ConfidentialInstanceType: d.Get(prefix + ".confidential_instance_type").(string), + return map[string]interface{}{ + "enableConfidentialCompute": d.Get(prefix + ".enable_confidential_compute").(bool), + "confidentialInstanceType": d.Get(prefix + ".confidential_instance_type").(string), } } @@ -801,19 +780,19 @@ func flattenConfidentialInstanceConfig(ConfidentialInstanceConfig *compute.Confi {{"}}"}} } -func expandAdvancedMachineFeatures(d tpgresource.TerraformResourceData) *compute.AdvancedMachineFeatures { +func expandAdvancedMachineFeatures(d tpgresource.TerraformResourceData) map[string]interface{} { if _, ok := d.GetOk("advanced_machine_features"); !ok { return nil } prefix := "advanced_machine_features.0" - return &compute.AdvancedMachineFeatures{ - EnableNestedVirtualization: d.Get(prefix + ".enable_nested_virtualization").(bool), - ThreadsPerCore: int64(d.Get(prefix + ".threads_per_core").(int)), - TurboMode: d.Get(prefix + ".turbo_mode").(string), - VisibleCoreCount: int64(d.Get(prefix + ".visible_core_count").(int)), - PerformanceMonitoringUnit: d.Get(prefix + ".performance_monitoring_unit").(string), - EnableUefiNetworking: d.Get(prefix + ".enable_uefi_networking").(bool), + return map[string]interface{}{ + "enableNestedVirtualization": d.Get(prefix + ".enable_nested_virtualization").(bool), + "threadsPerCore": int64(d.Get(prefix + ".threads_per_core").(int)), + "turboMode": d.Get(prefix + ".turbo_mode").(string), + "visibleCoreCount": int64(d.Get(prefix + ".visible_core_count").(int)), + "performanceMonitoringUnit": d.Get(prefix + ".performance_monitoring_unit").(string), + "enableUefiNetworking": d.Get(prefix + ".enable_uefi_networking").(bool), } } @@ -843,13 +822,12 @@ func flattenShieldedVmConfig(shieldedVmConfig *compute.ShieldedInstanceConfig) [ {{"}}"}} } -func expandDisplayDevice(d tpgresource.TerraformResourceData) *compute.DisplayDevice { +func expandDisplayDevice(d tpgresource.TerraformResourceData) map[string]interface{} { if _, ok := d.GetOk("enable_display"); !ok { return nil } - return &compute.DisplayDevice{ - EnableDisplay: d.Get("enable_display").(bool), - ForceSendFields: []string{"EnableDisplay"}, + return map[string]interface{}{ + "enableDisplay": d.Get("enable_display").(bool), } } @@ -1054,7 +1032,7 @@ func hasNodeAffinitiesChanged(oScheduling, newScheduling map[string]interface{}) return false } -func expandReservationAffinity(d tpgresource.TerraformResourceData) (*compute.ReservationAffinity, error) { +func expandReservationAffinity(d tpgresource.TerraformResourceData) (map[string]interface{}, error) { _, ok := d.GetOk("reservation_affinity") if !ok { return nil, nil @@ -1063,10 +1041,8 @@ func expandReservationAffinity(d tpgresource.TerraformResourceData) (*compute.Re prefix := "reservation_affinity.0" reservationAffinityType := d.Get(prefix + ".type").(string) - affinity := compute.ReservationAffinity{ - ConsumeReservationType: reservationAffinityType, - ForceSendFields: []string{"ConsumeReservationType"}, - } + affinity := make(map[string]interface{}) + affinity["consumeReservationType"] = reservationAffinityType _, hasSpecificReservation := d.GetOk(prefix + ".specific_reservation") if (reservationAffinityType == "SPECIFIC_RESERVATION") != hasSpecificReservation { @@ -1075,15 +1051,15 @@ func expandReservationAffinity(d tpgresource.TerraformResourceData) (*compute.Re prefix = prefix + ".specific_reservation.0" if hasSpecificReservation { - affinity.Key = d.Get(prefix + ".key").(string) - affinity.ForceSendFields = append(affinity.ForceSendFields, "Key", "Values") - + affinity["key"] = d.Get(prefix + ".key").(string) + var values []string for _, v := range d.Get(prefix + ".values").([]interface{}) { - affinity.Values = append(affinity.Values, v.(string)) + values = append(values, v.(string)) } + affinity["values"] = values } - return &affinity, nil + return affinity, nil } func flattenReservationAffinity(affinity *compute.ReservationAffinity) []map[string]interface{} { @@ -1105,7 +1081,7 @@ func flattenReservationAffinity(affinity *compute.ReservationAffinity) []map[str return []map[string]interface{}{flattened} } -func expandNetworkPerformanceConfig(d tpgresource.TerraformResourceData, config *transport_tpg.Config) (*compute.NetworkPerformanceConfig, error) { +func expandNetworkPerformanceConfig(d tpgresource.TerraformResourceData, config *transport_tpg.Config) (map[string]interface{}, error) { configs, ok := d.GetOk("network_performance_config") if !ok { return nil, nil @@ -1120,8 +1096,8 @@ func expandNetworkPerformanceConfig(d tpgresource.TerraformResourceData, config return nil, nil } npc := npcSlice[0].(map[string]interface{}) - return &compute.NetworkPerformanceConfig{ - TotalEgressBandwidthTier: npc["total_egress_bandwidth_tier"].(string), + return map[string]interface{}{ + "totalEgressBandwidthTier": npc["total_egress_bandwidth_tier"].(string), }, nil } @@ -1142,13 +1118,13 @@ func flattenComputeInstanceGuestOsFeatures(v interface{}) []interface{} { return result } -func expandComputeInstanceGuestOsFeatures(v interface{}) []*compute.GuestOsFeature { +func expandComputeInstanceGuestOsFeatures(v interface{}) []interface{} { if v == nil { return nil } - var result []*compute.GuestOsFeature + var result []interface{} for _, feature := range v.([]interface{}) { - result = append(result, &compute.GuestOsFeature{Type: feature.(string)}) + result = append(result, map[string]interface{}{"type": feature.(string)}) } return result } @@ -1164,17 +1140,17 @@ func flattenNetworkPerformanceConfig(c *compute.NetworkPerformanceConfig) []map[ } } -func expandComputeInstanceEncryptionKey(d tpgresource.TerraformResourceData) *compute.CustomerEncryptionKey { +func expandComputeInstanceEncryptionKey(d tpgresource.TerraformResourceData) map[string]interface{} { iek, ok := d.GetOk("instance_encryption_key") if !ok { return nil } iekRes := iek.([]interface{})[0].(map[string]interface{}) - return &compute.CustomerEncryptionKey{ - KmsKeyName: iekRes["kms_key_self_link"].(string), - Sha256: iekRes["sha256"].(string), - KmsKeyServiceAccount: iekRes["kms_key_service_account"].(string), + return map[string]interface{}{ + "kmsKeyName": iekRes["kms_key_self_link"].(string), + "sha256": iekRes["sha256"].(string), + "kmsKeyServiceAccount": iekRes["kms_key_service_account"].(string), } } @@ -1191,19 +1167,19 @@ func flattenComputeInstanceEncryptionKey(v *compute.CustomerEncryptionKey) []map } } -func expandComputeInstanceSourceEncryptionKey(d tpgresource.TerraformResourceData, field string) *compute.CustomerEncryptionKey { +func expandComputeInstanceSourceEncryptionKey(d tpgresource.TerraformResourceData, field string) map[string]interface{} { cek, ok := d.GetOk(field) if !ok { return nil } cekRes := cek.([]interface{})[0].(map[string]interface{}) - return &compute.CustomerEncryptionKey{ - RsaEncryptedKey: cekRes["rsa_encrypted_key"].(string), - RawKey: cekRes["raw_key"].(string), - KmsKeyName: cekRes["kms_key_self_link"].(string), - Sha256: cekRes["sha256"].(string), - KmsKeyServiceAccount: cekRes["kms_key_service_account"].(string), + return map[string]interface{}{ + "rsaEncryptedKey": cekRes["rsa_encrypted_key"].(string), + "rawKey": cekRes["raw_key"].(string), + "kmsKeyName": cekRes["kms_key_self_link"].(string), + "sha256": cekRes["sha256"].(string), + "kmsKeyServiceAccount": cekRes["kms_key_service_account"].(string), } } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl index 7f2cce7f1a97..7d983bbc5675 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/base64" + "encoding/json" "errors" "fmt" "log" @@ -1829,40 +1830,57 @@ func expandComputeInstance(project string, d *schema.ResourceData, config *trans } // Create the instance information - return &compute.Instance{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("description").(string), - Disks: disks, - MachineType: machineTypeUrl, - Metadata: metadata, - {{- if ne $.TargetVersionName "ga" }} - PartnerMetadata: PartnerMetadata, - {{- end }} - Name: d.Get("name").(string), - NetworkInterfaces: networkInterfaces, - NetworkPerformanceConfig: networkPerformanceConfig, - Tags: resourceInstanceTags(d), - Params: params, - Labels: tpgresource.ExpandEffectiveLabels(d), - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - GuestAccelerators: accels, - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Scheduling: scheduling, - DeletionProtection: d.Get("deletion_protection").(bool), - Hostname: d.Get("hostname").(string), - ForceSendFields: []string{"CanIpForward", "DeletionProtection"}, - ConfidentialInstanceConfig: expandConfidentialInstanceConfig(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - DisplayDevice: expandDisplayDevice(d), - ResourcePolicies: tpgresource.ConvertStringArr(d.Get("resource_policies").([]interface{})), - ReservationAffinity: reservationAffinity, - KeyRevocationActionType: d.Get("key_revocation_action_type").(string), - InstanceEncryptionKey: expandComputeInstanceEncryptionKey(d), - {{- if ne $.TargetVersionName `ga` }} - EraseWindowsVssSignature: d.Get("erase_windows_vss_signature").(bool), - {{- end }} - }, nil + instanceMap := map[string]interface{}{ + "canIpForward": d.Get("can_ip_forward").(bool), + "description": d.Get("description").(string), + "machineType": machineTypeUrl, + "name": d.Get("name").(string), + "networkInterfaces": networkInterfaces, + "networkPerformanceConfig": networkPerformanceConfig, + "tags": resourceInstanceTags(d), + "labels": tpgresource.ExpandEffectiveLabels(d), + "serviceAccounts": expandServiceAccounts(d.Get("service_account").([]interface{})), + "minCpuPlatform": d.Get("min_cpu_platform").(string), + "scheduling": scheduling, + "deletionProtection": d.Get("deletion_protection").(bool), + "hostname": d.Get("hostname").(string), + "confidentialInstanceConfig": expandConfidentialInstanceConfig(d), + "advancedMachineFeatures": expandAdvancedMachineFeatures(d), + "shieldedInstanceConfig": expandShieldedVmConfigs(d), + "displayDevice": expandDisplayDevice(d), + "reservationAffinity": reservationAffinity, + "keyRevocationActionType": d.Get("key_revocation_action_type").(string), + "instanceEncryptionKey": expandComputeInstanceEncryptionKey(d), + "metadata": metadata, + } + + {{- if ne $.TargetVersionName "ga" }} + if PartnerMetadata != nil { + instanceMap["partnerMetadata"] = PartnerMetadata + } + if eraseVss, ok := d.GetOkExists("erase_windows_vss_signature"); ok { + instanceMap["eraseWindowsVssSignature"] = eraseVss.(bool) + } + {{- end }} + + instanceBytes, err := json.Marshal(instanceMap) + if err != nil { + return nil, err + } + + var instance compute.Instance + if err := json.Unmarshal(instanceBytes, &instance); err != nil { + return nil, err + } + + // Re-assign typed slices/structs that are not handled by map + instance.Disks = disks + instance.GuestAccelerators = accels + instance.Params = params + instance.ResourcePolicies = tpgresource.ConvertStringArr(d.Get("resource_policies").([]interface{})) + instance.ForceSendFields = []string{"CanIpForward", "DeletionProtection"} + + return &instance, nil } var computeInstanceStatus = []string{ @@ -2584,8 +2602,13 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error creating request data to update scheduling: %s", err) } + var typedScheduling *compute.Scheduling + if schedulingBytes, err := json.Marshal(scheduling); err == nil { + json.Unmarshal(schedulingBytes, &typedScheduling) + } + op, err := config.NewComputeClient(userAgent).Instances.SetScheduling( - project, zone, instance.Name, scheduling).Do() + project, zone, instance.Name, typedScheduling).Do() if err != nil { return fmt.Errorf("Error updating scheduling policy: %s", err) } @@ -2603,8 +2626,13 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error getting network interface from config: %s", err) } + var typedNetworkInterfaces []*compute.NetworkInterface + if niBytes, err := json.Marshal(networkInterfaces); err == nil { + json.Unmarshal(niBytes, &typedNetworkInterfaces) + } + // Sanity check - if len(networkInterfaces) != len(instance.NetworkInterfaces) { + if len(typedNetworkInterfaces) != len(instance.NetworkInterfaces) { return fmt.Errorf("Instance had unexpected number of network interfaces: %d", len(instance.NetworkInterfaces)) } @@ -2633,9 +2661,9 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err {{- end }} var updatesToNIWhileStopped []func(inst *compute.Instance) error - for i := 0; i < len(networkInterfaces); i++ { + for i := 0; i < len(typedNetworkInterfaces); i++ { prefix := fmt.Sprintf("network_interface.%d", i) - networkInterface := networkInterfaces[i] + networkInterface := typedNetworkInterfaces[i] instNetworkInterface := instance.NetworkInterfaces[i] networkName := d.Get(prefix + ".name").(string) @@ -3180,7 +3208,12 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if d.HasChange("shielded_instance_config") { shieldedVmConfig := expandShieldedVmConfigs(d) - op, err := config.NewComputeClient(userAgent).Instances.UpdateShieldedInstanceConfig(project, zone, instance.Name, shieldedVmConfig).Do() + var typedShieldedVmConfig *compute.ShieldedInstanceConfig + if svcBytes, err := json.Marshal(shieldedVmConfig); err == nil { + json.Unmarshal(svcBytes, &typedShieldedVmConfig) + } + + op, err := config.NewComputeClient(userAgent).Instances.UpdateShieldedInstanceConfig(project, zone, instance.Name, typedShieldedVmConfig).Do() if err != nil { return fmt.Errorf("Error updating shielded vm config: %s", err) } @@ -3198,8 +3231,13 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error creating request data to update scheduling: %s", err) } + var typedScheduling *compute.Scheduling + if schedulingBytes, err := json.Marshal(scheduling); err == nil { + json.Unmarshal(schedulingBytes, &typedScheduling) + } + op, err := config.NewComputeClient(userAgent).Instances.SetScheduling( - project, zone, instance.Name, scheduling).Do() + project, zone, instance.Name, typedScheduling).Do() if err != nil { return fmt.Errorf("Error updating scheduling policy: %s", err) } @@ -3222,7 +3260,11 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error retrieving instance: %s", err) } - instance.AdvancedMachineFeatures = expandAdvancedMachineFeatures(d) + var typedAdvancedMachineFeatures *compute.AdvancedMachineFeatures + if amfBytes, err := json.Marshal(expandAdvancedMachineFeatures(d)); err == nil { + json.Unmarshal(amfBytes, &typedAdvancedMachineFeatures) + } + instance.AdvancedMachineFeatures = typedAdvancedMachineFeatures op, err := config.NewComputeClient(userAgent).Instances.Update(project, zone, instance.Name, instance).Do() if err != nil { @@ -3640,7 +3682,11 @@ func expandBootDisk(d *schema.ResourceData, config *transport_tpg.Config, projec } if v, ok := d.GetOk("boot_disk.0.guest_os_features"); ok { - disk.GuestOsFeatures = expandComputeInstanceGuestOsFeatures(v) + var typedGuestOsFeatures []*compute.GuestOsFeature + if gofBytes, err := json.Marshal(expandComputeInstanceGuestOsFeatures(v)); err == nil { + json.Unmarshal(gofBytes, &typedGuestOsFeatures) + } + disk.GuestOsFeatures = typedGuestOsFeatures } if v, ok := d.GetOk("boot_disk.0.disk_encryption_key_raw"); ok { @@ -3729,7 +3775,11 @@ func expandBootDisk(d *schema.ResourceData, config *transport_tpg.Config, projec } if _, ok := d.GetOk("boot_disk.0.initialize_params.0.source_image_encryption_key"); ok { - disk.InitializeParams.SourceImageEncryptionKey = expandComputeInstanceSourceEncryptionKey(d, "boot_disk.0.initialize_params.0.source_image_encryption_key") + var typedSourceImageEncryptionKey *compute.CustomerEncryptionKey + if siekBytes, err := json.Marshal(expandComputeInstanceSourceEncryptionKey(d, "boot_disk.0.initialize_params.0.source_image_encryption_key")); err == nil { + json.Unmarshal(siekBytes, &typedSourceImageEncryptionKey) + } + disk.InitializeParams.SourceImageEncryptionKey = typedSourceImageEncryptionKey } if v, ok := d.GetOk("boot_disk.0.initialize_params.0.snapshot"); ok { @@ -3742,7 +3792,11 @@ func expandBootDisk(d *schema.ResourceData, config *transport_tpg.Config, projec } if _, ok := d.GetOk("boot_disk.0.initialize_params.0.source_snapshot_encryption_key"); ok { - disk.InitializeParams.SourceSnapshotEncryptionKey = expandComputeInstanceSourceEncryptionKey(d, "boot_disk.0.initialize_params.0.source_snapshot_encryption_key") + var typedSourceSnapshotEncryptionKey *compute.CustomerEncryptionKey + if ssekBytes, err := json.Marshal(expandComputeInstanceSourceEncryptionKey(d, "boot_disk.0.initialize_params.0.source_snapshot_encryption_key")); err == nil { + json.Unmarshal(ssekBytes, &typedSourceSnapshotEncryptionKey) + } + disk.InitializeParams.SourceSnapshotEncryptionKey = typedSourceSnapshotEncryptionKey } if _, ok := d.GetOk("boot_disk.0.initialize_params.0.labels"); ok { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl index 822539014a5a..515e5cb9be5e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl @@ -8,6 +8,7 @@ import ( "strings" "strconv" "time" + "encoding/json" "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" @@ -1566,7 +1567,11 @@ func buildDisks(d *schema.ResourceData, config *transport_tpg.Config) ([]*comput } if v, ok := d.GetOk(prefix + ".guest_os_features"); ok { - disk.GuestOsFeatures = expandComputeInstanceGuestOsFeatures(v.([]interface{})) + var typedGuestOsFeatures []*compute.GuestOsFeature + if gofBytes, err := json.Marshal(expandComputeInstanceGuestOsFeatures(v.([]interface{}))); err == nil { + json.Unmarshal(gofBytes, &typedGuestOsFeatures) + } + disk.GuestOsFeatures = typedGuestOsFeatures } if v, ok := d.GetOk(prefix + ".architecture"); ok { @@ -1662,33 +1667,56 @@ func resourceComputeInstanceTemplateCreate(d *schema.ResourceData, meta interfac } resourcePolicies := expandInstanceTemplateResourcePolicies(d, "resource_policies") - instanceProperties := &compute.InstanceProperties{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("instance_description").(string), - GuestAccelerators: expandInstanceTemplateGuestAccelerators(d, config), - MachineType: d.Get("machine_type").(string), - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Disks: disks, - Metadata: metadata, - {{- if ne $.TargetVersionName "ga" }} - PartnerMetadata: PartnerMetadata, - {{- end }} - NetworkInterfaces: networks, - NetworkPerformanceConfig: networkPerformanceConfig, - Scheduling: scheduling, - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - Tags: resourceInstanceTags(d), - ConfidentialInstanceConfig: expandConfidentialInstanceConfig(d), - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), -{{- if ne $.TargetVersionName "ga" }} - DisplayDevice: expandDisplayDevice(d), -{{- end }} - ResourcePolicies: resourcePolicies, - ReservationAffinity: reservationAffinity, - KeyRevocationActionType: d.Get("key_revocation_action_type").(string), + instancePropertiesMap := map[string]interface{}{ + "canIpForward": d.Get("can_ip_forward").(bool), + "description": d.Get("instance_description").(string), + "machineType": d.Get("machine_type").(string), + "minCpuPlatform": d.Get("min_cpu_platform").(string), + "metadata": metadata, + "networkInterfaces": networks, + "networkPerformanceConfig": networkPerformanceConfig, + "scheduling": scheduling, + "serviceAccounts": expandServiceAccounts(d.Get("service_account").([]interface{})), + "tags": resourceInstanceTags(d), + "confidentialInstanceConfig": expandConfidentialInstanceConfig(d), + "shieldedInstanceConfig": expandShieldedVmConfigs(d), + "advancedMachineFeatures": expandAdvancedMachineFeatures(d), + "reservationAffinity": reservationAffinity, + "keyRevocationActionType": d.Get("key_revocation_action_type").(string), + } + + {{- if ne $.TargetVersionName "ga" }} + if PartnerMetadata != nil { + instancePropertiesMap["partnerMetadata"] = PartnerMetadata + } + if displayDevice := expandDisplayDevice(d); displayDevice != nil { + instancePropertiesMap["displayDevice"] = displayDevice + } + {{- end }} + + if _, ok := d.GetOk("effective_labels"); ok { + instancePropertiesMap["labels"] = tpgresource.ExpandEffectiveLabels(d) + } + + if _, ok := d.GetOk("resource_manager_tags"); ok { + instancePropertiesMap["resourceManagerTags"] = tpgresource.ExpandStringMap(d, "resource_manager_tags") + } + + ipBytes, err := json.Marshal(instancePropertiesMap) + if err != nil { + return err } + var instanceProperties compute.InstanceProperties + if err := json.Unmarshal(ipBytes, &instanceProperties); err != nil { + return err + } + + // Re-assign typed slices/structs + instanceProperties.GuestAccelerators = expandInstanceTemplateGuestAccelerators(d, config) + instanceProperties.Disks = disks + instanceProperties.ResourcePolicies = resourcePolicies + if _, ok := d.GetOk("effective_labels"); ok { instanceProperties.Labels = tpgresource.ExpandEffectiveLabels(d) } @@ -1712,7 +1740,7 @@ func resourceComputeInstanceTemplateCreate(d *schema.ResourceData, meta interfac } instanceTemplate := &compute.InstanceTemplate{ Description: d.Get("description").(string), - Properties: instanceProperties, + Properties: &instanceProperties, Name: itName, } @@ -2257,11 +2285,16 @@ func expandResourceComputeInstanceTemplateScheduling(d *schema.ResourceData, met return nil, err } + var typedScheduling *compute.Scheduling + if schedBytes, err := json.Marshal(expanded); err == nil { + json.Unmarshal(schedBytes, &typedScheduling) + } + // Make sure we have an appropriate value for OnHostMaintenance if Preemptible - if expanded.Preemptible && expanded.OnHostMaintenance == "" { - expanded.OnHostMaintenance = "TERMINATE" + if typedScheduling.Preemptible && typedScheduling.OnHostMaintenance == "" { + typedScheduling.OnHostMaintenance = "TERMINATE" } - return expanded, nil + return typedScheduling, nil } func resourceComputeInstanceTemplateImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl index 7238a5c3126f..620156fedbd6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl @@ -1332,33 +1332,56 @@ func resourceComputeRegionInstanceTemplateCreate(d *schema.ResourceData, meta in } resourcePolicies := expandInstanceTemplateResourcePolicies(d, "resource_policies") - instanceProperties := &compute.InstanceProperties{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("instance_description").(string), - GuestAccelerators: expandInstanceTemplateGuestAccelerators(d, config), - MachineType: d.Get("machine_type").(string), - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Disks: disks, - Metadata: metadata, - {{- if ne $.TargetVersionName "ga" }} - PartnerMetadata: PartnerMetadata, - {{- end }} - NetworkInterfaces: networks, - NetworkPerformanceConfig: networkPerformanceConfig, - Scheduling: scheduling, - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - Tags: resourceInstanceTags(d), - ConfidentialInstanceConfig: expandConfidentialInstanceConfig(d), - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), -{{- if ne $.TargetVersionName "ga" }} - DisplayDevice: expandDisplayDevice(d), -{{- end }} - ResourcePolicies: resourcePolicies, - ReservationAffinity: reservationAffinity, - KeyRevocationActionType: d.Get("key_revocation_action_type").(string), + instancePropertiesMap := map[string]interface{}{ + "canIpForward": d.Get("can_ip_forward").(bool), + "description": d.Get("instance_description").(string), + "machineType": d.Get("machine_type").(string), + "minCpuPlatform": d.Get("min_cpu_platform").(string), + "metadata": metadata, + "networkInterfaces": networks, + "networkPerformanceConfig": networkPerformanceConfig, + "scheduling": scheduling, + "serviceAccounts": expandServiceAccounts(d.Get("service_account").([]interface{})), + "tags": resourceInstanceTags(d), + "confidentialInstanceConfig": expandConfidentialInstanceConfig(d), + "shieldedInstanceConfig": expandShieldedVmConfigs(d), + "advancedMachineFeatures": expandAdvancedMachineFeatures(d), + "reservationAffinity": reservationAffinity, + "keyRevocationActionType": d.Get("key_revocation_action_type").(string), + } + + {{- if ne $.TargetVersionName "ga" }} + if PartnerMetadata != nil { + instancePropertiesMap["partnerMetadata"] = PartnerMetadata + } + if displayDevice := expandDisplayDevice(d); displayDevice != nil { + instancePropertiesMap["displayDevice"] = displayDevice + } + {{- end }} + + if _, ok := d.GetOk("effective_labels"); ok { + instancePropertiesMap["labels"] = tpgresource.ExpandEffectiveLabels(d) + } + + if _, ok := d.GetOk("resource_manager_tags"); ok { + instancePropertiesMap["resourceManagerTags"] = tpgresource.ExpandStringMap(d, "resource_manager_tags") + } + + ipBytes, err := json.Marshal(instancePropertiesMap) + if err != nil { + return err } + var instanceProperties compute.InstanceProperties + if err := json.Unmarshal(ipBytes, &instanceProperties); err != nil { + return err + } + + // Re-assign typed slices/structs + instanceProperties.GuestAccelerators = expandInstanceTemplateGuestAccelerators(d, config) + instanceProperties.Disks = disks + instanceProperties.ResourcePolicies = resourcePolicies + if _, ok := d.GetOk("effective_labels"); ok { instanceProperties.Labels = tpgresource.ExpandEffectiveLabels(d) } diff --git a/mmv1/third_party/tgc/services/compute/compute_instance.go.tmpl b/mmv1/third_party/tgc/services/compute/compute_instance.go.tmpl index 176025da6ac4..6986e27dcbac 100644 --- a/mmv1/third_party/tgc/services/compute/compute_instance.go.tmpl +++ b/mmv1/third_party/tgc/services/compute/compute_instance.go.tmpl @@ -9,6 +9,7 @@ package compute import ( + "encoding/json" "errors" "fmt" "strings" @@ -145,28 +146,42 @@ func expandComputeInstance(project string, d tpgresource.TerraformResourceData, } // Create the instance information - return &compute.Instance{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("description").(string), - Disks: disks, - MachineType: machineTypeUrl, - Metadata: metadata, - Name: d.Get("name").(string), - Zone: d.Get("zone").(string), - NetworkInterfaces: networkInterfaces, - Tags: resourceInstanceTags(d), - Labels: tpgresource.ExpandLabels(d), - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - GuestAccelerators: accels, - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Scheduling: scheduling, - DeletionProtection: d.Get("deletion_protection").(bool), - Hostname: d.Get("hostname").(string), - ForceSendFields: []string{"CanIpForward", "DeletionProtection"}, - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - DisplayDevice: expandDisplayDevice(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), - }, nil + instanceMap := map[string]interface{}{ + "canIpForward": d.Get("can_ip_forward").(bool), + "description": d.Get("description").(string), + "machineType": machineTypeUrl, + "name": d.Get("name").(string), + "zone": d.Get("zone").(string), + "networkInterfaces": networkInterfaces, + "tags": resourceInstanceTags(d), + "labels": tpgresource.ExpandLabels(d), + "serviceAccounts": expandServiceAccounts(d.Get("service_account").([]interface{})), + "minCpuPlatform": d.Get("min_cpu_platform").(string), + "scheduling": scheduling, + "deletionProtection": d.Get("deletion_protection").(bool), + "hostname": d.Get("hostname").(string), + "shieldedInstanceConfig": expandShieldedVmConfigs(d), + "displayDevice": expandDisplayDevice(d), + "advancedMachineFeatures": expandAdvancedMachineFeatures(d), + "metadata": metadata, + } + + instanceBytes, err := json.Marshal(instanceMap) + if err != nil { + return nil, err + } + + var instance compute.Instance + if err := json.Unmarshal(instanceBytes, &instance); err != nil { + return nil, err + } + + // Re-assign typed slices/structs that are not handled by map + instance.Disks = disks + instance.GuestAccelerators = accels + instance.ForceSendFields = []string{"CanIpForward", "DeletionProtection"} + + return &instance, nil } func expandAttachedDisk(diskConfig map[string]interface{}, d tpgresource.TerraformResourceData, meta interface{}) (*compute.AttachedDisk, error) { diff --git a/mmv1/third_party/tgc_next/pkg/services/compute/compute_instance_tfplan2cai.go b/mmv1/third_party/tgc_next/pkg/services/compute/compute_instance_tfplan2cai.go index bc5ee40e2e56..b2c54bb76d94 100644 --- a/mmv1/third_party/tgc_next/pkg/services/compute/compute_instance_tfplan2cai.go +++ b/mmv1/third_party/tgc_next/pkg/services/compute/compute_instance_tfplan2cai.go @@ -1,6 +1,7 @@ package compute import ( + "encoding/json" "errors" "fmt" "strings" @@ -153,34 +154,48 @@ func expandComputeInstance(project string, d tpgresource.TerraformResourceData, } // Create the instance information - return &compute.Instance{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("description").(string), - Disks: disks, - MachineType: machineTypeUrl, - Metadata: metadata, - Name: d.Get("name").(string), - Zone: d.Get("zone").(string), - NetworkInterfaces: networkInterfaces, - NetworkPerformanceConfig: networkPerformanceConfig, - Tags: resourceInstanceTags(d), - Params: params, - Labels: tpgresource.ExpandLabels(d), - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - GuestAccelerators: accels, - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Scheduling: scheduling, - DeletionProtection: d.Get("deletion_protection").(bool), - Hostname: d.Get("hostname").(string), - ConfidentialInstanceConfig: expandConfidentialInstanceConfig(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - DisplayDevice: expandDisplayDevice(d), - ResourcePolicies: tpgresource.ConvertStringArr(d.Get("resource_policies").([]interface{})), - ReservationAffinity: reservationAffinity, - KeyRevocationActionType: d.Get("key_revocation_action_type").(string), - InstanceEncryptionKey: expandComputeInstanceEncryptionKey(d), - }, nil + instanceMap := map[string]interface{}{ + "canIpForward": d.Get("can_ip_forward").(bool), + "description": d.Get("description").(string), + "machineType": machineTypeUrl, + "name": d.Get("name").(string), + "zone": d.Get("zone").(string), + "networkInterfaces": networkInterfaces, + "networkPerformanceConfig": networkPerformanceConfig, + "tags": resourceInstanceTags(d), + "labels": tpgresource.ExpandLabels(d), + "serviceAccounts": expandServiceAccounts(d.Get("service_account").([]interface{})), + "minCpuPlatform": d.Get("min_cpu_platform").(string), + "scheduling": scheduling, + "deletionProtection": d.Get("deletion_protection").(bool), + "hostname": d.Get("hostname").(string), + "confidentialInstanceConfig": expandConfidentialInstanceConfig(d), + "advancedMachineFeatures": expandAdvancedMachineFeatures(d), + "shieldedInstanceConfig": expandShieldedVmConfigs(d), + "displayDevice": expandDisplayDevice(d), + "reservationAffinity": reservationAffinity, + "keyRevocationActionType": d.Get("key_revocation_action_type").(string), + "instanceEncryptionKey": expandComputeInstanceEncryptionKey(d), + "metadata": metadata, + } + + instanceBytes, err := json.Marshal(instanceMap) + if err != nil { + return nil, err + } + + var instance compute.Instance + if err := json.Unmarshal(instanceBytes, &instance); err != nil { + return nil, err + } + + // Re-assign typed slices/structs + instance.Disks = disks + instance.GuestAccelerators = accels + instance.Params = params + instance.ForceSendFields = []string{"CanIpForward", "DeletionProtection"} + + return &instance, nil } func expandAttachedDisk(diskConfig map[string]interface{}, d tpgresource.TerraformResourceData, meta interface{}) (*compute.AttachedDisk, error) { @@ -311,7 +326,11 @@ func expandBootDisk(d tpgresource.TerraformResourceData, config *transport_tpg.C } if v, ok := d.GetOk("boot_disk.0.guest_os_features"); ok { - disk.GuestOsFeatures = expandComputeInstanceGuestOsFeatures(v) + var typedGuestOsFeatures []*compute.GuestOsFeature + if gofBytes, err := json.Marshal(expandComputeInstanceGuestOsFeatures(v)); err == nil { + json.Unmarshal(gofBytes, &typedGuestOsFeatures) + } + disk.GuestOsFeatures = typedGuestOsFeatures } if v, ok := d.GetOk("boot_disk.0.disk_encryption_key_raw"); ok { @@ -501,19 +520,29 @@ func expandNetworkInterfacesTgc(d tpgresource.TerraformResourceData, config *tra network := data["network"].(string) subnetwork := data["subnetwork"].(string) - ifaces[i] = &compute.NetworkInterface{ - NetworkIP: data["network_ip"].(string), - Network: network, - Subnetwork: subnetwork, - AccessConfigs: expandAccessConfigs(data["access_config"].([]interface{})), - AliasIpRanges: expandAliasIpRanges(data["alias_ip_range"].([]interface{})), - NicType: data["nic_type"].(string), - StackType: data["stack_type"].(string), - QueueCount: int64(data["queue_count"].(int)), - Ipv6AccessConfigs: expandIpv6AccessConfigs(data["ipv6_access_config"].([]interface{})), - Ipv6Address: data["ipv6_address"].(string), - InternalIpv6PrefixLength: int64(data["internal_ipv6_prefix_length"].(int)), + ifaceMap := map[string]interface{}{ + "networkIP": data["network_ip"].(string), + "network": network, + "subnetwork": subnetwork, + "accessConfigs": expandAccessConfigs(data["access_config"].([]interface{})), + "aliasIpRanges": expandAliasIpRanges(data["alias_ip_range"].([]interface{})), + "nicType": data["nic_type"].(string), + "stackType": data["stack_type"].(string), + "queueCount": int64(data["queue_count"].(int)), + "ipv6AccessConfigs": expandIpv6AccessConfigs(data["ipv6_access_config"].([]interface{})), + "ipv6Address": data["ipv6_address"].(string), + "internalIpv6PrefixLength": int64(data["internal_ipv6_prefix_length"].(int)), + } + + ifaceBytes, err := json.Marshal(ifaceMap) + if err != nil { + return nil, err + } + var iface compute.NetworkInterface + if err := json.Unmarshal(ifaceBytes, &iface); err != nil { + return nil, err } + ifaces[i] = &iface } return ifaces, nil } @@ -539,63 +568,56 @@ func expandSchedulingTgc(v interface{}) (*compute.Scheduling, error) { } original := ls[0].(map[string]interface{}) - scheduling := &compute.Scheduling{ - ForceSendFields: make([]string, 0, 4), - } + schedulingMap := make(map[string]interface{}) if v, ok := original["automatic_restart"]; ok { - scheduling.AutomaticRestart = googleapi.Bool(v.(bool)) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "AutomaticRestart") + schedulingMap["automaticRestart"] = v.(bool) } if v, ok := original["preemptible"]; ok { - scheduling.Preemptible = v.(bool) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "Preemptible") + schedulingMap["preemptible"] = v.(bool) } if v, ok := original["on_host_maintenance"]; ok { - scheduling.OnHostMaintenance = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "OnHostMaintenance") + schedulingMap["onHostMaintenance"] = v.(string) } if v, ok := original["node_affinities"]; ok && v != nil { naSet := v.(*schema.Set).List() - scheduling.NodeAffinities = make([]*compute.SchedulingNodeAffinity, 0) + var nodeAffinities []interface{} for _, nodeAffRaw := range naSet { if nodeAffRaw == nil { continue } nodeAff := nodeAffRaw.(map[string]interface{}) - transformed := &compute.SchedulingNodeAffinity{ - Key: nodeAff["key"].(string), - Operator: nodeAff["operator"].(string), - Values: tpgresource.ConvertStringArr(nodeAff["values"].(*schema.Set).List()), + transformed := map[string]interface{}{ + "key": nodeAff["key"].(string), + "operator": nodeAff["operator"].(string), + "values": tpgresource.ConvertStringArr(nodeAff["values"].(*schema.Set).List()), } - scheduling.NodeAffinities = append(scheduling.NodeAffinities, transformed) + nodeAffinities = append(nodeAffinities, transformed) } + schedulingMap["nodeAffinities"] = nodeAffinities } if v, ok := original["min_node_cpus"]; ok { - scheduling.MinNodeCpus = int64(v.(int)) + schedulingMap["minNodeCpus"] = int64(v.(int)) } if v, ok := original["provisioning_model"]; ok { - scheduling.ProvisioningModel = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "ProvisioningModel") + schedulingMap["provisioningModel"] = v.(string) } if v, ok := original["instance_termination_action"]; ok { - scheduling.InstanceTerminationAction = v.(string) - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "InstanceTerminationAction") + schedulingMap["instanceTerminationAction"] = v.(string) } if v, ok := original["availability_domain"]; ok && v != nil { - scheduling.AvailabilityDomain = int64(v.(int)) + schedulingMap["availabilityDomain"] = int64(v.(int)) } if v, ok := original["max_run_duration"]; ok { transformedMaxRunDuration, err := expandComputeMaxRunDuration(v) if err != nil { return nil, err } - scheduling.MaxRunDuration = transformedMaxRunDuration - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "MaxRunDuration") + schedulingMap["maxRunDuration"] = transformedMaxRunDuration } if v, ok := original["on_instance_stop_action"]; ok { @@ -603,8 +625,7 @@ func expandSchedulingTgc(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.OnInstanceStopAction = transformedOnInstanceStopAction - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "OnInstanceStopAction") + schedulingMap["onInstanceStopAction"] = transformedOnInstanceStopAction } if v, ok := original["local_ssd_recovery_timeout"]; ok { @@ -612,11 +633,21 @@ func expandSchedulingTgc(v interface{}) (*compute.Scheduling, error) { if err != nil { return nil, err } - scheduling.LocalSsdRecoveryTimeout = transformedLocalSsdRecoveryTimeout - scheduling.ForceSendFields = append(scheduling.ForceSendFields, "LocalSsdRecoveryTimeout") + schedulingMap["localSsdRecoveryTimeout"] = transformedLocalSsdRecoveryTimeout } if v, ok := original["termination_time"]; ok { - scheduling.TerminationTime = v.(string) + schedulingMap["terminationTime"] = v.(string) + } + + schedulingBytes, err := json.Marshal(schedulingMap) + if err != nil { + return nil, err + } + var sched compute.Scheduling + if err := json.Unmarshal(schedulingBytes, &sched); err != nil { + return nil, err } + scheduling := &sched + scheduling.ForceSendFields = []string{"AutomaticRestart", "Preemptible"} return scheduling, nil }