From 065f50ed586c43a6d0bbe35d3c98ca2d0d841d8b Mon Sep 17 00:00:00 2001 From: Tomas Karasek Date: Wed, 18 Oct 2023 16:25:49 +0200 Subject: [PATCH] Refactor provider code so that we can have a resources im subdirs --- equinix/acceptance/acceptance.go | 83 ++++++++++++ equinix/acceptance/device_helpers.go | 119 ++++++++++++++++++ equinix/acceptance/ssh_key_helpers.go | 37 ++++++ equinix/data_source_ecx_l2_sellerprofile.go | 11 +- equinix/data_source_ecx_l2_sellerprofiles.go | 9 +- equinix/data_source_ecx_port.go | 5 +- equinix/data_source_fabric_cloud_router.go | 0 equinix/data_source_fabric_connection.go | 0 equinix/data_source_fabric_service_profile.go | 0 equinix/data_source_metal_device.go | 11 +- .../data_source_metal_device_bgp_neighbors.go | 3 +- equinix/data_source_metal_devices.go | 5 +- equinix/data_source_metal_facility.go | 5 +- .../data_source_metal_hardware_reservation.go | 3 +- equinix/data_source_metal_ip_block_ranges.go | 5 +- equinix/data_source_metal_metro.go | 3 +- equinix/data_source_metal_operating_system.go | 3 +- equinix/data_source_metal_organization.go | 3 +- equinix/data_source_metal_plans.go | 9 +- .../data_source_metal_precreated_ip_block.go | 3 +- equinix/data_source_metal_project.go | 5 +- .../data_source_metal_reserved_ip_block.go | 3 +- .../data_source_metal_spot_market_price.go | 5 +- .../data_source_metal_spot_market_request.go | 7 +- equinix/data_source_metal_vlan.go | 17 +-- equinix/data_source_metal_vlan_acc_test.go | 3 +- equinix/data_source_network_account.go | 5 +- equinix/data_source_network_device.go | 11 +- .../data_source_network_device_software.go | 7 +- equinix/data_source_network_device_type.go | 7 +- equinix/data_source_network_platform.go | 11 +- equinix/equinix_sweeper_test.go | 22 ++-- equinix/fabric_cloud_router_read_schema.go | 0 equinix/fabric_cloud_router_schema.go | 0 equinix/fabric_connection_read_schema.go | 0 equinix/fabric_connection_schema.go | 0 equinix/fabric_necessary_utilities.go | 49 ++++++++ equinix/fabric_service_profile_read_schema.go | 0 equinix/fabric_service_profile_schema.go | 0 .../fabric_service_profile_search_schema.go | 0 equinix/{ => internal}/config.go | 49 +++++--- equinix/{ => internal}/errors.go | 28 ++--- equinix/internal/fabric_helpers_stub.go | 26 ++++ equinix/{ => internal}/hashcode.go | 4 +- equinix/{ => internal}/helpers_device.go | 56 ++++----- equinix/{ => internal}/helpers_device_test.go | 12 +- equinix/{ => internal}/mutexkv.go | 2 +- equinix/{ => internal}/port_helpers.go | 43 ++++--- equinix/internal/utils.go | 106 ++++++++++++++++ .../data_source.go} | 10 +- .../data_source_test.go} | 18 +-- equinix/metal_project_ssh_key/resource.go | 26 ++++ .../resource_test.go} | 23 ++-- .../resource.go} | 58 ++++----- .../resource_test.go} | 105 ++++++---------- equinix/provider.go | 84 +++++-------- equinix/provider_test.go | 15 +-- equinix/resource_ecx_l2_connection.go | 19 +-- .../resource_ecx_l2_connection_acc_test.go | 17 +-- equinix/resource_ecx_l2_connection_test.go | 3 +- equinix/resource_ecx_l2_serviceprofile.go | 27 ++-- ...resource_ecx_l2_serviceprofile_acc_test.go | 3 +- .../resource_ecx_l2_serviceprofile_test.go | 9 +- equinix/resource_fabric_cloud_router.go | 23 ++-- .../resource_fabric_cloud_router_acc_test.go | 3 +- equinix/resource_fabric_connection.go | 28 +++-- .../resource_fabric_connection_acc_test.go | 3 +- equinix/resource_fabric_port.go | 9 +- equinix/resource_fabric_port_acc_test.go | 0 equinix/resource_fabric_routing_protocol.go | 23 ++-- ...source_fabric_routing_protocol_acc_test.go | 3 +- equinix/resource_fabric_service_profile.go | 25 ++-- ...esource_fabric_service_profile_acc_test.go | 5 +- equinix/resource_metal_bgp_session.go | 21 ++-- equinix/resource_metal_bgp_setup_acc_test.go | 3 +- equinix/resource_metal_connection.go | 45 +++---- equinix/resource_metal_connection_acc_test.go | 3 +- equinix/resource_metal_device.go | 95 +++++++------- equinix/resource_metal_device_acc_test.go | 21 ++-- equinix/resource_metal_device_network_type.go | 17 +-- equinix/resource_metal_gateway.go | 19 +-- equinix/resource_metal_gateway_acc_test.go | 3 +- equinix/resource_metal_ip_attachment.go | 21 ++-- .../resource_metal_ip_attachment_acc_test.go | 3 +- equinix/resource_metal_organization.go | 29 ++--- .../resource_metal_organization_acc_test.go | 5 +- equinix/resource_metal_organization_member.go | 41 +++--- equinix/resource_metal_port.go | 55 ++++---- equinix/resource_metal_port_acc_test.go | 9 +- .../resource_metal_port_vlan_attachment.go | 29 ++--- ...rce_metal_port_vlan_attachment_acc_test.go | 3 +- equinix/resource_metal_project.go | 41 +++--- equinix/resource_metal_project_acc_test.go | 13 +- equinix/resource_metal_project_api_key.go | 23 ++-- ...resource_metal_project_api_key_acc_test.go | 3 +- equinix/resource_metal_project_ssh_key.go | 25 ---- equinix/resource_metal_reserved_ip_block.go | 25 ++-- ...source_metal_reserved_ip_block_acc_test.go | 3 +- equinix/resource_metal_spot_market_request.go | 29 ++--- ...urce_metal_spot_market_request_acc_test.go | 5 +- .../resource_metal_user_api_key_acc_test.go | 2 +- equinix/resource_metal_virtual_circuit.go | 29 ++--- ...resource_metal_virtual_circuit_acc_test.go | 3 +- equinix/resource_metal_vlan.go | 35 +++--- equinix/resource_metal_vlan_acc_test.go | 5 +- equinix/resource_metal_vrf.go | 31 ++--- equinix/resource_metal_vrf_acc_test.go | 5 +- equinix/resource_network_acl_template.go | 17 +-- .../resource_network_acl_template_acc_test.go | 7 +- equinix/resource_network_bgp.go | 13 +- equinix/resource_network_bgp_acc_test.go | 3 +- equinix/resource_network_device.go | 27 ++-- equinix/resource_network_device_acc_test.go | 13 +- equinix/resource_network_device_link.go | 21 ++-- .../resource_network_device_link_acc_test.go | 7 +- equinix/resource_network_device_test.go | 7 +- equinix/resource_network_file.go | 9 +- equinix/resource_network_file_acc_test.go | 3 +- equinix/resource_network_ssh_key.go | 13 +- equinix/resource_network_ssh_key_acc_test.go | 7 +- equinix/resource_network_ssh_user.go | 23 ++-- equinix/resource_network_ssh_user_acc_test.go | 7 +- equinix/resource_network_ssh_user_test.go | 3 +- equinix/utils.go | 75 ----------- 124 files changed, 1349 insertions(+), 939 deletions(-) create mode 100644 equinix/acceptance/acceptance.go create mode 100644 equinix/acceptance/device_helpers.go create mode 100644 equinix/acceptance/ssh_key_helpers.go mode change 100755 => 100644 equinix/data_source_fabric_cloud_router.go mode change 100755 => 100644 equinix/data_source_fabric_connection.go mode change 100755 => 100644 equinix/data_source_fabric_service_profile.go mode change 100755 => 100644 equinix/fabric_cloud_router_read_schema.go mode change 100755 => 100644 equinix/fabric_cloud_router_schema.go mode change 100755 => 100644 equinix/fabric_connection_read_schema.go mode change 100755 => 100644 equinix/fabric_connection_schema.go create mode 100644 equinix/fabric_necessary_utilities.go mode change 100755 => 100644 equinix/fabric_service_profile_read_schema.go mode change 100755 => 100644 equinix/fabric_service_profile_schema.go mode change 100755 => 100644 equinix/fabric_service_profile_search_schema.go rename equinix/{ => internal}/config.go (89%) rename equinix/{ => internal}/errors.go (84%) create mode 100644 equinix/internal/fabric_helpers_stub.go rename equinix/{ => internal}/hashcode.go (89%) rename equinix/{ => internal}/helpers_device.go (81%) rename equinix/{ => internal}/helpers_device_test.go (92%) rename equinix/{ => internal}/mutexkv.go (98%) rename equinix/{ => internal}/port_helpers.go (89%) create mode 100644 equinix/internal/utils.go rename equinix/{data_source_metal_project_ssh_key.go => metal_project_ssh_key/data_source.go} (91%) rename equinix/{data_source_metal_project_ssh_key_acc_test.go => metal_project_ssh_key/data_source_test.go} (88%) create mode 100644 equinix/metal_project_ssh_key/resource.go rename equinix/{resource_metal_project_ssh_key_acc_test.go => metal_project_ssh_key/resource_test.go} (76%) rename equinix/{resource_metal_ssh_key.go => metal_ssh_key/resource.go} (65%) rename equinix/{resource_metal_ssh_key_acc_test.go => metal_ssh_key/resource_test.go} (74%) mode change 100755 => 100644 equinix/resource_fabric_cloud_router.go mode change 100755 => 100644 equinix/resource_fabric_cloud_router_acc_test.go mode change 100755 => 100644 equinix/resource_fabric_connection.go mode change 100755 => 100644 equinix/resource_fabric_connection_acc_test.go mode change 100755 => 100644 equinix/resource_fabric_port.go mode change 100755 => 100644 equinix/resource_fabric_port_acc_test.go mode change 100755 => 100644 equinix/resource_fabric_service_profile.go mode change 100755 => 100644 equinix/resource_fabric_service_profile_acc_test.go delete mode 100644 equinix/resource_metal_project_ssh_key.go delete mode 100644 equinix/utils.go diff --git a/equinix/acceptance/acceptance.go b/equinix/acceptance/acceptance.go new file mode 100644 index 000000000..ff4a3c541 --- /dev/null +++ b/equinix/acceptance/acceptance.go @@ -0,0 +1,83 @@ +package acceptance + +import ( + "fmt" + "os" + "strconv" + "strings" + "testing" + "time" + + "github.com/equinix/terraform-provider-equinix/equinix" + "github.com/equinix/terraform-provider-equinix/equinix/internal" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // duplicated from equinix_sweeoer_test.go + tstResourcePrefix = "tfacc" + missingMetalToken = "To run acceptance tests of Equinix Metal Resources, you must set %s" +) + +var ( + TestAccProvider *schema.Provider + TestAccProviders map[string]*schema.Provider + TestAccProviderFactories map[string]func() (*schema.Provider, error) + TestExternalProviders map[string]resource.ExternalProvider +) + +func init() { + TestAccProvider = equinix.Provider() + TestAccProviders = map[string]*schema.Provider{ + "equinix": TestAccProvider, + } + TestAccProviderFactories = map[string]func() (*schema.Provider, error){ + "equinix": func() (*schema.Provider, error) { + return TestAccProvider, nil + }, + } + TestExternalProviders = map[string]resource.ExternalProvider{ + "random": { + Source: "hashicorp/random", + }, + } +} + +func TestAccPreCheckMetal(t *testing.T) { + if os.Getenv(equinix.MetalAuthTokenEnvVar) == "" { + t.Fatalf(missingMetalToken, equinix.MetalAuthTokenEnvVar) + } +} + +func IsSweepableTestResource(namePrefix string) bool { + return strings.HasPrefix(namePrefix, tstResourcePrefix) +} + +func getFromEnvDefault(varName string, defaultValue string) string { + if v := os.Getenv(varName); v != "" { + return v + } + return defaultValue +} + +func GetConfigForNonStandardMetalTest() (*internal.Config, error) { + endpoint := getFromEnvDefault(equinix.EndpointEnvVar, internal.DefaultBaseURL) + clientTimeout := getFromEnvDefault(equinix.ClientTimeoutEnvVar, strconv.Itoa(internal.DefaultTimeout)) + clientTimeoutInt, err := strconv.Atoi(clientTimeout) + if err != nil { + return nil, fmt.Errorf("cannot convert value of '%s' env variable to int", equinix.ClientTimeoutEnvVar) + } + metalAuthToken := getFromEnvDefault(equinix.MetalAuthTokenEnvVar, "") + + if metalAuthToken == "" { + return nil, fmt.Errorf(missingMetalToken, equinix.MetalAuthTokenEnvVar) + } + + return &internal.Config{ + AuthToken: metalAuthToken, + BaseURL: endpoint, + RequestTimeout: time.Duration(clientTimeoutInt) * time.Second, + }, nil +} diff --git a/equinix/acceptance/device_helpers.go b/equinix/acceptance/device_helpers.go new file mode 100644 index 000000000..43805f207 --- /dev/null +++ b/equinix/acceptance/device_helpers.go @@ -0,0 +1,119 @@ +package acceptance + +import ( + "fmt" + "strings" + "time" +) + +// list of plans and metros and os used as filter criteria to find available hardware to run tests +var ( + Preferable_plans = []string{"x1.small.x86", "t1.small.x86", "c2.medium.x86", "c3.small.x86", "c3.medium.x86", "m3.small.x86"} + Preferable_metros = []string{"ch", "ny", "sv", "ty", "am"} + Preferable_os = []string{"ubuntu_20_04"} +) + +func TestDeviceTerminationTime() string { + return time.Now().UTC().Add(60 * time.Minute).Format(time.RFC3339) +} + +// This function should be used to find available plans in all test where a metal_device resource is needed. +// +// TODO consider adding a datasource for equinix_metal_operating_system and making the local.os conditional +// +// https://github.com/equinix/terraform-provider-equinix/pull/220#discussion_r915418418equinix_metal_operating_system +// https://github.com/equinix/terraform-provider-equinix/discussions/221 +func ConfAccMetalDevice_base(plans, metros, os []string) string { + return fmt.Sprintf(` +data "equinix_metal_plans" "test" { + sort { + attribute = "id" + direction = "asc" + } + + filter { + attribute = "name" + values = [%s] + } + filter { + attribute = "available_in_metros" + values = [%s] + } + filter { + attribute = "deployment_types" + values = ["on_demand", "spot_market"] + } +} + +// Select a metal plan randomly and lock it in +// so that we don't pick a different one for +// every subsequent terraform plan +resource "random_integer" "plan_idx" { + min = 0 + max = length(data.equinix_metal_plans.test.plans) - 1 +} + +resource "terraform_data" "plan" { + input = data.equinix_metal_plans.test.plans[random_integer.plan_idx.result] + + lifecycle { + ignore_changes = ["input"] + } +} + +resource "terraform_data" "facilities" { + input = sort(tolist(setsubtract(terraform_data.plan.output.available_in, ["nrt1", "dfw2", "ewr1", "ams1", "sjc1", "ld7", "sy4", "ny6"]))) + + lifecycle { + ignore_changes = ["input"] + } +} + +// Select a metal facility randomly and lock it in +// so that we don't pick a different one for +// every subsequent terraform plan +resource "random_integer" "facility_idx" { + min = 0 + max = length(local.facilities) - 1 +} + +resource "terraform_data" "facility" { + input = local.facilities[random_integer.facility_idx.result] + + lifecycle { + ignore_changes = ["input"] + } +} + +// Select a metal metro randomly and lock it in +// so that we don't pick a different one for +// every subsequent terraform plan +resource "random_integer" "metro_idx" { + min = 0 + max = length(local.metros) - 1 +} + +resource "terraform_data" "metro" { + input = local.metros[random_integer.metro_idx.result] + + lifecycle { + ignore_changes = ["input"] + } +} + +locals { + // Select a random plan + plan = terraform_data.plan.output.slug + + // Select a random facility from the facilities in which the selected plan is available, excluding decommed facilities + facilities = terraform_data.facilities.output + facility = terraform_data.facility.output + + // Select a random metro from the metros in which the selected plan is available + metros = sort(tolist(terraform_data.plan.output.available_in_metros)) + metro = terraform_data.metro.output + + os = [%s][0] +} +`, fmt.Sprintf("\"%s\"", strings.Join(plans[:], `","`)), fmt.Sprintf("\"%s\"", strings.Join(metros[:], `","`)), fmt.Sprintf("\"%s\"", strings.Join(os[:], `","`))) +} diff --git a/equinix/acceptance/ssh_key_helpers.go b/equinix/acceptance/ssh_key_helpers.go new file mode 100644 index 000000000..4eb71cf98 --- /dev/null +++ b/equinix/acceptance/ssh_key_helpers.go @@ -0,0 +1,37 @@ +package acceptance + +import ( + "fmt" + + "github.com/equinix/terraform-provider-equinix/equinix/internal" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/packethost/packngo" +) + + +func TestAccCheckMetalSSHKeyExists(n string, key *packngo.SSHKey) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + client := TestAccProvider.Meta().(*internal.Config).Metal + + foundKey, _, err := client.SSHKeys.Get(rs.Primary.ID, nil) + if err != nil { + return err + } + if foundKey.ID != rs.Primary.ID { + return fmt.Errorf("SSh Key not found: %v - %v", rs.Primary.ID, foundKey) + } + + *key = *foundKey + + return nil + } +} diff --git a/equinix/data_source_ecx_l2_sellerprofile.go b/equinix/data_source_ecx_l2_sellerprofile.go index 59b9958a2..bbc9ab50e 100644 --- a/equinix/data_source_ecx_l2_sellerprofile.go +++ b/equinix/data_source_ecx_l2_sellerprofile.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "bytes" "context" "fmt" @@ -229,12 +230,12 @@ func createECXL2SellerProfileSchema() map[string]*schema.Schema { } func dataSourceECXL2SellerProfileRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics name := d.Get(ecxL2SellerProfileSchemaNames["Name"]).(string) orgName := d.Get(ecxL2SellerProfileSchemaNames["OrganizationName"]).(string) orgGlobalName := d.Get(ecxL2SellerProfileSchemaNames["GlobalOrganization"]).(string) - profiles, err := conf.ecx.GetL2SellerProfiles() + profiles, err := conf.Ecx.GetL2SellerProfiles() if err != nil { return diag.FromErr(err) } @@ -346,19 +347,19 @@ func ecxL2ServiceProfileSpeedBandHash(v interface{}) int { m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%d-", m[ecxL2ServiceProfileSpeedBandSchemaNames["Speed"]].(int))) buf.WriteString(fmt.Sprintf("%s-", m[ecxL2ServiceProfileSpeedBandSchemaNames["SpeedUnit"]].(string))) - return hashcodeString(buf.String()) + return internal.HashcodeString(buf.String()) } func ecxL2SellerProfileMetroHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m[ecxL2SellerProfileMetrosSchemaNames["Code"]].(string))) - return hashcodeString(buf.String()) + return internal.HashcodeString(buf.String()) } func ecxL2SellerProfileAdditionalInfoHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m[ecxL2SellerProfileAdditionalInfosSchemaNames["Name"]].(string))) - return hashcodeString(buf.String()) + return internal.HashcodeString(buf.String()) } diff --git a/equinix/data_source_ecx_l2_sellerprofiles.go b/equinix/data_source_ecx_l2_sellerprofiles.go index 5a48a10d0..589125583 100644 --- a/equinix/data_source_ecx_l2_sellerprofiles.go +++ b/equinix/data_source_ecx_l2_sellerprofiles.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "regexp" @@ -87,16 +88,16 @@ func dataSourceECXL2SellerProfiles() *schema.Resource { } func dataSourceECXL2SellerProfilesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics - profiles, err := conf.ecx.GetL2SellerProfiles() + profiles, err := conf.Ecx.GetL2SellerProfiles() if err != nil { return diag.FromErr(err) } var filteredProfiles []ecx.L2ServiceProfile nameRegex := d.Get(ecxL2SellerProfilesSchemaNames["NameRegex"]).(string) - metros := expandSetToStringList(d.Get(ecxL2SellerProfilesSchemaNames["Metros"]).(*schema.Set)) - speedBands := expandSetToStringList(d.Get(ecxL2SellerProfilesSchemaNames["SpeedBands"]).(*schema.Set)) + metros := internal.ExpandSetToStringList(d.Get(ecxL2SellerProfilesSchemaNames["Metros"]).(*schema.Set)) + speedBands := internal.ExpandSetToStringList(d.Get(ecxL2SellerProfilesSchemaNames["SpeedBands"]).(*schema.Set)) orgName := d.Get(ecxL2SellerProfilesSchemaNames["OrganizationName"]).(string) globalOrgName := d.Get(ecxL2SellerProfilesSchemaNames["GlobalOrganization"]).(string) for _, profile := range profiles { diff --git a/equinix/data_source_ecx_port.go b/equinix/data_source_ecx_port.go index eefbb9cdc..0d8ba400e 100644 --- a/equinix/data_source_ecx_port.go +++ b/equinix/data_source_ecx_port.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/equinix/terraform-provider-equinix/equinix/internal" ) var ecxPortSchemaNames = map[string]string{ @@ -97,10 +98,10 @@ func dataSourceECXPort() *schema.Resource { } func dataSourceECXPortRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics name := d.Get(ecxPortSchemaNames["Name"]).(string) - ports, err := conf.ecx.GetUserPorts() + ports, err := conf.Ecx.GetUserPorts() if err != nil { return diag.FromErr(err) } diff --git a/equinix/data_source_fabric_cloud_router.go b/equinix/data_source_fabric_cloud_router.go old mode 100755 new mode 100644 diff --git a/equinix/data_source_fabric_connection.go b/equinix/data_source_fabric_connection.go old mode 100755 new mode 100644 diff --git a/equinix/data_source_fabric_service_profile.go b/equinix/data_source_fabric_service_profile.go old mode 100755 new mode 100644 diff --git a/equinix/data_source_metal_device.go b/equinix/data_source_metal_device.go index 22b619d46..bf4f62aef 100644 --- a/equinix/data_source_metal_device.go +++ b/equinix/data_source_metal_device.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "encoding/json" "fmt" @@ -208,7 +209,7 @@ func dataSourceMetalDevice() *schema.Resource { } func dataSourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metalgo + client := meta.(*internal.Config).Metalgo hostnameRaw, hostnameOK := d.GetOk("hostname") projectIdRaw, projectIdOK := d.GetOk("project_id") @@ -276,7 +277,7 @@ func dataSourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta if device.HardwareReservation != nil { d.Set("hardware_reservation_id", device.HardwareReservation.GetId()) } - networkType, err := getNetworkType(device) + networkType, err := internal.GetNetworkType(device) if err != nil { return fmt.Errorf("[ERR] Error computing network type for device (%s): %s", d.Id(), err) } @@ -290,14 +291,14 @@ func dataSourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta keyIDs = append(keyIDs, path.Base(k.Href)) } d.Set("ssh_key_ids", keyIDs) - networkInfo := getNetworkInfo(device.IpAddresses) + networkInfo := internal.GetNetworkInfo(device.IpAddresses) sort.SliceStable(networkInfo.Networks, func(i, j int) bool { famI := networkInfo.Networks[i]["family"].(int32) famJ := networkInfo.Networks[j]["family"].(int32) pubI := networkInfo.Networks[i]["public"].(bool) pubJ := networkInfo.Networks[j]["public"].(bool) - return getNetworkRank(int(famI), pubI) < getNetworkRank(int(famJ), pubJ) + return internal.GetNetworkRank(int(famI), pubI) < internal.GetNetworkRank(int(famJ), pubJ) }) d.Set("network", networkInfo.Networks) @@ -305,7 +306,7 @@ func dataSourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta d.Set("access_private_ipv4", networkInfo.PrivateIPv4) d.Set("access_public_ipv6", networkInfo.PublicIPv6) - ports := getPorts(device.NetworkPorts) + ports := internal.GetPorts(device.NetworkPorts) d.Set("ports", ports) d.SetId(device.GetId()) diff --git a/equinix/data_source_metal_device_bgp_neighbors.go b/equinix/data_source_metal_device_bgp_neighbors.go index ed5e6bd39..ba59a6e5d 100644 --- a/equinix/data_source_metal_device_bgp_neighbors.go +++ b/equinix/data_source_metal_device_bgp_neighbors.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" metalv1 "github.com/equinix-labs/metal-go/metal/v1" @@ -106,7 +107,7 @@ func dataSourceMetalDeviceBGPNeighbors() *schema.Resource { } func dataSourceMetalDeviceBGPNeighborsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).metalgo + client := meta.(*internal.Config).Metalgo deviceID := d.Get("device_id").(string) bgpNeighborsRaw, _, err := client.DevicesApi.GetBgpNeighborData(ctx, deviceID).Execute() diff --git a/equinix/data_source_metal_devices.go b/equinix/data_source_metal_devices.go index 3904af6ec..9db0975b7 100644 --- a/equinix/data_source_metal_devices.go +++ b/equinix/data_source_metal_devices.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" @@ -50,7 +51,7 @@ func dataSourceMetalDevices() *schema.Resource { } func getDevices(meta interface{}, extra map[string]interface{}) ([]interface{}, error) { - client := meta.(*Config).metalgo + client := meta.(*internal.Config).Metalgo projectID := extra["project_id"].(string) orgID := extra["organization_id"].(string) @@ -93,5 +94,5 @@ func flattenDevice(rawDevice interface{}, meta interface{}, extra map[string]int if !ok { return nil, fmt.Errorf("expected device to be of type *metalv1.Device, got %T", rawDevice) } - return getDeviceMap(device), nil + return internal.GetDeviceMap(device), nil } diff --git a/equinix/data_source_metal_facility.go b/equinix/data_source_metal_facility.go index 38b85aa0a..e29a52418 100644 --- a/equinix/data_source_metal_facility.go +++ b/equinix/data_source_metal_facility.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "strings" @@ -81,7 +82,7 @@ func dataSourceMetalFacility() *schema.Resource { } func dataSourceMetalFacilityRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal code := d.Get("code").(string) _, capacityOk := d.GetOk("capacity") @@ -114,7 +115,7 @@ func dataSourceMetalFacilityRead(d *schema.ResourceData, meta interface{}) error for _, f := range facilities { if f.Code == code { if dfOk { - unsupported := difference(convertStringArr(dfRaw.(*schema.Set).List()), f.Features) + unsupported := internal.Difference(internal.ConvertStringArr(dfRaw.(*schema.Set).List()), f.Features) if len(unsupported) > 0 { return fmt.Errorf("facililty %s doesn't have feature(s) %v", f.Code, unsupported) } diff --git a/equinix/data_source_metal_hardware_reservation.go b/equinix/data_source_metal_hardware_reservation.go index 3dc9da595..33c4cb036 100644 --- a/equinix/data_source_metal_hardware_reservation.go +++ b/equinix/data_source_metal_hardware_reservation.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -65,7 +66,7 @@ func dataSourceMetalHardwareReservation() *schema.Resource { } func dataSourceMetalHardwareReservationRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal hrIdRaw, hrIdOk := d.GetOk("id") dIdRaw, dIdOk := d.GetOk("device_id") diff --git a/equinix/data_source_metal_ip_block_ranges.go b/equinix/data_source_metal_ip_block_ranges.go index 823b86a68..ea0d96869 100644 --- a/equinix/data_source_metal_ip_block_ranges.go +++ b/equinix/data_source_metal_ip_block_ranges.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -27,7 +28,7 @@ func dataSourceMetalIPBlockRanges() *schema.Resource { Type: schema.TypeString, Description: "Metro code filtering the IP blocks. Global IPv4 blocks will be listed anyway. If you omit this and facility, all the block from the project will be listed", Optional: true, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "public_ipv4": { Type: schema.TypeList, @@ -88,7 +89,7 @@ func metroOffacilityMatch(ref string, facility *packngo.Facility) bool { } func dataSourceMetalIPBlockRangesRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal projectID := d.Get("project_id").(string) ips, _, err := client.ProjectIPs.List(projectID, nil) if err != nil { diff --git a/equinix/data_source_metal_metro.go b/equinix/data_source_metal_metro.go index d8dde9647..d2f63b289 100644 --- a/equinix/data_source_metal_metro.go +++ b/equinix/data_source_metal_metro.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -37,7 +38,7 @@ func dataSourceMetalMetro() *schema.Resource { } func dataSourceMetalMetroRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal code := d.Get("code").(string) _, capacityOk := d.GetOk("capacity") diff --git a/equinix/data_source_metal_operating_system.go b/equinix/data_source_metal_operating_system.go index 469d493a8..d8cd775aa 100644 --- a/equinix/data_source_metal_operating_system.go +++ b/equinix/data_source_metal_operating_system.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "strings" @@ -42,7 +43,7 @@ func dataSourceOperatingSystem() *schema.Resource { } func dataSourceMetalOperatingSystemRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal name, nameOK := d.GetOk("name") distro, distroOK := d.GetOk("distro") diff --git a/equinix/data_source_metal_organization.go b/equinix/data_source_metal_organization.go index 24bdac3f5..338924981 100644 --- a/equinix/data_source_metal_organization.go +++ b/equinix/data_source_metal_organization.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "path" @@ -108,7 +109,7 @@ func findOrgByName(os []packngo.Organization, name string) (*packngo.Organizatio } func dataSourceMetalOrganizationRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal nameRaw, nameOK := d.GetOk("name") orgIdRaw, orgIdOK := d.GetOk("organization_id") diff --git a/equinix/data_source_metal_plans.go b/equinix/data_source_metal_plans.go index 58c13a90d..b995a76c3 100644 --- a/equinix/data_source_metal_plans.go +++ b/equinix/data_source_metal_plans.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/equinix/terraform-provider-equinix/equinix/internal/datalist" @@ -21,7 +22,7 @@ func dataSourceMetalPlans() *schema.Resource { } func getPlans(meta interface{}, extra map[string]interface{}) ([]interface{}, error) { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal opts := &packngo.ListOptions{ Includes: []string{"available_in", "available_in_metros"}, } @@ -106,10 +107,10 @@ func flattenPlan(rawPlan interface{}, meta interface{}, extra map[string]interfa metros = append(metros, m.Code) } - flattenedFacs := schema.NewSet(schema.HashString, stringArrToIfArr(facs)) - flattenedMetros := schema.NewSet(schema.HashString, stringArrToIfArr(metros)) + flattenedFacs := schema.NewSet(schema.HashString, internal.StringArrToIfArr(facs)) + flattenedMetros := schema.NewSet(schema.HashString, internal.StringArrToIfArr(metros)) flattenedDepTypes := schema.NewSet(schema.HashString, - stringArrToIfArr(plan.DeploymentTypes)) + internal.StringArrToIfArr(plan.DeploymentTypes)) flattenedPlan := map[string]interface{}{ "id": plan.ID, diff --git a/equinix/data_source_metal_precreated_ip_block.go b/equinix/data_source_metal_precreated_ip_block.go index dbedefcbe..7a793a4d1 100644 --- a/equinix/data_source_metal_precreated_ip_block.go +++ b/equinix/data_source_metal_precreated_ip_block.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" @@ -67,7 +68,7 @@ func dataSourceMetalPreCreatedIPBlock() *schema.Resource { func dataSourceMetalPreCreatedIPBlockRead(d *schema.ResourceData, meta interface{}) error { var types string - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal projectID := d.Get("project_id").(string) ipv := d.Get("address_family").(int) diff --git a/equinix/data_source_metal_project.go b/equinix/data_source_metal_project.go index 5e13c6800..c639432ac 100644 --- a/equinix/data_source_metal_project.go +++ b/equinix/data_source_metal_project.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "path" @@ -104,7 +105,7 @@ func dataSourceMetalProject() *schema.Resource { } func dataSourceMetalProjectRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal nameRaw, nameOK := d.GetOk("name") projectIdRaw, projectIdOK := d.GetOk("project_id") @@ -155,7 +156,7 @@ func dataSourceMetalProjectRead(d *schema.ResourceData, meta interface{}) error if bgpConf.ID != "" { err := d.Set("bgp_config", flattenBGPConfig(bgpConf)) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) return err } } diff --git a/equinix/data_source_metal_reserved_ip_block.go b/equinix/data_source_metal_reserved_ip_block.go index 512625c4c..b823aade0 100644 --- a/equinix/data_source_metal_reserved_ip_block.go +++ b/equinix/data_source_metal_reserved_ip_block.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "net" "strings" @@ -119,7 +120,7 @@ func dataSourceMetalReservedIPBlock() *schema.Resource { } func dataSourceMetalReservedIPBlockRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal blockId, blockIdOk := d.GetOk("id") projectId, projectIdOk := d.GetOk("project_id") diff --git a/equinix/data_source_metal_spot_market_price.go b/equinix/data_source_metal_spot_market_price.go index 24f659e6f..4bbf1d822 100644 --- a/equinix/data_source_metal_spot_market_price.go +++ b/equinix/data_source_metal_spot_market_price.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -23,7 +24,7 @@ func dataSourceSpotMarketPrice() *schema.Resource { Description: "Name of the metro", ConflictsWith: []string{"facility"}, Optional: true, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "plan": { Type: schema.TypeString, @@ -40,7 +41,7 @@ func dataSourceSpotMarketPrice() *schema.Resource { } func dataSourceMetalSpotMarketPriceRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal sms := client.SpotMarket.(*packngo.SpotMarketServiceOp) facility := d.Get("facility").(string) metro := d.Get("metro").(string) diff --git a/equinix/data_source_metal_spot_market_request.go b/equinix/data_source_metal_spot_market_request.go index 7b8f94cea..472a56b2a 100644 --- a/equinix/data_source_metal_spot_market_request.go +++ b/equinix/data_source_metal_spot_market_request.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "sort" "strings" @@ -74,13 +75,13 @@ func dataSourceMetalSpotMarketRequest() *schema.Resource { } func dataSourceMetalSpotMarketRequestRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal id := d.Get("request_id").(string) smr, _, err := client.SpotMarketRequests.Get(id, &packngo.GetOptions{Includes: []string{"project", "devices", "facilities", "metro"}}) if err != nil { - err = friendlyError(err) - if isNotFound(err) { + err = internal.FriendlyError(err) + if internal.IsNotFound(err) { d.SetId("") return nil } diff --git a/equinix/data_source_metal_vlan.go b/equinix/data_source_metal_vlan.go index 7c80b4123..3fa3ab076 100644 --- a/equinix/data_source_metal_vlan.go +++ b/equinix/data_source_metal_vlan.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -42,7 +43,7 @@ func dataSourceMetalVlan() *schema.Resource { Computed: true, ConflictsWith: []string{"vlan_id", "facility"}, Description: "Metro where the VLAN is deployed", - StateFunc: toLower, + StateFunc: internal.ToLower, }, "vlan_id": { Type: schema.TypeString, @@ -67,7 +68,7 @@ func dataSourceMetalVlan() *schema.Resource { } func dataSourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal projectRaw, projectOk := d.GetOk("project_id") vxlanRaw, vxlanOk := d.GetOk("vxlan") @@ -76,7 +77,7 @@ func dataSourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { facilityRaw, facilityOk := d.GetOk("facility") if !(vlanIdOk || (vxlanOk || projectOk || metroOk || facilityOk)) { - return friendlyError(fmt.Errorf("You must set either vlan_id or a combination of vxlan, project_id, and, metro or facility")) + return internal.FriendlyError(fmt.Errorf("You must set either vlan_id or a combination of vxlan, project_id, and, metro or facility")) } var vlan *packngo.VirtualNetwork @@ -88,7 +89,7 @@ func dataSourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { &packngo.GetOptions{Includes: []string{"assigned_to"}}, ) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } else { @@ -101,12 +102,12 @@ func dataSourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { &packngo.GetOptions{Includes: []string{"assigned_to"}}, ) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } vlan, err = matchingVlan(vlans.VirtualNetworks, vxlan, projectID, facility, metro) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -142,11 +143,11 @@ func matchingVlan(vlans []packngo.VirtualNetwork, vxlan int, projectID, facility matches = append(matches, v) } if len(matches) > 1 { - return nil, friendlyError(fmt.Errorf("Project %s has more than one matching VLAN", projectID)) + return nil, internal.FriendlyError(fmt.Errorf("Project %s has more than one matching VLAN", projectID)) } if len(matches) == 0 { - return nil, friendlyError(fmt.Errorf("Project %s does not have matching VLANs", projectID)) + return nil, internal.FriendlyError(fmt.Errorf("Project %s does not have matching VLANs", projectID)) } return &matches[0], nil } diff --git a/equinix/data_source_metal_vlan_acc_test.go b/equinix/data_source_metal_vlan_acc_test.go index a173e35b2..64ff2fb19 100644 --- a/equinix/data_source_metal_vlan_acc_test.go +++ b/equinix/data_source_metal_vlan_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "reflect" "testing" @@ -320,7 +321,7 @@ func TestMetalVlan_matchingVlan(t *testing.T) { } func testAccMetalDatasourceVlanCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_vlan" { diff --git a/equinix/data_source_network_account.go b/equinix/data_source_network_account.go index 50660bc77..30f2166bd 100644 --- a/equinix/data_source_network_account.go +++ b/equinix/data_source_network_account.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "strings" @@ -67,12 +68,12 @@ func dataSourceNetworkAccount() *schema.Resource { } func dataSourceNetworkAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics metro := d.Get(networkAccountSchemaNames["MetroCode"]).(string) name := d.Get(networkAccountSchemaNames["Name"]).(string) status := d.Get(networkAccountSchemaNames["Status"]).(string) - accounts, err := conf.ne.GetAccounts(metro) + accounts, err := conf.Ne.GetAccounts(metro) if err != nil { return diag.FromErr(err) } diff --git a/equinix/data_source_network_device.go b/equinix/data_source_network_device.go index 8d4b7fa45..1017a10fd 100644 --- a/equinix/data_source_network_device.go +++ b/equinix/data_source_network_device.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "strings" @@ -620,10 +621,10 @@ func dataSourceNetworkDevice() *schema.Resource { } } -func getDeviceByName(deviceName string, conf *Config, validDeviceStateList *[]string) (*ne.Device, error) { +func getDeviceByName(deviceName string, conf *internal.Config, validDeviceStateList *[]string) (*ne.Device, error) { var devices []ne.Device err := error(nil) - devices, err = conf.ne.GetDevices(*validDeviceStateList) + devices, err = conf.Ne.GetDevices(*validDeviceStateList) if err != nil { return nil, fmt.Errorf("'devices: %v'", devices) } @@ -636,7 +637,7 @@ func getDeviceByName(deviceName string, conf *Config, validDeviceStateList *[]st } func dataSourceNetworkDeviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics var err error var primary, secondary *ne.Device @@ -655,7 +656,7 @@ func dataSourceNetworkDeviceRead(ctx context.Context, d *schema.ResourceData, m if nameExists { primary, err = getDeviceByName(name, conf, validDeviceStatusList) } else { - primary, err = conf.ne.GetDevice(uuid) + primary, err = conf.Ne.GetDevice(uuid) } if err != nil { @@ -668,7 +669,7 @@ func dataSourceNetworkDeviceRead(ctx context.Context, d *schema.ResourceData, m } if ne.StringValue(primary.RedundantUUID) != "" { - secondary, err = conf.ne.GetDevice(ne.StringValue(primary.RedundantUUID)) + secondary, err = conf.Ne.GetDevice(ne.StringValue(primary.RedundantUUID)) if err != nil { return diag.Errorf("cannot fetch secondary network device due to '%v'", err) } diff --git a/equinix/data_source_network_device_software.go b/equinix/data_source_network_device_software.go index 81a8b6065..dda8c2a1e 100644 --- a/equinix/data_source_network_device_software.go +++ b/equinix/data_source_network_device_software.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "regexp" @@ -111,11 +112,11 @@ func dataSourceNetworkDeviceSoftware() *schema.Resource { } func dataSourceNetworkDeviceSoftwareRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics typeCode := d.Get(networkDeviceSoftwareSchemaNames["DeviceTypeCode"]).(string) - pkgCodes := expandSetToStringList(d.Get(networkDeviceSoftwareSchemaNames["PackageCodes"]).(*schema.Set)) - versions, err := conf.ne.GetDeviceSoftwareVersions(typeCode) + pkgCodes := internal.ExpandSetToStringList(d.Get(networkDeviceSoftwareSchemaNames["PackageCodes"]).(*schema.Set)) + versions, err := conf.Ne.GetDeviceSoftwareVersions(typeCode) if err != nil { return diag.FromErr(err) } diff --git a/equinix/data_source_network_device_type.go b/equinix/data_source_network_device_type.go index 0bdeb178f..d405f834d 100644 --- a/equinix/data_source_network_device_type.go +++ b/equinix/data_source_network_device_type.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "strings" @@ -81,13 +82,13 @@ func dataSourceNetworkDeviceType() *schema.Resource { } func dataSourceNetworkDeviceTypeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics - types, err := conf.ne.GetDeviceTypes() + types, err := conf.Ne.GetDeviceTypes() name := d.Get(networkDeviceTypeSchemaNames["Name"]).(string) vendor := d.Get(networkDeviceTypeSchemaNames["Vendor"]).(string) category := d.Get(networkDeviceTypeSchemaNames["Category"]).(string) - metroCodes := expandSetToStringList(d.Get(networkDeviceTypeSchemaNames["MetroCodes"]).(*schema.Set)) + metroCodes := internal.ExpandSetToStringList(d.Get(networkDeviceTypeSchemaNames["MetroCodes"]).(*schema.Set)) if err != nil { return diag.FromErr(err) } diff --git a/equinix/data_source_network_platform.go b/equinix/data_source_network_platform.go index 739bf1d32..1eddefbb1 100644 --- a/equinix/data_source_network_platform.go +++ b/equinix/data_source_network_platform.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" @@ -104,10 +105,10 @@ func dataSourceNetworkDevicePlatform() *schema.Resource { } func dataSourceNetworkDevicePlatformRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - conf := m.(*Config) + conf := m.(*internal.Config) var diags diag.Diagnostics typeCode := d.Get(networkDevicePlatformSchemaNames["DeviceTypeCode"]).(string) - platforms, err := conf.ne.GetDevicePlatforms(typeCode) + platforms, err := conf.Ne.GetDevicePlatforms(typeCode) if err != nil { return diag.FromErr(err) } @@ -120,19 +121,19 @@ func dataSourceNetworkDevicePlatformRead(ctx context.Context, d *schema.Resource continue } if v, ok := d.GetOk(networkDevicePlatformSchemaNames["PackageCodes"]); ok { - pkgCodes := expandSetToStringList(v.(*schema.Set)) + pkgCodes := internal.ExpandSetToStringList(v.(*schema.Set)) if !stringsFound(pkgCodes, platform.PackageCodes) { continue } } if v, ok := d.GetOk(networkDevicePlatformSchemaNames["ManagementTypes"]); ok { - mgmtTypes := expandSetToStringList(v.(*schema.Set)) + mgmtTypes := internal.ExpandSetToStringList(v.(*schema.Set)) if !stringsFound(mgmtTypes, platform.ManagementTypes) { continue } } if v, ok := d.GetOk(networkDevicePlatformSchemaNames["LicenseOptions"]); ok { - licOptions := expandSetToStringList(v.(*schema.Set)) + licOptions := internal.ExpandSetToStringList(v.(*schema.Set)) if !stringsFound(licOptions, platform.LicenseOptions) { continue } diff --git a/equinix/equinix_sweeper_test.go b/equinix/equinix_sweeper_test.go index ea717ed0e..16f20541c 100644 --- a/equinix/equinix_sweeper_test.go +++ b/equinix/equinix_sweeper_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "github.com/equinix/terraform-provider-equinix/equinix/internal" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -16,24 +18,24 @@ func TestMain(m *testing.M) { resource.TestMain(m) } -func sharedConfigForRegion(region string) (*Config, error) { - endpoint := getFromEnvDefault(endpointEnvVar, DefaultBaseURL) - clientToken := getFromEnvDefault(clientTokenEnvVar, "") - clientID := getFromEnvDefault(clientIDEnvVar, "") - clientSecret := getFromEnvDefault(clientSecretEnvVar, "") - clientTimeout := getFromEnvDefault(clientTimeoutEnvVar, strconv.Itoa(DefaultTimeout)) +func sharedConfigForRegion(region string) (*internal.Config, error) { + endpoint := getFromEnvDefault(EndpointEnvVar, internal.DefaultBaseURL) + clientToken := getFromEnvDefault(ClientTokenEnvVar, "") + clientID := getFromEnvDefault(ClientIDEnvVar, "") + clientSecret := getFromEnvDefault(ClientSecretEnvVar, "") + clientTimeout := getFromEnvDefault(ClientTimeoutEnvVar, strconv.Itoa(internal.DefaultTimeout)) clientTimeoutInt, err := strconv.Atoi(clientTimeout) if err != nil { - return nil, fmt.Errorf("cannot convert value of '%s' env variable to int", clientTimeoutEnvVar) + return nil, fmt.Errorf("cannot convert value of '%s' env variable to int", ClientTimeoutEnvVar) } - metalAuthToken := getFromEnvDefault(metalAuthTokenEnvVar, "") + metalAuthToken := getFromEnvDefault(MetalAuthTokenEnvVar, "") if clientToken == "" && (clientID == "" || clientSecret == "") && metalAuthToken == "" { return nil, fmt.Errorf("To run acceptance tests sweeper, one of '%s' or pair '%s' - '%s' must be set for Equinix Fabric and Network Edge, and '%s' for Equinix Metal", - clientTokenEnvVar, clientIDEnvVar, clientSecretEnvVar, metalAuthTokenEnvVar) + ClientTokenEnvVar, ClientIDEnvVar, ClientSecretEnvVar, MetalAuthTokenEnvVar) } - return &Config{ + return &internal.Config{ AuthToken: metalAuthToken, BaseURL: endpoint, Token: clientToken, diff --git a/equinix/fabric_cloud_router_read_schema.go b/equinix/fabric_cloud_router_read_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_cloud_router_schema.go b/equinix/fabric_cloud_router_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_connection_read_schema.go b/equinix/fabric_connection_read_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_connection_schema.go b/equinix/fabric_connection_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_necessary_utilities.go b/equinix/fabric_necessary_utilities.go new file mode 100644 index 000000000..965899109 --- /dev/null +++ b/equinix/fabric_necessary_utilities.go @@ -0,0 +1,49 @@ +package equinix + +import ( + "fmt" + "sort" + + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +type setFn = func(d *schema.ResourceData, key string) error + +func expandListToStringList(list []interface{}) []string { + result := make([]string, len(list)) + for i, v := range list { + result[i] = fmt.Sprint(v) + } + return result +} + +func expandListToInt32List(list []interface{}) []int32 { + result := make([]int32, len(list)) + for i, v := range list { + result[i] = int32(v.(int)) + } + return result +} + +func setMap(d *schema.ResourceData, m map[string]interface{}) error { + errs := &multierror.Error{} + for key, v := range m { + var err error + if f, ok := v.(setFn); ok { + err = f(d, key) + } else { + if key == "router" { + d.Set("gateway", v) + } + err = d.Set(key, v) + } + + if err != nil { + errs = multierror.Append(errs, err) + } + } + sort.Sort(errs) + + return errs.ErrorOrNil() +} \ No newline at end of file diff --git a/equinix/fabric_service_profile_read_schema.go b/equinix/fabric_service_profile_read_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_service_profile_schema.go b/equinix/fabric_service_profile_schema.go old mode 100755 new mode 100644 diff --git a/equinix/fabric_service_profile_search_schema.go b/equinix/fabric_service_profile_search_schema.go old mode 100755 new mode 100644 diff --git a/equinix/config.go b/equinix/internal/config.go similarity index 89% rename from equinix/config.go rename to equinix/internal/config.go index b2c5ee812..3598872ea 100644 --- a/equinix/config.go +++ b/equinix/internal/config.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "context" @@ -28,6 +28,15 @@ import ( xoauth2 "golang.org/x/oauth2" ) +var ( + UuidRE = regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$") + IpAddressTypes = []string{"public_ipv4", "private_ipv4", "public_ipv6"} +) + +type ProviderMeta struct { + ModuleName string `cty:"module_name"` +} + type DumpTransport struct { r http.RoundTripper } @@ -81,18 +90,18 @@ type Config struct { PageSize int Token string - ecx ecx.Client - ne ne.Client - metal *packngo.Client - metalgo *metalv1.APIClient + Ecx ecx.Client + Ne ne.Client + Metal *packngo.Client + Metalgo *metalv1.APIClient ecxUserAgent string neUserAgent string metalUserAgent string metalGoUserAgent string - terraformVersion string - fabricClient *v4.APIClient + TerraformVersion string + FabricClient *v4.APIClient FabricAuthToken string } @@ -158,15 +167,17 @@ func (c *Config) Load(ctx context.Context) error { "User-agent": c.neUserAgent, }) - c.ecx = ecxClient - c.ne = neClient - c.metal = c.NewMetalClient() - c.metalgo = c.NewMetalGoClient() - c.fabricClient = c.NewFabricClient() + c.Ecx = ecxClient + c.Ne = neClient + c.Metal = c.NewMetalClient() + c.Metalgo = c.NewMetalGoClient() + c.FabricClient = c.NewFabricClient() return nil } // NewFabricClient returns a new client for accessing Equinix Fabric's v4 API. +// uncomment the funct when migrating Fabric resources to use +// functions from internal/ func (c *Config) NewFabricClient() *v4.APIClient { transport := logging.NewTransport("Equinix Fabric", http.DefaultTransport) authClient := &http.Client{ @@ -281,14 +292,14 @@ func terraformUserAgent(version string) string { return ua } -func (c *Config) addModuleToECXUserAgent(client *ecx.Client, d *schema.ResourceData) { +func (c *Config) AddModuleToECXUserAgent(client *ecx.Client, d *schema.ResourceData) { cli := *client rc := cli.(*ecx.RestClient) rc.SetHeader("User-agent", generateModuleUserAgentString(d, c.ecxUserAgent)) *client = rc } -func (c *Config) addModuleToNEUserAgent(client *ne.Client, d *schema.ResourceData) { +func (c *Config) AddModuleToNEUserAgent(client *ne.Client, d *schema.ResourceData) { cli := *client rc := cli.(*ne.RestClient) rc.SetHeader("User-agent", generateModuleUserAgentString(d, c.neUserAgent)) @@ -300,16 +311,16 @@ func (c *Config) addModuleToNEUserAgent(client *ne.Client, d *schema.ResourceDat // the UserAgent resulting in swapped UserAgent. // This can be fixed by letting the headers be overwritten on the initialized Packngo ServiceOp // clients on a query-by-query basis. -func (c *Config) addModuleToMetalUserAgent(d *schema.ResourceData) { - c.metal.UserAgent = generateModuleUserAgentString(d, c.metalUserAgent) +func (c *Config) AddModuleToMetalUserAgent(d *schema.ResourceData) { + c.Metal.UserAgent = generateModuleUserAgentString(d, c.metalUserAgent) } func (c *Config) addModuleToMetalGoUserAgent(d *schema.ResourceData) { - c.metalgo.GetConfig().UserAgent = generateModuleUserAgentString(d, c.metalGoUserAgent) + c.Metalgo.GetConfig().UserAgent = generateModuleUserAgentString(d, c.metalGoUserAgent) } func generateModuleUserAgentString(d *schema.ResourceData, baseUserAgent string) string { - var m providerMeta + var m ProviderMeta err := d.GetProviderMeta(&m) if err != nil { log.Printf("[WARN] error retrieving provider_meta") @@ -323,7 +334,7 @@ func generateModuleUserAgentString(d *schema.ResourceData, baseUserAgent string) } func (c *Config) fullUserAgent(suffix string) string { - tfUserAgent := terraformUserAgent(c.terraformVersion) + tfUserAgent := terraformUserAgent(c.TerraformVersion) userAgent := fmt.Sprintf("%s terraform-provider-equinix/%s %s", tfUserAgent, version.ProviderVersion, suffix) return strings.TrimSpace(userAgent) } diff --git a/equinix/errors.go b/equinix/internal/errors.go similarity index 84% rename from equinix/errors.go rename to equinix/internal/errors.go index c3c546762..185d0faf3 100644 --- a/equinix/errors.go +++ b/equinix/internal/errors.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "fmt" @@ -12,9 +12,9 @@ import ( "github.com/packethost/packngo" ) -// friendlyError improves error messages when the API error is blank or in an +// FriendlyError improves error messages when the API error is blank or in an // alternate format (as is the case with invalid token or loadbalancer errors) -func friendlyError(err error) error { +func FriendlyError(err error) error { if e, ok := err.(*packngo.ErrorResponse); ok { resp := e.Response errors := Errors(e.Errors) @@ -28,7 +28,7 @@ func friendlyError(err error) error { return err } -func friendlyErrorForMetalGo(err error, resp *http.Response) error { +func FriendlyErrorForMetalGo(err error, resp *http.Response) error { errors := Errors([]string{err.Error()}) return convertToFriendlyError(errors, resp) } @@ -51,7 +51,7 @@ func convertToFriendlyError(errors Errors, resp *http.Response) error { return er } -func isForbidden(err error) bool { +func IsForbidden(err error) bool { r, ok := err.(*packngo.ErrorResponse) if ok && r.Response != nil { return r.Response.StatusCode == http.StatusForbidden @@ -62,7 +62,7 @@ func isForbidden(err error) bool { return false } -func isNotFound(err error) bool { +func IsNotFound(err error) bool { if r, ok := err.(*ErrorResponse); ok { return r.StatusCode == http.StatusNotFound && r.IsAPIError } @@ -124,8 +124,8 @@ func setMap(d *schema.ResourceData, m map[string]interface{}) error { type setFn = func(d *schema.ResourceData, key string) error -// isNotAssigned matches errors reported from unassigned virtual networks -func isNotAssigned(resp *http.Response, err error) bool { +// IsNotAssigned matches errors reported from unassigned virtual networks +func IsNotAssigned(resp *http.Response, err error) bool { if resp.StatusCode != http.StatusUnprocessableEntity { return false } @@ -139,34 +139,34 @@ func isNotAssigned(resp *http.Response, err error) bool { return false } -func httpForbidden(resp *http.Response, err error) bool { +func HttpForbidden(resp *http.Response, err error) bool { if resp != nil && (resp.StatusCode != http.StatusForbidden) { return false } switch err := err.(type) { case *ErrorResponse, *packngo.ErrorResponse: - return isForbidden(err) + return IsForbidden(err) } return false } -func httpNotFound(resp *http.Response, err error) bool { +func HttpNotFound(resp *http.Response, err error) bool { if resp != nil && (resp.StatusCode != http.StatusNotFound) { return false } switch err := err.(type) { case *ErrorResponse, *packngo.ErrorResponse: - return isNotFound(err) + return IsNotFound(err) } return false } -// ignoreResponseErrors ignores http response errors when matched by one of the +// IgnoreResponseErrors ignores http response errors when matched by one of the // provided checks -func ignoreResponseErrors(ignore ...func(resp *http.Response, err error) bool) func(resp *packngo.Response, err error) error { +func IgnoreResponseErrors(ignore ...func(resp *http.Response, err error) bool) func(resp *packngo.Response, err error) error { return func(resp *packngo.Response, err error) error { var r *http.Response if resp != nil && resp.Response != nil { diff --git a/equinix/internal/fabric_helpers_stub.go b/equinix/internal/fabric_helpers_stub.go new file mode 100644 index 000000000..c86ef0d29 --- /dev/null +++ b/equinix/internal/fabric_helpers_stub.go @@ -0,0 +1,26 @@ +package internal + +import ( + "math/rand" + "time" +) + +// This is just some code needed for NewFabricClient here in internal/ + +const allowed_charset = "abcdefghijklmnopqrstuvwxyz" + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$&@" + +var seededRand = rand.New( + rand.NewSource(time.Now().UnixNano())) + +func CorrelationIdWithCharset(length int, charset string) string { + b := make([]byte, length) + for i := range b { + b[i] = charset[seededRand.Intn(len(charset))] + } + return string(b) +} + +func CorrelationId(length int) string { + return CorrelationIdWithCharset(length, allowed_charset) +} diff --git a/equinix/hashcode.go b/equinix/internal/hashcode.go similarity index 89% rename from equinix/hashcode.go rename to equinix/internal/hashcode.go index 3fb5af523..ce9b2e9ff 100644 --- a/equinix/hashcode.go +++ b/equinix/internal/hashcode.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "hash/crc32" @@ -11,7 +11,7 @@ import ( // and invert it if the result is negative. // // Originally from https://github.com/hashicorp/terraform-plugin-sdk/blob/main/internal/helper/hashcode/hashcode.go -func hashcodeString(s string) int { +func HashcodeString(s string) int { v := int(crc32.ChecksumIEEE([]byte(s))) if v >= 0 { return v diff --git a/equinix/helpers_device.go b/equinix/internal/helpers_device.go similarity index 81% rename from equinix/helpers_device.go rename to equinix/internal/helpers_device.go index fcf26c1f8..9d81b4c79 100644 --- a/equinix/helpers_device.go +++ b/equinix/internal/helpers_device.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "context" @@ -47,11 +47,11 @@ func ifToIPCreateRequest(m interface{}) packngo.IPAddressCreateRequest { iacr.Public = true } iacr.CIDR = ia["cidr"].(int) - iacr.Reservations = convertStringArr(ia["reservation_ids"].([]interface{})) + iacr.Reservations = ConvertStringArr(ia["reservation_ids"].([]interface{})) return iacr } -func getNewIPAddressSlice(arr []interface{}) []packngo.IPAddressCreateRequest { +func GetNewIPAddressSlice(arr []interface{}) []packngo.IPAddressCreateRequest { addressTypesSlice := make([]packngo.IPAddressCreateRequest, len(arr)) for i, m := range arr { @@ -69,7 +69,7 @@ type NetworkInfo struct { PrivateIPv4 string } -func getNetworkInfo(ips []metalv1.IPAssignment) NetworkInfo { +func GetNetworkInfo(ips []metalv1.IPAssignment) NetworkInfo { ni := NetworkInfo{Networks: make([]map[string]interface{}, 0, 1)} for _, ip := range ips { network := map[string]interface{}{ @@ -99,7 +99,7 @@ func getNetworkInfo(ips []metalv1.IPAssignment) NetworkInfo { return ni } -func getNetworkType(device *metalv1.Device) (*string, error) { +func GetNetworkType(device *metalv1.Device) (*string, error) { pgDevice := packngo.Device{} res, err := device.MarshalJSON() if err == nil { @@ -111,7 +111,7 @@ func getNetworkType(device *metalv1.Device) (*string, error) { return nil, err } -func getNetworkRank(family int, public bool) int { +func GetNetworkRank(family int, public bool) int { switch { case family == 4 && public: return 0 @@ -123,15 +123,15 @@ func getNetworkRank(family int, public bool) int { return 3 } -func getPorts(ps []metalv1.Port) []map[string]interface{} { +func GetPorts(ps []metalv1.Port) []map[string]interface{} { ret := make([]map[string]interface{}, 0, 1) for _, p := range ps { port := map[string]interface{}{ - "name": p.GetName(), - "id": p.GetId(), - "type": p.GetType(), - "mac": p.Data.GetMac(), - "bonded": p.Data.GetBonded(), + "name": p.Name, + "id": p.Id, + "type": p.Type, + "mac": p.Data.Mac, + "bonded": p.Data.Bonded, } ret = append(ret, port) } @@ -144,7 +144,7 @@ func hwReservationStateRefreshFunc(client *packngo.Client, reservationId, instan state := deprovisioning switch { case err != nil: - err = friendlyError(err) + err = FriendlyError(err) state = errstate case r != nil && r.Provisionable: state = provisionable @@ -159,7 +159,7 @@ func hwReservationStateRefreshFunc(client *packngo.Client, reservationId, instan } } -func waitUntilReservationProvisionable(ctx context.Context, client *packngo.Client, reservationId, instanceId string, delay, timeout, minTimeout time.Duration) error { +func WaitUntilReservationProvisionable(ctx context.Context, client *packngo.Client, reservationId, instanceId string, delay, timeout, minTimeout time.Duration) error { stateConf := &retry.StateChangeConf{ Pending: []string{deprovisioning}, Target: []string{provisionable, reprovisioned}, @@ -183,7 +183,7 @@ func getWaitForDeviceLock(deviceID string) *sync.WaitGroup { return wg } -func waitForDeviceAttribute(ctx context.Context, d *schema.ResourceData, stateConf *retry.StateChangeConf) (string, error) { +func WaitForDeviceAttribute(ctx context.Context, d *schema.ResourceData, stateConf *retry.StateChangeConf) (string, error) { wg := getWaitForDeviceLock(d.Id()) wg.Wait() @@ -210,14 +210,14 @@ func waitForDeviceAttribute(ctx context.Context, d *schema.ResourceData, stateCo return "", err } -func ipAddressSchema() *schema.Resource { +func IpAddressSchema() *schema.Resource { return &schema.Resource{ Schema: map[string]*schema.Schema{ "type": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringInSlice(ipAddressTypes, false), - Description: fmt.Sprintf("one of %s", strings.Join(ipAddressTypes, ",")), + ValidateFunc: validation.StringInSlice(IpAddressTypes, false), + Description: fmt.Sprintf("one of %s", strings.Join(IpAddressTypes, ",")), }, "cidr": { Type: schema.TypeInt, @@ -231,27 +231,27 @@ func ipAddressSchema() *schema.Resource { MinItems: 1, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: validation.StringMatch(uuidRE, "must be a valid UUID"), + ValidateFunc: validation.StringMatch(UuidRE, "must be a valid UUID"), }, }, }, } } -func getDeviceMap(device metalv1.Device) map[string]interface{} { - networkInfo := getNetworkInfo(device.IpAddresses) +func GetDeviceMap(device metalv1.Device) map[string]interface{} { + networkInfo := GetNetworkInfo(device.IpAddresses) sort.SliceStable(networkInfo.Networks, func(i, j int) bool { - famI := int(networkInfo.Networks[i]["family"].(int32)) - famJ := int(networkInfo.Networks[j]["family"].(int32)) - pubI := networkInfo.Networks[i]["public"].(bool) - pubJ := networkInfo.Networks[j]["public"].(bool) - return getNetworkRank(famI, pubI) < getNetworkRank(famJ, pubJ) + famI := int(*networkInfo.Networks[i]["family"].(*int32)) + famJ := int(*networkInfo.Networks[j]["family"].(*int32)) + pubI := *networkInfo.Networks[i]["public"].(*bool) + pubJ := *networkInfo.Networks[j]["public"].(*bool) + return GetNetworkRank(famI, pubI) < GetNetworkRank(famJ, pubJ) }) keyIDs := []string{} for _, k := range device.SshKeys { keyIDs = append(keyIDs, path.Base(k.GetHref())) } - ports := getPorts(device.NetworkPorts) + ports := GetPorts(device.NetworkPorts) return map[string]interface{}{ "hostname": device.GetHostname(), @@ -267,7 +267,7 @@ func getDeviceMap(device metalv1.Device) map[string]interface{} { "ipxe_script_url": device.GetIpxeScriptUrl(), "always_pxe": device.GetAlwaysPxe(), "root_password": device.GetRootPassword(), - "tags": stringArrToIfArr(device.GetTags()), + "tags": StringArrToIfArr(device.GetTags()), "access_public_ipv6": networkInfo.PublicIPv6, "access_public_ipv4": networkInfo.PublicIPv4, "access_private_ipv4": networkInfo.PrivateIPv4, diff --git a/equinix/helpers_device_test.go b/equinix/internal/helpers_device_test.go similarity index 92% rename from equinix/helpers_device_test.go rename to equinix/internal/helpers_device_test.go index f57c714d3..c3cc57b3c 100644 --- a/equinix/helpers_device_test.go +++ b/equinix/internal/helpers_device_test.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "context" @@ -29,7 +29,7 @@ func (m *mockHWService) Move(id string, dest string) (*packngo.HardwareReservati var _ packngo.HardwareReservationService = (*mockHWService)(nil) -func Test_waitUntilReservationProvisionable(t *testing.T) { +func Test_WaitUntilReservationProvisionable(t *testing.T) { type args struct { reservationId string instanceId string @@ -79,7 +79,7 @@ func Test_waitUntilReservationProvisionable(t *testing.T) { *invoked++ var device *packngo.Device - if opts != nil && contains(opts.Includes, "device") { + if opts != nil && Contains(opts.Includes, "device") { device = &packngo.Device{ID: response.id} } return &packngo.HardwareReservation{ @@ -114,7 +114,7 @@ func Test_waitUntilReservationProvisionable(t *testing.T) { *invoked++ var device *packngo.Device - if opts != nil && contains(opts.Includes, "device") { + if opts != nil && Contains(opts.Includes, "device") { device = &packngo.Device{ID: response.id} } return &packngo.HardwareReservation{ @@ -150,8 +150,8 @@ func Test_waitUntilReservationProvisionable(t *testing.T) { // timeout * number of tests that reach timeout must be less than 30s (default go test timeout). for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := waitUntilReservationProvisionable(context.Background(), tt.args.meta, tt.args.reservationId, tt.args.instanceId, 50*time.Millisecond, 1*time.Second, 50*time.Millisecond); (err != nil) != tt.wantErr { - t.Errorf("waitUntilReservationProvisionable() error = %v, wantErr %v", err, tt.wantErr) + if err := WaitUntilReservationProvisionable(context.Background(), tt.args.meta, tt.args.reservationId, tt.args.instanceId, 50*time.Millisecond, 1*time.Second, 50*time.Millisecond); (err != nil) != tt.wantErr { + t.Errorf("WaitUntilReservationProvisionable() error = %v, wantErr %v", err, tt.wantErr) } }) } diff --git a/equinix/mutexkv.go b/equinix/internal/mutexkv.go similarity index 98% rename from equinix/mutexkv.go rename to equinix/internal/mutexkv.go index 29bc015a9..1d2f738cc 100644 --- a/equinix/mutexkv.go +++ b/equinix/internal/mutexkv.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "log" diff --git a/equinix/port_helpers.go b/equinix/internal/port_helpers.go similarity index 89% rename from equinix/port_helpers.go rename to equinix/internal/port_helpers.go index 742198d7b..9d9754060 100644 --- a/equinix/port_helpers.go +++ b/equinix/internal/port_helpers.go @@ -1,4 +1,4 @@ -package equinix +package internal import ( "context" @@ -18,9 +18,14 @@ type ClientPortResource struct { Resource *schema.ResourceData } -func getClientPortResource(d *schema.ResourceData, meta interface{}) (*ClientPortResource, *packngo.Response, error) { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal +var ( + L2Types = []string{"layer2-individual", "layer2-bonded"} + L3Types = []string{"layer3", "hybrid", "hybrid-bonded"} +) + +func GetClientPortResource(d *schema.ResourceData, meta interface{}) (*ClientPortResource, *packngo.Response, error) { + meta.(*Config).AddModuleToMetalUserAgent(d) + client := meta.(*Config).Metal port_id := d.Get("port_id").(string) @@ -41,7 +46,7 @@ func getClientPortResource(d *schema.ResourceData, meta interface{}) (*ClientPor return cpr, resp, nil } -func getPortByResourceData(d *schema.ResourceData, client *packngo.Client) (*packngo.Port, error) { +func GetPortByResourceData(d *schema.ResourceData, client *packngo.Client) (*packngo.Port, error) { portId, portIdOk := d.GetOk("port_id") resourceId := d.Id() @@ -117,7 +122,7 @@ func specifiedVlanIds(d *schema.ResourceData) []string { // either vlan_ids or vxlan_ids should be set, TF should ensure that vlanIdsRaw, vlanIdsOk := d.GetOk("vlan_ids") if vlanIdsOk { - return convertStringArr(vlanIdsRaw.(*schema.Set).List()) + return ConvertStringArr(vlanIdsRaw.(*schema.Set).List()) } vxlanIdsRaw, vxlanIdsOk := d.GetOk("vxlan_ids") @@ -127,18 +132,18 @@ func specifiedVlanIds(d *schema.ResourceData) []string { return []string{} } -func batchVlans(ctx context.Context, start time.Time, removeOnly bool) func(*ClientPortResource) error { +func BatchVlans(ctx context.Context, start time.Time, removeOnly bool) func(*ClientPortResource) error { return func(cpr *ClientPortResource) error { var vlansToAssign []string var currentNative string - vlansToRemove := difference( + vlansToRemove := Difference( attachedVlanIds(cpr.Port), specifiedVlanIds(cpr.Resource), ) if !removeOnly { currentNative = getCurrentNative(cpr.Port) - vlansToAssign = difference( + vlansToAssign = Difference( specifiedVlanIds(cpr.Resource), attachedVlanIds(cpr.Port), ) @@ -208,7 +213,7 @@ func createAndWaitForBatch(ctx context.Context, start time.Time, cpr *ClientPort return nil } -func updateNativeVlan(cpr *ClientPortResource) error { +func UpdateNativeVlan(cpr *ClientPortResource) error { currentNative := getCurrentNative(cpr.Port) specifiedNative := getSpecifiedNative(cpr.Resource) @@ -259,17 +264,17 @@ func processBondAction(cpr *ClientPortResource, actionIsBond bool) error { return nil } -func makeBond(cpr *ClientPortResource) error { +func MakeBond(cpr *ClientPortResource) error { return processBondAction(cpr, true) } -func makeDisbond(cpr *ClientPortResource) error { +func MakeDisbond(cpr *ClientPortResource) error { return processBondAction(cpr, false) } -func convertToL2(cpr *ClientPortResource) error { +func ConvertToL2(cpr *ClientPortResource) error { l2, l2Ok := cpr.Resource.GetOkExists("layer2") - isLayer2 := contains(l2Types, cpr.Port.NetworkType) + isLayer2 := Contains(L2Types, cpr.Port.NetworkType) if l2Ok && l2.(bool) && !isLayer2 { port, _, err := cpr.Client.Ports.ConvertToLayerTwo(cpr.Port.ID) @@ -281,9 +286,9 @@ func convertToL2(cpr *ClientPortResource) error { return nil } -func convertToL3(cpr *ClientPortResource) error { +func ConvertToL3(cpr *ClientPortResource) error { l2, l2Ok := cpr.Resource.GetOkExists("layer2") - isLayer2 := contains(l2Types, cpr.Port.NetworkType) + isLayer2 := Contains(L2Types, cpr.Port.NetworkType) if l2Ok && !l2.(bool) && isLayer2 { ips := []packngo.AddressRequest{ @@ -300,7 +305,7 @@ func convertToL3(cpr *ClientPortResource) error { return nil } -func portSanityChecks(cpr *ClientPortResource) error { +func PortSanityChecks(cpr *ClientPortResource) error { isBondPort := cpr.Port.Type == "NetworkBondPort" // Constraint: Only bond ports have layer2 mode @@ -325,7 +330,7 @@ func portSanityChecks(cpr *ClientPortResource) error { if nativeVlanOk { nativeVlan := nativeVlanRaw.(string) vlans := specifiedVlanIds(cpr.Resource) - if !contains(vlans, nativeVlan) { + if !Contains(vlans, nativeVlan) { return fmt.Errorf("the native VLAN to be set is not (being) assigned to the port") } if len(vlans) < 2 { @@ -336,7 +341,7 @@ func portSanityChecks(cpr *ClientPortResource) error { return nil } -func portProperlyDestroyed(port *packngo.Port) error { +func PortProperlyDestroyed(port *packngo.Port) error { var errs []string if !port.Data.Bonded { errs = append(errs, fmt.Sprintf("port %s wasn't bonded after equinix_metal_port destroy;", port.ID)) diff --git a/equinix/internal/utils.go b/equinix/internal/utils.go new file mode 100644 index 000000000..9d51c03ef --- /dev/null +++ b/equinix/internal/utils.go @@ -0,0 +1,106 @@ +package internal + +import ( + "fmt" + "strconv" + "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func Contains(s []string, e string) bool { + for _, a := range s { + if a == e { + return true + } + } + return false +} + +func StringArrToIfArr(sli []string) []interface{} { + var arr []interface{} + for _, v := range sli { + arr = append(arr, v) + } + return arr +} + +func ConvertStringArr(ifaceArr []interface{}) []string { + var arr []string + for _, v := range ifaceArr { + if v == nil { + continue + } + arr = append(arr, v.(string)) + } + return arr +} + +func convertIntArr(ifaceArr []interface{}) []string { + var arr []string + for _, v := range ifaceArr { + if v == nil { + continue + } + arr = append(arr, strconv.Itoa(v.(int))) + } + return arr +} + +func ConvertIntArr2(ifaceArr []interface{}) []int { + var arr []int + for _, v := range ifaceArr { + if v == nil { + continue + } + arr = append(arr, v.(int)) + } + return arr +} + +func ToLower(v interface{}) string { + return strings.ToLower(v.(string)) +} + +// from https://stackoverflow.com/a/45428032 +func Difference(a, b []string) []string { + mb := make(map[string]struct{}, len(b)) + for _, x := range b { + mb[x] = struct{}{} + } + var diff []string + for _, x := range a { + if _, found := mb[x]; !found { + diff = append(diff, x) + } + } + return diff +} + +func expandListToStringList(list []interface{}) []string { + result := make([]string, len(list)) + for i, v := range list { + result[i] = fmt.Sprint(v) + } + return result +} + +func expandListToInt32List(list []interface{}) []int32 { + result := make([]int32, len(list)) + for i, v := range list { + result[i] = int32(v.(int)) + } + return result +} + +func ExpandSetToStringList(set *schema.Set) []string { + list := set.List() + return expandListToStringList(list) +} + +func ExpandInterfaceMapToStringMap(mapIn map[string]interface{}) map[string]string { + mapOut := make(map[string]string) + for k, v := range mapIn { + mapOut[k] = fmt.Sprintf("%v", v) + } + return mapOut +} diff --git a/equinix/data_source_metal_project_ssh_key.go b/equinix/metal_project_ssh_key/data_source.go similarity index 91% rename from equinix/data_source_metal_project_ssh_key.go rename to equinix/metal_project_ssh_key/data_source.go index ae564a36c..8acb741c0 100644 --- a/equinix/data_source_metal_project_ssh_key.go +++ b/equinix/metal_project_ssh_key/data_source.go @@ -1,16 +1,18 @@ -package equinix +package metal_project_ssh_key import ( "fmt" "path" "strings" + "github.com/equinix/terraform-provider-equinix/equinix/internal" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/packethost/packngo" ) -func dataSourceMetalProjectSSHKey() *schema.Resource { +func DataSource() *schema.Resource { return &schema.Resource{ Read: dataSourceMetalProjectSSHKeyRead, Schema: map[string]*schema.Schema{ @@ -64,7 +66,7 @@ func dataSourceMetalProjectSSHKey() *schema.Resource { } func dataSourceMetalProjectSSHKeyRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal search := d.Get("search").(string) id := d.Get("id").(string) @@ -84,7 +86,7 @@ func dataSourceMetalProjectSSHKeyRead(d *schema.ResourceData, meta interface{}) } keys, _, err := client.Projects.ListSSHKeys(projectID, searchOpts) if err != nil { - err = fmt.Errorf("Error listing project ssh keys: %s", friendlyError(err)) + err = fmt.Errorf("Error listing project ssh keys: %s", internal.FriendlyError(err)) return err } diff --git a/equinix/data_source_metal_project_ssh_key_acc_test.go b/equinix/metal_project_ssh_key/data_source_test.go similarity index 88% rename from equinix/data_source_metal_project_ssh_key_acc_test.go rename to equinix/metal_project_ssh_key/data_source_test.go index 45180e237..5e27a13d5 100644 --- a/equinix/data_source_metal_project_ssh_key_acc_test.go +++ b/equinix/metal_project_ssh_key/data_source_test.go @@ -1,4 +1,4 @@ -package equinix +package metal_project_ssh_key_test import ( "fmt" @@ -7,8 +7,12 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + "github.com/equinix/terraform-provider-equinix/equinix/acceptance" ) +// + func TestAccDataSourceMetalProjectSSHKey_bySearch(t *testing.T) { datasourceName := "data.equinix_metal_project_ssh_key.foobar" keyName := acctest.RandomWithPrefix("tfacc-project-key") @@ -19,10 +23,10 @@ func TestAccDataSourceMetalProjectSSHKey_bySearch(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, PreventPostDestroyRefresh: true, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + CheckDestroy: testAccMetalProjectSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccDataSourceMetalProjectSSHKeyConfig_bySearch(keyName, publicKeyMaterial), @@ -58,10 +62,10 @@ func TestAccDataSourceMetalProjectSSHKeyDataSource_yID(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, PreventPostDestroyRefresh: true, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + CheckDestroy: testAccMetalProjectSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccDataSourceMetalProjectSSHKeyDataSourceConfig_byID(keyName, publicKeyMaterial), diff --git a/equinix/metal_project_ssh_key/resource.go b/equinix/metal_project_ssh_key/resource.go new file mode 100644 index 000000000..4c1679408 --- /dev/null +++ b/equinix/metal_project_ssh_key/resource.go @@ -0,0 +1,26 @@ +package metal_project_ssh_key + +import ( + "github.com/equinix/terraform-provider-equinix/equinix/metal_ssh_key" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func Resource() *schema.Resource { + pkeySchema := metal_ssh_key.MetalSSHKeyCommonFields() + pkeySchema["project_id"] = &schema.Schema{ + Type: schema.TypeString, + Description: "The ID of parent project", + ForceNew: true, + Required: true, + } + return &schema.Resource{ + Create: metal_ssh_key.ResourceMetalSSHKeyCreate, + Read: metal_ssh_key.ResourceMetalSSHKeyRead, + Update: metal_ssh_key.ResourceMetalSSHKeyUpdate, + Delete: metal_ssh_key.ResourceMetalSSHKeyDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: pkeySchema, + } +} diff --git a/equinix/resource_metal_project_ssh_key_acc_test.go b/equinix/metal_project_ssh_key/resource_test.go similarity index 76% rename from equinix/resource_metal_project_ssh_key_acc_test.go rename to equinix/metal_project_ssh_key/resource_test.go index d8553f751..3632f9da9 100644 --- a/equinix/resource_metal_project_ssh_key_acc_test.go +++ b/equinix/metal_project_ssh_key/resource_test.go @@ -1,4 +1,5 @@ -package equinix +package metal_project_ssh_key_test + import ( "fmt" @@ -7,7 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/equinix/terraform-provider-equinix/equinix/acceptance" "github.com/packethost/packngo" + "github.com/equinix/terraform-provider-equinix/equinix/internal" ) func testAccMetalProjectSSHKeyConfig_basic(name, publicSshKey string) string { @@ -35,7 +38,13 @@ resource "equinix_metal_device" "test" { termination_time = "%s" } -`, confAccMetalDevice_base(preferable_plans, preferable_metros, preferable_os), name, publicSshKey, testDeviceTerminationTime()) +`, acceptance.ConfAccMetalDevice_base( + acceptance.Preferable_plans, + acceptance.Preferable_metros, + acceptance.Preferable_os), + name, + publicSshKey, + acceptance.TestDeviceTerminationTime()) } func TestAccMetalProjectSSHKey_basic(t *testing.T) { @@ -48,15 +57,15 @@ func TestAccMetalProjectSSHKey_basic(t *testing.T) { cfg := testAccMetalProjectSSHKeyConfig_basic(rs, publicKeyMaterial) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + ExternalProviders: acceptance.TestExternalProviders, + Providers: acceptance.TestAccProviders, CheckDestroy: testAccMetalProjectSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: cfg, Check: resource.ComposeTestCheckFunc( - testAccCheckMetalSSHKeyExists("equinix_metal_project_ssh_key.test", &key), + acceptance.TestAccCheckMetalSSHKeyExists("equinix_metal_project_ssh_key.test", &key), resource.TestCheckResourceAttr( "equinix_metal_project_ssh_key.test", "public_key", publicKeyMaterial), resource.TestCheckResourceAttrPair( @@ -74,7 +83,7 @@ func TestAccMetalProjectSSHKey_basic(t *testing.T) { } func testAccMetalProjectSSHKeyCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := acceptance.TestAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_project_ssh_key" { diff --git a/equinix/resource_metal_ssh_key.go b/equinix/metal_ssh_key/resource.go similarity index 65% rename from equinix/resource_metal_ssh_key.go rename to equinix/metal_ssh_key/resource.go index 49000d967..9b0ce7919 100644 --- a/equinix/resource_metal_ssh_key.go +++ b/equinix/metal_ssh_key/resource.go @@ -1,4 +1,4 @@ -package equinix +package metal_ssh_key import ( "log" @@ -7,9 +7,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/packethost/packngo" + + "github.com/equinix/terraform-provider-equinix/equinix/internal" ) -func metalSSHKeyCommonFields() map[string]*schema.Schema { +func MetalSSHKeyCommonFields() map[string]*schema.Schema { return map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -48,23 +50,23 @@ func metalSSHKeyCommonFields() map[string]*schema.Schema { } } -func resourceMetalSSHKey() *schema.Resource { +func Resource() *schema.Resource { return &schema.Resource{ - Create: resourceMetalSSHKeyCreate, - Read: resourceMetalSSHKeyRead, - Update: resourceMetalSSHKeyUpdate, - Delete: resourceMetalSSHKeyDelete, + Create: ResourceMetalSSHKeyCreate, + Read: ResourceMetalSSHKeyRead, + Update: ResourceMetalSSHKeyUpdate, + Delete: ResourceMetalSSHKeyDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, - Schema: metalSSHKeyCommonFields(), + Schema: MetalSSHKeyCommonFields(), } } -func resourceMetalSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal +func ResourceMetalSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal createRequest := &packngo.SSHKeyCreateRequest{ Label: d.Get("name").(string), @@ -78,25 +80,25 @@ func resourceMetalSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { key, _, err := client.SSHKeys.Create(createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(key.ID) - return resourceMetalSSHKeyRead(d, meta) + return ResourceMetalSSHKeyRead(d, meta) } -func resourceMetalSSHKeyRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal +func ResourceMetalSSHKeyRead(d *schema.ResourceData, meta interface{}) error { + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal key, _, err := client.SSHKeys.Get(d.Id(), nil) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the key is somehow already destroyed, mark as // succesfully gone - if isNotFound(err) { + if internal.IsNotFound(err) { log.Printf("[WARN] SSHKey (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -122,9 +124,9 @@ func resourceMetalSSHKeyRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceMetalSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal +func ResourceMetalSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error { + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal updateRequest := &packngo.SSHKeyUpdateRequest{} @@ -140,19 +142,19 @@ func resourceMetalSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error { _, _, err := client.SSHKeys.Update(d.Id(), updateRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } - return resourceMetalSSHKeyRead(d, meta) + return ResourceMetalSSHKeyRead(d, meta) } -func resourceMetalSSHKeyDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal +func ResourceMetalSSHKeyDelete(d *schema.ResourceData, meta interface{}) error { + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.SSHKeys.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } d.SetId("") diff --git a/equinix/resource_metal_ssh_key_acc_test.go b/equinix/metal_ssh_key/resource_test.go similarity index 74% rename from equinix/resource_metal_ssh_key_acc_test.go rename to equinix/metal_ssh_key/resource_test.go index f2b07f113..e6a1a2514 100644 --- a/equinix/resource_metal_ssh_key_acc_test.go +++ b/equinix/metal_ssh_key/resource_test.go @@ -1,4 +1,4 @@ -package equinix +package metal_ssh_key_test import ( "fmt" @@ -6,6 +6,8 @@ import ( "net/http" "testing" + "github.com/equinix/terraform-provider-equinix/equinix/acceptance" + "github.com/equinix/terraform-provider-equinix/equinix/internal" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" @@ -21,7 +23,7 @@ func init() { func testSweepSSHKeys(region string) error { log.Printf("[DEBUG] Sweeping ssh keys") - config, err := sharedConfigForRegion(region) + config, err := acceptance.GetConfigForNonStandardMetalTest() if err != nil { return fmt.Errorf("[INFO][SWEEPER_LOG] Error getting configuration for sweeping ssh keys: %s", err) } @@ -32,7 +34,7 @@ func testSweepSSHKeys(region string) error { } ids := []string{} for _, k := range sshkeys { - if isSweepableTestResource(k.Label) { + if acceptance.IsSweepableTestResource(k.Label) { ids = append(ids, k.ID) } } @@ -55,15 +57,14 @@ func TestAccMetalSSHKey_basic(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, + CheckDestroy: testAccMetalSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccMetalSSHKeyConfig_basic(rInt, publicKeyMaterial), Check: resource.ComposeTestCheckFunc( - testAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), + acceptance.TestAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), resource.TestCheckResourceAttr( "equinix_metal_ssh_key.foobar", "name", fmt.Sprintf("tfacc-user-key-%d", rInt)), resource.TestCheckResourceAttr( @@ -84,10 +85,9 @@ func TestAccMetalSSHKey_projectBasic(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, + CheckDestroy: testAccMetalSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccCheckMetalSSHKeyConfig_projectBasic(rInt, publicKeyMaterial), @@ -111,15 +111,14 @@ func TestAccMetalSSHKey_update(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, + CheckDestroy: testAccMetalSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccMetalSSHKeyConfig_basic(rInt, publicKeyMaterial), Check: resource.ComposeTestCheckFunc( - testAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), + acceptance.TestAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), resource.TestCheckResourceAttr( "equinix_metal_ssh_key.foobar", "name", fmt.Sprintf("tfacc-user-key-%d", rInt)), resource.TestCheckResourceAttr( @@ -129,7 +128,7 @@ func TestAccMetalSSHKey_update(t *testing.T) { { Config: testAccMetalSSHKeyConfig_basic(rInt+1, publicKeyMaterial), Check: resource.ComposeTestCheckFunc( - testAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), + acceptance.TestAccCheckMetalSSHKeyExists("equinix_metal_ssh_key.foobar", &key), resource.TestCheckResourceAttr( "equinix_metal_ssh_key.foobar", "name", fmt.Sprintf("tfacc-user-key-%d", rInt+1)), resource.TestCheckResourceAttr( @@ -146,10 +145,9 @@ func TestAccMetalSSHKey_projectImportBasic(t *testing.T) { t.Fatalf("Cannot generate test SSH key pair: %s", err) } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, + CheckDestroy: testAccMetalSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccCheckMetalSSHKeyConfig_projectBasic(acctest.RandInt(), sshKey), @@ -169,10 +167,9 @@ func TestAccMetalSSHKey_importBasic(t *testing.T) { t.Fatalf("Cannot generate test SSH key pair: %s", err) } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ExternalProviders: testExternalProviders, - Providers: testAccProviders, - CheckDestroy: testAccMetalSSHKeyCheckDestroyed, + PreCheck: func() { acceptance.TestAccPreCheckMetal(t) }, + Providers: acceptance.TestAccProviders, + CheckDestroy: testAccMetalSSHKeyCheckDestroyed, Steps: []resource.TestStep{ { Config: testAccMetalSSHKeyConfig_basic(acctest.RandInt(), sshKey), @@ -187,47 +184,6 @@ func TestAccMetalSSHKey_importBasic(t *testing.T) { }) } -func testAccMetalSSHKeyCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal - - for _, rs := range s.RootModule().Resources { - if rs.Type != "equinix_metal_ssh_key" { - continue - } - if _, _, err := client.SSHKeys.Get(rs.Primary.ID, nil); err == nil { - return fmt.Errorf("Metal SSH key still exists") - } - } - - return nil -} - -func testAccCheckMetalSSHKeyExists(n string, key *packngo.SSHKey) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - if rs.Primary.ID == "" { - return fmt.Errorf("No Record ID is set") - } - - client := testAccProvider.Meta().(*Config).metal - - foundKey, _, err := client.SSHKeys.Get(rs.Primary.ID, nil) - if err != nil { - return err - } - if foundKey.ID != rs.Primary.ID { - return fmt.Errorf("SSh Key not found: %v - %v", rs.Primary.ID, foundKey) - } - - *key = *foundKey - - return nil - } -} - func testAccMetalSSHKeyConfig_basic(rInt int, publicSshKey string) string { return fmt.Sprintf(` resource "equinix_metal_ssh_key" "foobar" { @@ -249,3 +205,18 @@ resource "equinix_metal_project_ssh_key" "foobar" { project_id = equinix_metal_project.test.id }`, rInt, rInt, publicSshKey) } + +func testAccMetalSSHKeyCheckDestroyed(s *terraform.State) error { + client := acceptance.TestAccProvider.Meta().(*internal.Config).Metal + + for _, rs := range s.RootModule().Resources { + if rs.Type != "equinix_metal_ssh_key" { + continue + } + if _, _, err := client.SSHKeys.Get(rs.Primary.ID, nil); err == nil { + return fmt.Errorf("Metal SSH key still exists") + } + } + + return nil +} diff --git a/equinix/provider.go b/equinix/provider.go index d8eda438f..58d3d8758 100644 --- a/equinix/provider.go +++ b/equinix/provider.go @@ -15,10 +15,15 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + + "github.com/equinix/terraform-provider-equinix/equinix/internal" + + "github.com/equinix/terraform-provider-equinix/equinix/metal_project_ssh_key" + "github.com/equinix/terraform-provider-equinix/equinix/metal_ssh_key" ) var ( - metalMutexKV = NewMutexKV() + metalMutexKV = internal.NewMutexKV() DeviceNetworkTypes = []string{"layer3", "hybrid", "layer2-individual", "layer2-bonded"} DeviceNetworkTypesHB = []string{"layer3", "hybrid", "hybrid-bonded", "layer2-individual", "layer2-bonded"} NetworkTypeList = strings.Join(DeviceNetworkTypes, ", ") @@ -26,12 +31,12 @@ var ( ) const ( - endpointEnvVar = "EQUINIX_API_ENDPOINT" - clientIDEnvVar = "EQUINIX_API_CLIENTID" - clientSecretEnvVar = "EQUINIX_API_CLIENTSECRET" - clientTokenEnvVar = "EQUINIX_API_TOKEN" - clientTimeoutEnvVar = "EQUINIX_API_TIMEOUT" - metalAuthTokenEnvVar = "METAL_AUTH_TOKEN" + EndpointEnvVar = "EQUINIX_API_ENDPOINT" + ClientIDEnvVar = "EQUINIX_API_CLIENTID" + ClientSecretEnvVar = "EQUINIX_API_CLIENTSECRET" + ClientTokenEnvVar = "EQUINIX_API_TOKEN" + ClientTimeoutEnvVar = "EQUINIX_API_TIMEOUT" + MetalAuthTokenEnvVar = "METAL_AUTH_TOKEN" ) // resourceDataProvider provies interface to schema.ResourceData @@ -50,40 +55,40 @@ func Provider() *schema.Provider { "endpoint": { Type: schema.TypeString, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(endpointEnvVar, DefaultBaseURL), + DefaultFunc: schema.EnvDefaultFunc(EndpointEnvVar, internal.DefaultBaseURL), ValidateFunc: validation.IsURLWithHTTPorHTTPS, - Description: fmt.Sprintf("The Equinix API base URL to point out desired environment. Defaults to %s", DefaultBaseURL), + Description: fmt.Sprintf("The Equinix API base URL to point out desired environment. Defaults to %s", internal.DefaultBaseURL), }, "client_id": { Type: schema.TypeString, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(clientIDEnvVar, ""), + DefaultFunc: schema.EnvDefaultFunc(ClientIDEnvVar, ""), Description: "API Consumer Key available under My Apps section in developer portal", }, "client_secret": { Type: schema.TypeString, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(clientSecretEnvVar, ""), + DefaultFunc: schema.EnvDefaultFunc(ClientSecretEnvVar, ""), Description: "API Consumer secret available under My Apps section in developer portal", }, "token": { Type: schema.TypeString, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(clientTokenEnvVar, ""), + DefaultFunc: schema.EnvDefaultFunc(ClientTokenEnvVar, ""), Description: "API token from the developer sandbox", }, "auth_token": { Type: schema.TypeString, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(metalAuthTokenEnvVar, ""), + DefaultFunc: schema.EnvDefaultFunc(MetalAuthTokenEnvVar, ""), Description: "The Equinix Metal API auth key for API operations", }, "request_timeout": { Type: schema.TypeInt, Optional: true, - DefaultFunc: schema.EnvDefaultFunc(clientTimeoutEnvVar, DefaultTimeout), + DefaultFunc: schema.EnvDefaultFunc(ClientTimeoutEnvVar, internal.DefaultTimeout), ValidateFunc: validation.IntAtLeast(1), - Description: fmt.Sprintf("The duration of time, in seconds, that the Equinix Platform API Client should wait before canceling an API request. Defaults to %d", DefaultTimeout), + Description: fmt.Sprintf("The duration of time, in seconds, that the Equinix Platform API Client should wait before canceling an API request. Defaults to %d", internal.DefaultTimeout), }, "response_max_page_size": { Type: schema.TypeInt, @@ -134,7 +139,7 @@ func Provider() *schema.Provider { "equinix_metal_plans": dataSourceMetalPlans(), "equinix_metal_port": dataSourceMetalPort(), "equinix_metal_project": dataSourceMetalProject(), - "equinix_metal_project_ssh_key": dataSourceMetalProjectSSHKey(), + "equinix_metal_project_ssh_key": metal_project_ssh_key.DataSource(), "equinix_metal_reserved_ip_block": dataSourceMetalReservedIPBlock(), "equinix_metal_spot_market_request": dataSourceMetalSpotMarketRequest(), "equinix_metal_virtual_circuit": dataSourceMetalVirtualCircuit(), @@ -161,10 +166,10 @@ func Provider() *schema.Provider { "equinix_metal_connection": resourceMetalConnection(), "equinix_metal_device": resourceMetalDevice(), "equinix_metal_device_network_type": resourceMetalDeviceNetworkType(), - "equinix_metal_ssh_key": resourceMetalSSHKey(), + "equinix_metal_ssh_key": metal_ssh_key.Resource(), "equinix_metal_organization_member": resourceMetalOrganizationMember(), "equinix_metal_port": resourceMetalPort(), - "equinix_metal_project_ssh_key": resourceMetalProjectSSHKey(), + "equinix_metal_project_ssh_key": metal_project_ssh_key.Resource(), "equinix_metal_project": resourceMetalProject(), "equinix_metal_organization": resourceMetalOrganization(), "equinix_metal_reserved_ip_block": resourceMetalReservedIPBlock(), @@ -191,15 +196,11 @@ func Provider() *schema.Provider { return provider } -type providerMeta struct { - ModuleName string `cty:"module_name"` -} - func configureProvider(ctx context.Context, d *schema.ResourceData, p *schema.Provider) (interface{}, diag.Diagnostics) { mrws := d.Get("max_retry_wait_seconds").(int) rt := d.Get("request_timeout").(int) - config := Config{ + config := internal.Config{ AuthToken: d.Get("auth_token").(string), BaseURL: d.Get("endpoint").(string), ClientID: d.Get("client_id").(string), @@ -210,16 +211,16 @@ func configureProvider(ctx context.Context, d *schema.ResourceData, p *schema.Pr MaxRetries: d.Get("max_retries").(int), MaxRetryWait: time.Duration(mrws) * time.Second, } - meta := providerMeta{} + meta := internal.ProviderMeta{} if err := d.GetProviderMeta(&meta); err != nil { return nil, diag.FromErr(err) } - config.terraformVersion = p.TerraformVersion - if config.terraformVersion == "" { + config.TerraformVersion = p.TerraformVersion + if config.TerraformVersion == "" { // Terraform 0.12 introduced this field to the protocol // We can therefore assume that if it's missing it's 0.10 or 0.11 - config.terraformVersion = "0.11+compatible" + config.TerraformVersion = "0.11+compatible" } stopCtx, ok := schema.StopContext(ctx) @@ -239,35 +240,6 @@ var resourceDefaultTimeouts = &schema.ResourceTimeout{ Default: schema.DefaultTimeout(60 * time.Minute), } -func expandListToStringList(list []interface{}) []string { - result := make([]string, len(list)) - for i, v := range list { - result[i] = fmt.Sprint(v) - } - return result -} - -func expandListToInt32List(list []interface{}) []int32 { - result := make([]int32, len(list)) - for i, v := range list { - result[i] = int32(v.(int)) - } - return result -} - -func expandSetToStringList(set *schema.Set) []string { - list := set.List() - return expandListToStringList(list) -} - -func expandInterfaceMapToStringMap(mapIn map[string]interface{}) map[string]string { - mapOut := make(map[string]string) - for k, v := range mapIn { - mapOut[k] = fmt.Sprintf("%v", v) - } - return mapOut -} - func hasApplicationErrorCode(errors []rest.ApplicationError, code string) bool { for _, err := range errors { if err.Code == code { diff --git a/equinix/provider_test.go b/equinix/provider_test.go index 27f650dcb..e2797b36f 100644 --- a/equinix/provider_test.go +++ b/equinix/provider_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "net/http" "os" @@ -160,7 +161,7 @@ func TestProvider_hasApplicationErrorCode(t *testing.T) { // when result := hasApplicationErrorCode(errors, code) // then - assert.True(t, result, "Error list contains error with given code") + assert.True(t, result, "Error list internal.Contains error with given code") } func TestProvider_stringsFound(t *testing.T) { @@ -378,7 +379,7 @@ func TestProvider_schemaSetToMap(t *testing.T) { } setFunc := func(v interface{}) int { i := v.(item) - return hashcodeString(i.id) + return internal.HashcodeString(i.id) } items := []interface{}{ item{"id1", 100, 200}, @@ -401,20 +402,20 @@ func TestProvider_schemaSetToMap(t *testing.T) { func testAccPreCheck(t *testing.T) { var err error - if _, err = getFromEnv(clientTokenEnvVar); err != nil { - _, err = getFromEnv(clientIDEnvVar) + if _, err = getFromEnv(ClientTokenEnvVar); err != nil { + _, err = getFromEnv(ClientIDEnvVar) if err == nil { - _, err = getFromEnv(clientSecretEnvVar) + _, err = getFromEnv(ClientSecretEnvVar) } } if err == nil { - _, err = getFromEnv(metalAuthTokenEnvVar) + _, err = getFromEnv(MetalAuthTokenEnvVar) } if err != nil { t.Fatalf("To run acceptance tests, one of '%s' or pair '%s' - '%s' must be set for Equinix Fabric and Network Edge, and '%s' for Equinix Metal", - clientTokenEnvVar, clientIDEnvVar, clientSecretEnvVar, metalAuthTokenEnvVar) + ClientTokenEnvVar, ClientIDEnvVar, ClientSecretEnvVar, MetalAuthTokenEnvVar) } } diff --git a/equinix/resource_ecx_l2_connection.go b/equinix/resource_ecx_l2_connection.go index 5dd66df6e..6fedd55d3 100644 --- a/equinix/resource_ecx_l2_connection.go +++ b/equinix/resource_ecx_l2_connection.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -658,8 +659,8 @@ func createECXL2ConnectionActionsRequiredDataSchema() map[string]*schema.Schema } func resourceECXL2ConnectionCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics primary, secondary := createECXL2Connections(d) @@ -696,8 +697,8 @@ func resourceECXL2ConnectionCreate(ctx context.Context, d *schema.ResourceData, } func resourceECXL2ConnectionRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics var err error var primary *ecx.L2Connection @@ -741,8 +742,8 @@ func resourceECXL2ConnectionRead(ctx context.Context, d *schema.ResourceData, m } func resourceECXL2ConnectionUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics supportedChanges := []string{ ecxL2ConnectionSchemaNames["Name"], @@ -766,8 +767,8 @@ func resourceECXL2ConnectionUpdate(ctx context.Context, d *schema.ResourceData, } func resourceECXL2ConnectionDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics if err := client.DeleteL2Connection(d.Id()); err != nil { @@ -822,7 +823,7 @@ func createECXL2Connections(d *schema.ResourceData) (*ecx.L2Connection, *ecx.L2C primary.SpeedUnit = ecx.String(v.(string)) } if v, ok := d.GetOk(ecxL2ConnectionSchemaNames["Notifications"]); ok { - primary.Notifications = expandSetToStringList(v.(*schema.Set)) + primary.Notifications = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(ecxL2ConnectionSchemaNames["PurchaseOrderNumber"]); ok { primary.PurchaseOrderNumber = ecx.String(v.(string)) diff --git a/equinix/resource_ecx_l2_connection_acc_test.go b/equinix/resource_ecx_l2_connection_acc_test.go index 8fe2cbbe2..520ba94a0 100644 --- a/equinix/resource_ecx_l2_connection_acc_test.go +++ b/equinix/resource_ecx_l2_connection_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -44,7 +45,7 @@ func testSweepECXL2Connections(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - conns, err := config.ecx.GetL2OutgoingConnections([]string{ + conns, err := config.Ecx.GetL2OutgoingConnections([]string{ ecx.ConnectionStatusNotAvailable, ecx.ConnectionStatusPendingAutoApproval, ecx.ConnectionStatusPendingBGPPeering, @@ -62,7 +63,7 @@ func testSweepECXL2Connections(region string) error { nonSweepableCount++ continue } - if err := config.ecx.DeleteL2Connection(ecx.StringValue(conn.UUID)); err != nil { + if err := config.Ecx.DeleteL2Connection(ecx.StringValue(conn.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting ECXL2Connection resource %s (%s): %s", ecx.StringValue(conn.UUID), ecx.StringValue(conn.Name), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for ECXL2Connection resource %s (%s)", ecx.StringValue(conn.UUID), ecx.StringValue(conn.Name)) @@ -363,8 +364,8 @@ func TestAccFabricL2Connection_ServiceToken_HA_SP(t *testing.T) { } mockEquinix := Provider() mockEquinix.ConfigureContextFunc = func(c context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { - config := Config{ - ecx: mockECXClient, + config := internal.Config{ + Ecx: mockECXClient, } return &config, nil } @@ -496,8 +497,8 @@ func TestAccFabricL2Connection_ZSideServiceToken_Single(t *testing.T) { } mockEquinix := Provider() mockEquinix.ConfigureContextFunc = func(c context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { - config := Config{ - ecx: mockECXClient, + config := internal.Config{ + Ecx: mockECXClient, } return &config, nil } @@ -540,7 +541,7 @@ func testAccFabricL2ConnectionExists(resourceName string, conn *ecx.L2Connection if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ecx + client := testAccProvider.Meta().(*internal.Config).Ecx if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } @@ -563,7 +564,7 @@ func testAccFabricL2ConnectionSecondaryExists(resourceName string, conn *ecx.L2C if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ecx + client := testAccProvider.Meta().(*internal.Config).Ecx if connID, ok := rs.Primary.Attributes["secondary_connection.0.uuid"]; ok { resp, err := client.GetL2Connection(connID) diff --git a/equinix/resource_ecx_l2_connection_test.go b/equinix/resource_ecx_l2_connection_test.go index 219ee7db7..fa7897203 100644 --- a/equinix/resource_ecx_l2_connection_test.go +++ b/equinix/resource_ecx_l2_connection_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -111,7 +112,7 @@ func TestFabricL2Connection_updateResourceData(t *testing.T) { assert.Equal(t, ecx.StringValue(input.SpeedUnit), d.Get(ecxL2ConnectionSchemaNames["SpeedUnit"]), "SpeedUnit matches") assert.Equal(t, ecx.StringValue(input.Status), d.Get(ecxL2ConnectionSchemaNames["Status"]), "Status matches") assert.Equal(t, ecx.StringValue(input.ProviderStatus), d.Get(ecxL2ConnectionSchemaNames["ProviderStatus"]), "ProviderStatus matches") - assert.Equal(t, input.Notifications, expandSetToStringList(d.Get(ecxL2ConnectionSchemaNames["Notifications"]).(*schema.Set)), "Notifications matches") + assert.Equal(t, input.Notifications, internal.ExpandSetToStringList(d.Get(ecxL2ConnectionSchemaNames["Notifications"]).(*schema.Set)), "Notifications matches") assert.Equal(t, ecx.StringValue(input.PurchaseOrderNumber), d.Get(ecxL2ConnectionSchemaNames["PurchaseOrderNumber"]), "PurchaseOrderNumber matches") assert.Equal(t, ecx.StringValue(input.PortUUID), d.Get(ecxL2ConnectionSchemaNames["PortUUID"]), "PortUUID matches") assert.Equal(t, ecx.StringValue(input.DeviceUUID), d.Get(ecxL2ConnectionSchemaNames["DeviceUUID"]), "DeviceUUID matches") diff --git a/equinix/resource_ecx_l2_serviceprofile.go b/equinix/resource_ecx_l2_serviceprofile.go index ae8465b26..4ebb9ccc9 100644 --- a/equinix/resource_ecx_l2_serviceprofile.go +++ b/equinix/resource_ecx_l2_serviceprofile.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" @@ -341,8 +342,8 @@ func createECXL2ServiceProfileResourceSchema() map[string]*schema.Schema { } func resourceECXL2ServiceProfileCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics profile := createECXL2ServiceProfile(d) uuid, err := client.CreateL2ServiceProfile(*profile) @@ -355,8 +356,8 @@ func resourceECXL2ServiceProfileCreate(ctx context.Context, d *schema.ResourceDa } func resourceECXL2ServiceProfileRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics profile, err := client.GetL2ServiceProfile(d.Id()) if err != nil { @@ -369,8 +370,8 @@ func resourceECXL2ServiceProfileRead(ctx context.Context, d *schema.ResourceData } func resourceECXL2ServiceProfileUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics profile := createECXL2ServiceProfile(d) if err := client.UpdateL2ServiceProfile(*profile); err != nil { @@ -381,8 +382,8 @@ func resourceECXL2ServiceProfileUpdate(ctx context.Context, d *schema.ResourceDa } func resourceECXL2ServiceProfileDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ecx - m.(*Config).addModuleToECXUserAgent(&client, d) + client := m.(*internal.Config).Ecx + m.(*internal.Config).AddModuleToECXUserAgent(&client, d) var diags diag.Diagnostics if err := client.DeleteL2ServiceProfile(d.Id()); err != nil { restErr, ok := err.(rest.Error) @@ -442,13 +443,13 @@ func createECXL2ServiceProfile(d *schema.ResourceData) *ecx.L2ServiceProfile { profile.Name = ecx.String(v.(string)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["OnBandwidthThresholdNotification"]); ok { - profile.OnBandwidthThresholdNotification = expandSetToStringList(v.(*schema.Set)) + profile.OnBandwidthThresholdNotification = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["OnProfileApprovalRejectNotification"]); ok { - profile.OnProfileApprovalRejectNotification = expandSetToStringList(v.(*schema.Set)) + profile.OnProfileApprovalRejectNotification = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["OnVcApprovalRejectionNotification"]); ok { - profile.OnVcApprovalRejectionNotification = expandSetToStringList(v.(*schema.Set)) + profile.OnVcApprovalRejectionNotification = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["OverSubscription"]); ok { profile.OverSubscription = ecx.String(v.(string)) @@ -457,7 +458,7 @@ func createECXL2ServiceProfile(d *schema.ResourceData) *ecx.L2ServiceProfile { profile.Private = ecx.Bool(v.(bool)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["PrivateUserEmails"]); ok { - profile.PrivateUserEmails = expandSetToStringList(v.(*schema.Set)) + profile.PrivateUserEmails = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["RequiredRedundancy"]); ok { profile.RequiredRedundancy = ecx.Bool(v.(bool)) @@ -547,7 +548,7 @@ func updateECXL2ServiceProfileResource(profile *ecx.L2ServiceProfile, d *schema. // API accepts capitalizations of the private user emails and converts it to a lowercase string // If API retuns same emails in lowercase we keep to suppress diff if v, ok := d.GetOk(ecxL2ServiceProfileSchemaNames["PrivateUserEmails"]); ok { - prevPrivateUserEmails := expandSetToStringList(v.(*schema.Set)) + prevPrivateUserEmails := internal.ExpandSetToStringList(v.(*schema.Set)) if slicesMatchCaseInsensitive(prevPrivateUserEmails, profile.PrivateUserEmails) { profile.PrivateUserEmails = prevPrivateUserEmails } diff --git a/equinix/resource_ecx_l2_serviceprofile_acc_test.go b/equinix/resource_ecx_l2_serviceprofile_acc_test.go index 7f5d8a05b..62f0bb3b7 100644 --- a/equinix/resource_ecx_l2_serviceprofile_acc_test.go +++ b/equinix/resource_ecx_l2_serviceprofile_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -62,7 +63,7 @@ func testAccECXL2ServiceProfileExists(resourceName string, profile *ecx.L2Servic if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ecx + client := testAccProvider.Meta().(*internal.Config).Ecx if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_ecx_l2_serviceprofile_test.go b/equinix/resource_ecx_l2_serviceprofile_test.go index 8cb59a4ee..8a810f3d9 100644 --- a/equinix/resource_ecx_l2_serviceprofile_test.go +++ b/equinix/resource_ecx_l2_serviceprofile_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "testing" "github.com/equinix/ecx-go/v2" @@ -167,12 +168,12 @@ func TestFabricL2ServiceProfile_updateResourceData(t *testing.T) { assert.Equal(t, ecx.BoolValue(input.EquinixManagedPortAndVlan), d.Get(ecxL2ServiceProfileSchemaNames["EquinixManagedPortAndVlan"]), "EquinixManagedPortAndVlan matches") assert.Equal(t, ecx.StringValue(input.IntegrationID), d.Get(ecxL2ServiceProfileSchemaNames["IntegrationID"]), "IntegrationID matches") assert.Equal(t, ecx.StringValue(input.Name), d.Get(ecxL2ServiceProfileSchemaNames["Name"]), "Name matches") - assert.Equal(t, input.OnBandwidthThresholdNotification, expandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnBandwidthThresholdNotification"]).(*schema.Set)), "OnBandwidthThresholdNotification matches") - assert.Equal(t, input.OnProfileApprovalRejectNotification, expandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnProfileApprovalRejectNotification"]).(*schema.Set)), "OnProfileApprovalRejectNotification matches") - assert.Equal(t, input.OnVcApprovalRejectionNotification, expandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnVcApprovalRejectionNotification"]).(*schema.Set)), "OnVcApprovalRejectionNotification matches") + assert.Equal(t, input.OnBandwidthThresholdNotification, internal.ExpandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnBandwidthThresholdNotification"]).(*schema.Set)), "OnBandwidthThresholdNotification matches") + assert.Equal(t, input.OnProfileApprovalRejectNotification, internal.ExpandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnProfileApprovalRejectNotification"]).(*schema.Set)), "OnProfileApprovalRejectNotification matches") + assert.Equal(t, input.OnVcApprovalRejectionNotification, internal.ExpandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["OnVcApprovalRejectionNotification"]).(*schema.Set)), "OnVcApprovalRejectionNotification matches") assert.Equal(t, ecx.StringValue(input.OverSubscription), d.Get(ecxL2ServiceProfileSchemaNames["OverSubscription"]), "OverSubscription matches") assert.Equal(t, ecx.BoolValue(input.Private), d.Get(ecxL2ServiceProfileSchemaNames["Private"]), "Private matches") - assert.Equal(t, input.PrivateUserEmails, expandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["PrivateUserEmails"]).(*schema.Set)), "PrivateUserEmails matches") + assert.Equal(t, input.PrivateUserEmails, internal.ExpandSetToStringList(d.Get(ecxL2ServiceProfileSchemaNames["PrivateUserEmails"]).(*schema.Set)), "PrivateUserEmails matches") assert.Equal(t, ecx.BoolValue(input.RequiredRedundancy), d.Get(ecxL2ServiceProfileSchemaNames["RequiredRedundancy"]), "RequiredRedundancy matches") assert.Equal(t, ecx.BoolValue(input.SpeedFromAPI), d.Get(ecxL2ServiceProfileSchemaNames["SpeedFromAPI"]), "SpeedFromAPI matches") assert.Equal(t, ecx.StringValue(input.TagType), d.Get(ecxL2ServiceProfileSchemaNames["TagType"]), "TagType matches") diff --git a/equinix/resource_fabric_cloud_router.go b/equinix/resource_fabric_cloud_router.go old mode 100755 new mode 100644 index ed67ab8bb..015a0a233 --- a/equinix/resource_fabric_cloud_router.go +++ b/equinix/resource_fabric_cloud_router.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -35,8 +36,8 @@ func resourceCloudRouter() *schema.Resource { } func resourceCloudRouterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) schemaNotifications := d.Get("notifications").([]interface{}) notifications := notificationToFabric(schemaNotifications) schemaAccount := d.Get("account").(*schema.Set).List() @@ -80,8 +81,8 @@ func resourceCloudRouterCreate(ctx context.Context, d *schema.ResourceData, meta } func resourceCloudRouterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) CloudRouter, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, d.Id()) if err != nil { log.Printf("[WARN] Fabric Cloud Router %s not found , error %s", d.Id(), err) @@ -115,8 +116,8 @@ func setCloudRouterMap(d *schema.ResourceData, fcr v4.CloudRouter) diag.Diagnost } func resourceCloudRouterUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) dbConn, err := waitUntilCloudRouterIsProvisioned(d.Id(), meta, ctx) if err != nil { if !strings.Contains(err.Error(), "500") { @@ -153,7 +154,7 @@ func waitForCloudRouterUpdateCompletion(uuid string, meta interface{}, ctx conte stateConf := &resource.StateChangeConf{ Target: []string{string(v4.PROVISIONED_CloudRouterAccessPointState)}, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid) if err != nil { return "", "", err @@ -185,7 +186,7 @@ func waitUntilCloudRouterIsProvisioned(uuid string, meta interface{}, ctx contex string(v4.PROVISIONED_CloudRouterAccessPointState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid) if err != nil { return "", "", err @@ -208,8 +209,8 @@ func waitUntilCloudRouterIsProvisioned(uuid string, meta interface{}, ctx contex func resourceCloudRouterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diags := diag.Diagnostics{} - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) resp, err := client.CloudRoutersApi.DeleteCloudRouterByUuid(ctx, d.Id()) if err != nil { errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError) @@ -239,7 +240,7 @@ func waitUntilCloudRouterDeprovisioned(uuid string, meta interface{}, ctx contex string(v4.DEPROVISIONED_CloudRouterAccessPointState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid) if err != nil { return "", "", err diff --git a/equinix/resource_fabric_cloud_router_acc_test.go b/equinix/resource_fabric_cloud_router_acc_test.go old mode 100755 new mode 100644 index a4339821b..7e362926f --- a/equinix/resource_fabric_cloud_router_acc_test.go +++ b/equinix/resource_fabric_cloud_router_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "testing" @@ -38,7 +39,7 @@ func TestAccCloudRouterCreate(t *testing.T) { func checkCloudRouterDelete(s *terraform.State) error { ctx := context.Background() - ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*Config).FabricAuthToken) + ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*internal.Config).FabricAuthToken) for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_fabric_cloud_router" { continue diff --git a/equinix/resource_fabric_connection.go b/equinix/resource_fabric_connection.go old mode 100755 new mode 100644 index 2764fe9a5..05bc688a6 --- a/equinix/resource_fabric_connection.go +++ b/equinix/resource_fabric_connection.go @@ -7,6 +7,8 @@ import ( "strings" "time" + "github.com/equinix/terraform-provider-equinix/equinix/internal" + v4 "github.com/equinix-labs/fabric-go/fabric/v4" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -35,8 +37,8 @@ func resourceFabricConnection() *schema.Resource { } func resourceFabricConnectionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) conType := v4.ConnectionType(d.Get("type").(string)) schemaNotifications := d.Get("notifications").([]interface{}) notifications := notificationToFabric(schemaNotifications) @@ -154,8 +156,8 @@ func additionalInfoContainsAWSSecrets(info []interface{}) ([]interface{}, bool) } func resourceFabricConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) conn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, d.Id(), nil) if err != nil { log.Printf("[WARN] Connection %s not found , error %s", d.Id(), err) @@ -199,8 +201,8 @@ func setFabricMap(d *schema.ResourceData, conn v4.Connection) diag.Diagnostics { } func resourceFabricConnectionUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) dbConn, err := verifyConnectionCreated(d.Id(), meta, ctx) if err != nil { if !strings.Contains(err.Error(), "500") { @@ -254,7 +256,7 @@ func waitForConnectionUpdateCompletion(uuid string, meta interface{}, ctx contex stateConf := &retry.StateChangeConf{ Target: []string{"COMPLETED"}, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil) if err != nil { return "", "", err @@ -291,7 +293,7 @@ func waitUntilConnectionIsCreated(uuid string, meta interface{}, ctx context.Con string(v4.ACTIVE_ConnectionState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil) if err != nil { return "", "", err @@ -319,7 +321,7 @@ func waitForConnectionProviderStatusChange(uuid string, meta interface{}, ctx co string(v4.PROVISIONED_ProviderStatus), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil) if err != nil { return "", "", err @@ -349,7 +351,7 @@ func verifyConnectionCreated(uuid string, meta interface{}, ctx context.Context) string(v4.PENDING_ConnectionState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil) if err != nil { return "", "", err @@ -372,8 +374,8 @@ func verifyConnectionCreated(uuid string, meta interface{}, ctx context.Context) func resourceFabricConnectionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diags := diag.Diagnostics{} - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) _, _, err := client.ConnectionsApi.DeleteConnectionByUuid(ctx, d.Id()) if err != nil { errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError) @@ -403,7 +405,7 @@ func waitUntilConnectionDeprovisioned(uuid string, meta interface{}, ctx context string(v4.DEPROVISIONED_ConnectionState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil) if err != nil { return "", "", err diff --git a/equinix/resource_fabric_connection_acc_test.go b/equinix/resource_fabric_connection_acc_test.go old mode 100755 new mode 100644 index c928c3e11..01e2899f7 --- a/equinix/resource_fabric_connection_acc_test.go +++ b/equinix/resource_fabric_connection_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "testing" @@ -72,7 +73,7 @@ func TestAccFabricCreateCloudRouterConnection(t *testing.T) { func checkConnectionDelete(s *terraform.State) error { ctx := context.Background() - ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*Config).FabricAuthToken) + ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*internal.Config).FabricAuthToken) for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_fabric_connection" { continue diff --git a/equinix/resource_fabric_port.go b/equinix/resource_fabric_port.go old mode 100755 new mode 100644 index 98f78c185..318ef7817 --- a/equinix/resource_fabric_port.go +++ b/equinix/resource_fabric_port.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "errors" "fmt" @@ -15,8 +16,8 @@ import ( ) func resourceFabricPortRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) port, _, err := client.PortsApi.GetPortByUuid(ctx, d.Id()) if err != nil { log.Printf("[WARN] Port %s not found , error %s", d.Id(), err) @@ -83,8 +84,8 @@ func resourceFabricPortGetByPortName(ctx context.Context, d *schema.ResourceData } }() - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) portNameParam := d.Get("filters").(*schema.Set).List() portName := portNameQueryParamToFabric(portNameParam) ports, _, err := client.PortsApi.GetPorts(ctx, &portName) diff --git a/equinix/resource_fabric_port_acc_test.go b/equinix/resource_fabric_port_acc_test.go old mode 100755 new mode 100644 diff --git a/equinix/resource_fabric_routing_protocol.go b/equinix/resource_fabric_routing_protocol.go index 92d04c855..598f15ef9 100644 --- a/equinix/resource_fabric_routing_protocol.go +++ b/equinix/resource_fabric_routing_protocol.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -47,8 +48,8 @@ func resourceFabricRoutingProtocol() *schema.Resource { } func resourceFabricRoutingProtocolRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) log.Printf("[WARN] Routing Protocol Connection uuid: %s", d.Get("connection_uuid").(string)) fabricRoutingProtocol, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string)) if err != nil { @@ -69,8 +70,8 @@ func resourceFabricRoutingProtocolRead(ctx context.Context, d *schema.ResourceDa } func resourceFabricRoutingProtocolCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) schemaBgpIpv4 := d.Get("bgp_ipv4").(*schema.Set).List() bgpIpv4 := routingProtocolBgpIpv4ToFabric(schemaBgpIpv4) schemaBgpIpv6 := d.Get("bgp_ipv6").(*schema.Set).List() @@ -152,8 +153,8 @@ func resourceFabricRoutingProtocolCreate(ctx context.Context, d *schema.Resource } func resourceFabricRoutingProtocolUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) /* todo: support patch bgp in the future - switch between PUT and PATCH 1. get getRoutingProtocolPatchUpdateRequest() @@ -251,8 +252,8 @@ func resourceFabricRoutingProtocolUpdate(ctx context.Context, d *schema.Resource func resourceFabricRoutingProtocolDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diags := diag.Diagnostics{} - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) _, resp, err := client.RoutingProtocolsApi.DeleteConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string)) if err != nil { errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError) @@ -324,7 +325,7 @@ func waitUntilRoutingProtocolIsProvisioned(uuid string, connUuid string, meta in string(v4.PROVISIONED_ConnectionState), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid) if err != nil { return "", "", err @@ -361,7 +362,7 @@ func waitUntilRoutingProtocolIsDeprovisioned(uuid string, connUuid string, meta strconv.Itoa(404), }, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, resp, _ := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid) // fixme: check for error code instead? // ignore error for Target @@ -382,7 +383,7 @@ func waitForRoutingProtocolUpdateCompletion(rpChangeUuid string, uuid string, co stateConf := &resource.StateChangeConf{ Target: []string{"COMPLETED"}, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolsChangeByUuid(ctx, connUuid, uuid, rpChangeUuid) if err != nil { return "", "", err diff --git a/equinix/resource_fabric_routing_protocol_acc_test.go b/equinix/resource_fabric_routing_protocol_acc_test.go index 4fc9cc5af..7d233d4e6 100644 --- a/equinix/resource_fabric_routing_protocol_acc_test.go +++ b/equinix/resource_fabric_routing_protocol_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "testing" @@ -97,7 +98,7 @@ func testAccFabricCreateRoutingProtocolBgpConfig(connectionUuid string, ipv4 str func checkRoutingProtocolDelete(s *terraform.State) error { ctx := context.Background() - ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*Config).FabricAuthToken) + ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*internal.Config).FabricAuthToken) for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_fabric_routing_protocol" { continue diff --git a/equinix/resource_fabric_service_profile.go b/equinix/resource_fabric_service_profile.go old mode 100755 new mode 100644 index a7b91524a..6e786e747 --- a/equinix/resource_fabric_service_profile.go +++ b/equinix/resource_fabric_service_profile.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "errors" "fmt" @@ -37,8 +38,8 @@ func resourceFabricServiceProfile() *schema.Resource { } func resourceFabricServiceProfileRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) serviceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, d.Id(), nil) if err != nil { if !strings.Contains(err.Error(), "500") { @@ -53,8 +54,8 @@ func resourceFabricServiceProfileRead(ctx context.Context, d *schema.ResourceDat } func resourceFabricServiceProfileCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) createRequest := getServiceProfileRequestPayload(d) sp, _, err := client.ServiceProfilesApi.CreateServiceProfile(ctx, createRequest) @@ -123,8 +124,8 @@ func getServiceProfileRequestPayload(d *schema.ResourceData) v4.ServiceProfileRe } func resourceFabricServiceProfileUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) uuid := d.Id() updateRequest := getServiceProfileRequestPayload(d) @@ -159,7 +160,7 @@ func waitForServiceProfileUpdateCompletion(uuid string, meta interface{}, ctx co stateConf := &retry.StateChangeConf{ Target: []string{"COMPLETED"}, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbServiceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid, nil) if err != nil { return "", "", err @@ -187,7 +188,7 @@ func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, c stateConf := &retry.StateChangeConf{ Target: []string{string(v4.ACTIVE_ServiceProfileStateEnum)}, Refresh: func() (interface{}, string, error) { - client := meta.(*Config).fabricClient + client := meta.(*internal.Config).FabricClient dbServiceProfile, res, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid, nil) if err != nil { return nil, "", err @@ -219,8 +220,8 @@ func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, c func resourceFabricServiceProfileDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diags := diag.Diagnostics{} - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) uuid := d.Id() if uuid == "" { return diag.Errorf("No uuid found %v ", uuid) @@ -273,8 +274,8 @@ func setFabricServiceProfilesListMap(d *schema.ResourceData, spl v4.ServiceProfi } func resourceServiceProfilesSearchRequest(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - client := meta.(*Config).fabricClient - ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*Config).FabricAuthToken) + client := meta.(*internal.Config).FabricClient + ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*internal.Config).FabricAuthToken) schemaFilter := d.Get("filter").(*schema.Set).List() filter := serviceProfilesSearchFilterRequestToFabric(schemaFilter) var serviceProfileFlt v4.ServiceProfileFilter // Cast ServiceProfile search expression struct type to interface diff --git a/equinix/resource_fabric_service_profile_acc_test.go b/equinix/resource_fabric_service_profile_acc_test.go old mode 100755 new mode 100644 index 4063958fc..ff081acaa --- a/equinix/resource_fabric_service_profile_acc_test.go +++ b/equinix/resource_fabric_service_profile_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -150,9 +151,9 @@ func testAccFabricCreateServiceProfileConfig(name string) string { } func checkServiceProfileDelete(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).fabricClient + client := testAccProvider.Meta().(*internal.Config).FabricClient ctx := context.Background() - ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*Config).FabricAuthToken) + ctx = context.WithValue(ctx, v4.ContextAccessToken, testAccProvider.Meta().(*internal.Config).FabricAuthToken) for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_fabric_service_profile" { continue diff --git a/equinix/resource_metal_bgp_session.go b/equinix/resource_metal_bgp_session.go index 122e8f9a8..ddd96064a 100644 --- a/equinix/resource_metal_bgp_session.go +++ b/equinix/resource_metal_bgp_session.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -49,8 +50,8 @@ func resourceMetalBGPSession() *schema.Resource { } func resourceMetalBGPSessionCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal dID := d.Get("device_id").(string) addressFamily := d.Get("address_family").(string) @@ -62,7 +63,7 @@ func resourceMetalBGPSessionCreate(d *schema.ResourceData, meta interface{}) err DefaultRoute: &defaultRoute, }) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(bgpSession.ID) @@ -70,14 +71,14 @@ func resourceMetalBGPSessionCreate(d *schema.ResourceData, meta interface{}) err } func resourceMetalBGPSessionRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal bgpSession, _, err := client.BGPSessions.Get(d.Id(), &packngo.GetOptions{Includes: []string{"device"}}) if err != nil { - err = friendlyError(err) - if isNotFound(err) { + err = internal.FriendlyError(err) + if internal.IsNotFound(err) { log.Printf("[WARN] BGP Session (%s) not found, removing from state", d.Id()) d.SetId("") @@ -100,8 +101,8 @@ func resourceMetalBGPSessionRead(d *schema.ResourceData, meta interface{}) error } func resourceMetalBGPSessionDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.BGPSessions.Delete(d.Id()) - return ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) + return internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) } diff --git a/equinix/resource_metal_bgp_setup_acc_test.go b/equinix/resource_metal_bgp_setup_acc_test.go index 226a7d0c2..2c3aec29a 100644 --- a/equinix/resource_metal_bgp_setup_acc_test.go +++ b/equinix/resource_metal_bgp_setup_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -52,7 +53,7 @@ func TestAccMetalBGPSetup_basic(t *testing.T) { } func testAccMetalBGPSetupCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_bgp_session" { diff --git a/equinix/resource_metal_connection.go b/equinix/resource_metal_connection.go index 91bffe376..b98561da0 100644 --- a/equinix/resource_metal_connection.go +++ b/equinix/resource_metal_connection.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "math" "reflect" @@ -89,7 +90,7 @@ func resourceMetalConnection() *schema.Resource { Description: "Metro where the connection will be created", ConflictsWith: []string{"facility"}, ForceNew: true, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "redundancy": { Type: schema.TypeString, @@ -198,8 +199,8 @@ func resourceMetalConnection() *schema.Resource { } func resourceMetalConnectionCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal facility, facOk := d.GetOk("facility") metro, metOk := d.GetOk("metro") @@ -218,7 +219,7 @@ func resourceMetalConnectionCreate(d *schema.ResourceData, meta interface{}) err vlans := []int{} vlansNum := d.Get("vlans.#").(int) if vlansNum > 0 { - vlans = convertIntArr2(d.Get("vlans").([]interface{})) + vlans = internal.ConvertIntArr2(d.Get("vlans").([]interface{})) } connRedundancy := packngo.ConnectionRedundancy(d.Get("redundancy").(string)) @@ -251,7 +252,7 @@ func resourceMetalConnectionCreate(d *schema.ResourceData, meta interface{}) err // this could be generalized, see $ grep "d.Get(\"tags" * tags := d.Get("tags.#").(int) if tags > 0 { - connReq.Tags = convertStringArr(d.Get("tags").([]interface{})) + connReq.Tags = internal.ConvertStringArr(d.Get("tags").([]interface{})) } if metOk { @@ -293,7 +294,7 @@ func resourceMetalConnectionCreate(d *schema.ResourceData, meta interface{}) err } proj, _, err := client.Projects.Get(projectId.(string), &packngo.GetOptions{Includes: []string{"organization"}}) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } organizationId = proj.Organization.ID } @@ -315,8 +316,8 @@ func resourceMetalConnectionCreate(d *schema.ResourceData, meta interface{}) err } func resourceMetalConnectionUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal if d.HasChange("locked") { var action func(string) (*packngo.Response, error) @@ -326,7 +327,7 @@ func resourceMetalConnectionUpdate(d *schema.ResourceData, meta interface{}) err action = client.Devices.Unlock } if _, err := action(d.Id()); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } ur := packngo.ConnectionUpdateRequest{} @@ -360,13 +361,13 @@ func resourceMetalConnectionUpdate(d *schema.ResourceData, meta interface{}) err } ur.Tags = sts default: - return friendlyError(fmt.Errorf("garbage in tags: %s", ts)) + return internal.FriendlyError(fmt.Errorf("garbage in tags: %s", ts)) } } if !reflect.DeepEqual(ur, packngo.ConnectionUpdateRequest{}) { if _, _, err := client.Connections.Update(d.Id(), &ur, nil); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -376,8 +377,8 @@ func resourceMetalConnectionUpdate(d *schema.ResourceData, meta interface{}) err if connType == packngo.ConnectionShared { old, new := d.GetChange("vlans") - oldVlans := convertIntArr2(old.([]interface{})) - newVlans := convertIntArr2(new.([]interface{})) + oldVlans := internal.ConvertIntArr2(old.([]interface{})) + newVlans := internal.ConvertIntArr2(new.([]interface{})) maxVlans := int(math.Max(float64(len(oldVlans)), float64(len(newVlans)))) ports := d.Get("ports").([]interface{}) @@ -387,19 +388,19 @@ func resourceMetalConnectionUpdate(d *schema.ResourceData, meta interface{}) err if i+1 > len(newVlans) { // The VNID was removed; unassign the old VNID if _, _, err := updateHiddenVirtualCircuitVNID(client, ports[i].(map[string]interface{}), ""); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } else { j := slices.Index(oldVlans, newVlans[i]) if j > i { // The VNID was moved to a different list index; unassign the VNID for the old index so that it is available for reassignment if _, _, err := updateHiddenVirtualCircuitVNID(client, ports[j].(map[string]interface{}), ""); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } // Assign the VNID (whether it is new or moved) to the correct port if _, _, err := updateHiddenVirtualCircuitVNID(client, ports[i].(map[string]interface{}), strconv.Itoa(newVlans[i])); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } } @@ -423,8 +424,8 @@ func updateHiddenVirtualCircuitVNID(client *packngo.Client, port map[string]inte } func resourceMetalConnectionRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal connId := d.Id() conn, _, err := client.Connections.Get( @@ -489,11 +490,11 @@ func resourceMetalConnectionRead(d *schema.ResourceData, meta interface{}) error } func resourceMetalConnectionDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.Connections.Delete(d.Id(), true) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } return nil } diff --git a/equinix/resource_metal_connection_acc_test.go b/equinix/resource_metal_connection_acc_test.go index 53c02592f..a1ec1ce9d 100644 --- a/equinix/resource_metal_connection_acc_test.go +++ b/equinix/resource_metal_connection_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -42,7 +43,7 @@ func TestSpeedConversion(t *testing.T) { } func testAccMetalConnectionCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_connection" { diff --git a/equinix/resource_metal_device.go b/equinix/resource_metal_device.go index 756dadc26..ea7ee778d 100644 --- a/equinix/resource_metal_device.go +++ b/equinix/resource_metal_device.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "encoding/json" "errors" @@ -87,14 +88,14 @@ func resourceMetalDevice() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { if len(old) > 0 && new == "" { // here it would be good to also test if the "old" metro - // contains the device facility. If yes, we'd suppress diff + // internal.Contains the device facility. If yes, we'd suppress diff // and if it's a different metro, we would re-create. // Not sure if this is possible. return true } return old == new }, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "facilities": { Type: schema.TypeList, @@ -106,12 +107,12 @@ func resourceMetalDevice() *schema.Resource { MinItems: 1, DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { fsRaw := d.Get("facilities") - fs := convertStringArr(fsRaw.([]interface{})) + fs := internal.ConvertStringArr(fsRaw.([]interface{})) df := d.Get("deployed_facility").(string) - if contains(fs, df) { + if internal.Contains(fs, df) { return true } - if contains(fs, "any") && (len(df) != 0) { + if internal.Contains(fs, "any") && (len(df) != 0) { return true } return false @@ -122,7 +123,7 @@ func resourceMetalDevice() *schema.Resource { Type: schema.TypeList, Description: "A list of IP address types for the device (structure is documented below)", Optional: true, - Elem: ipAddressSchema(), + Elem: internal.IpAddressSchema(), MinItems: 1, }, "plan": { @@ -397,7 +398,7 @@ func resourceMetalDevice() *schema.Resource { ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) { attribute := val.(string) supportedAttributes := []string{"custom_data", "user_data"} - if !contains(supportedAttributes, attribute) { + if !internal.Contains(supportedAttributes, attribute) { errs = []error{fmt.Errorf("behavior.allow_changes was given %s, but only supports %v", attribute, supportedAttributes)} } return @@ -459,11 +460,11 @@ func reinstallDisabledAndNoChangesAllowed(attribute string) customdiff.ResourceC behavior_list := behavior.([]interface{}) behavior_config := behavior_list[0].(map[string]interface{}) - allow_changes := convertStringArr(behavior_config["allow_changes"].([]interface{})) + allow_changes := internal.ConvertStringArr(behavior_config["allow_changes"].([]interface{})) // This means we got a valid behavior specification, so we set ForceNew // to true if behavior.allow_changes includes the attribute that is changing - return !contains(allow_changes, attribute) + return !internal.Contains(allow_changes, attribute) } // This means reinstall is enabled, so it doesn't matter what the behavior @@ -473,14 +474,14 @@ func reinstallDisabledAndNoChangesAllowed(attribute string) customdiff.ResourceC } func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal var addressTypesSlice []packngo.IPAddressCreateRequest _, ok := d.GetOk("ip_address") if ok { arr := d.Get("ip_address").([]interface{}) - addressTypesSlice = getNewIPAddressSlice(arr) + addressTypesSlice = internal.GetNewIPAddressSlice(arr) } createRequest := &packngo.DeviceCreateRequest{ @@ -500,7 +501,7 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta } if facsOk { - createRequest.Facility = convertStringArr(facsRaw.([]interface{})) + createRequest.Facility = internal.ConvertStringArr(facsRaw.([]interface{})) } if metroOk { @@ -532,13 +533,13 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta } else { wfrd := "wait_for_reservation_deprovision" if d.Get(wfrd).(bool) { - return friendlyError(fmt.Errorf("You can't set %s when not using a hardware reservation", wfrd)) + return internal.FriendlyError(fmt.Errorf("You can't set %s when not using a hardware reservation", wfrd)) } } if createRequest.OS == "custom_ipxe" { if createRequest.IPXEScriptURL == "" && createRequest.UserData == "" { - return friendlyError(errors.New("\"ipxe_script_url\" or \"user_data\"" + + return internal.FriendlyError(errors.New("\"ipxe_script_url\" or \"user_data\"" + " must be provided when \"custom_ipxe\" OS is selected.")) } @@ -546,14 +547,14 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta // which case it's an error. if createRequest.IPXEScriptURL != "" { if matchIPXEScript.MatchString(createRequest.UserData) { - return friendlyError(errors.New("\"user_data\" should not be an iPXE " + + return internal.FriendlyError(errors.New("\"user_data\" should not be an iPXE " + "script when \"ipxe_script_url\" is also provided.")) } } } if createRequest.OS != "custom_ipxe" && createRequest.IPXEScriptURL != "" { - return friendlyError(errors.New("\"ipxe_script_url\" argument provided, but" + + return internal.FriendlyError(errors.New("\"ipxe_script_url\" argument provided, but" + " OS is not \"custom_ipxe\". Please verify and fix device arguments.")) } @@ -563,23 +564,23 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta projectKeys := d.Get("project_ssh_key_ids.#").(int) if projectKeys > 0 { - createRequest.ProjectSSHKeys = convertStringArr(d.Get("project_ssh_key_ids").([]interface{})) + createRequest.ProjectSSHKeys = internal.ConvertStringArr(d.Get("project_ssh_key_ids").([]interface{})) } userKeys := d.Get("user_ssh_key_ids.#").(int) if userKeys > 0 { - createRequest.UserSSHKeys = convertStringArr(d.Get("user_ssh_key_ids").([]interface{})) + createRequest.UserSSHKeys = internal.ConvertStringArr(d.Get("user_ssh_key_ids").([]interface{})) } tags := d.Get("tags.#").(int) if tags > 0 { - createRequest.Tags = convertStringArr(d.Get("tags").([]interface{})) + createRequest.Tags = internal.ConvertStringArr(d.Get("tags").([]interface{})) } if attr, ok := d.GetOk("storage"); ok { s, err := structure.NormalizeJsonString(attr.(string)) if err != nil { - return fmt.Errorf("storage param contains invalid JSON: %s", err) + return fmt.Errorf("storage param internal.Contains invalid JSON: %s", err) } var cpr packngo.CPR err = json.Unmarshal([]byte(s), &cpr) @@ -592,8 +593,8 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta start := time.Now() newDevice, _, err := client.Devices.Create(createRequest) if err != nil { - retErr := friendlyError(err) - if isNotFound(retErr) { + retErr := internal.FriendlyError(err) + if internal.IsNotFound(retErr) { retErr = fmt.Errorf("%s, make sure project \"%s\" exists", retErr, createRequest.ProjectID) } return retErr @@ -610,17 +611,17 @@ func resourceMetalDeviceCreate(ctx context.Context, d *schema.ResourceData, meta } func resourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalGoUserAgent(d) - client := meta.(*Config).metalgo + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metalgo device, resp, err := client.DevicesApi.FindDeviceById(context.Background(), d.Id()).Include(deviceCommonIncludes).Execute() if err != nil { - err = friendlyErrorForMetalGo(err, resp) + err = internal.FriendlyErrorForMetalGo(err, resp) // If the device somehow already destroyed, mark as successfully gone. // Checking d.IsNewResource prevents the creation of a resource from failing // silently. Note d.IsNewResource is false in resource import operations. - if !d.IsNewResource() && (isNotFound(err) || isForbidden(err)) { + if !d.IsNewResource() && (internal.IsNotFound(err) || internal.IsForbidden(err)) { log.Printf("[WARN] Device (%s) not found or in failed status, removing from state", d.Id()) d.SetId("") return nil @@ -663,7 +664,7 @@ func resourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("deployed_hardware_reservation_id", device.HardwareReservation.GetId()) } - networkType, err := getNetworkType(device) + networkType, err := internal.GetNetworkType(device) if err != nil { return fmt.Errorf("[ERR] Error computing network type for device (%s): %s", d.Id(), err) } @@ -688,14 +689,14 @@ func resourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta i keyIDs = append(keyIDs, path.Base(k.Href)) } d.Set("ssh_key_ids", keyIDs) - networkInfo := getNetworkInfo(device.IpAddresses) + networkInfo := internal.GetNetworkInfo(device.IpAddresses) sort.SliceStable(networkInfo.Networks, func(i, j int) bool { famI := networkInfo.Networks[i]["family"].(int32) famJ := networkInfo.Networks[j]["family"].(int32) pubI := networkInfo.Networks[i]["public"].(bool) pubJ := networkInfo.Networks[j]["public"].(bool) - return getNetworkRank(int(famI), pubI) < getNetworkRank(int(famJ), pubJ) + return internal.GetNetworkRank(int(famI), pubI) < internal.GetNetworkRank(int(famJ), pubJ) }) d.Set("network", networkInfo.Networks) @@ -703,7 +704,7 @@ func resourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("access_private_ipv4", networkInfo.PrivateIPv4) d.Set("access_public_ipv6", networkInfo.PublicIPv6) - ports := getPorts(device.NetworkPorts) + ports := internal.GetPorts(device.NetworkPorts) d.Set("ports", ports) if networkInfo.Host != "" { @@ -717,8 +718,8 @@ func resourceMetalDeviceRead(ctx context.Context, d *schema.ResourceData, meta i } func resourceMetalDeviceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal if d.HasChange("locked") { var action func(string) (*packngo.Response, error) @@ -728,7 +729,7 @@ func resourceMetalDeviceUpdate(ctx context.Context, d *schema.ResourceData, meta action = client.Devices.Unlock } if _, err := action(d.Id()); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } ur := packngo.DeviceUpdateRequest{} @@ -760,7 +761,7 @@ func resourceMetalDeviceUpdate(ctx context.Context, d *schema.ResourceData, meta } ur.Tags = &sts default: - return friendlyError(fmt.Errorf("garbage in tags: %s", ts)) + return internal.FriendlyError(fmt.Errorf("garbage in tags: %s", ts)) } } if d.HasChange("ipxe_script_url") { @@ -775,7 +776,7 @@ func resourceMetalDeviceUpdate(ctx context.Context, d *schema.ResourceData, meta start := time.Now() if !reflect.DeepEqual(ur, packngo.DeviceUpdateRequest{}) { if _, _, err := client.Devices.Update(d.Id(), &ur); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -811,7 +812,7 @@ func doReinstall(ctx context.Context, client *packngo.Client, d *schema.Resource } if _, err := client.Devices.Reinstall(d.Id(), &reinstallOptions); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start) @@ -824,8 +825,8 @@ func doReinstall(ctx context.Context, client *packngo.Client, d *schema.Resource } func resourceMetalDeviceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal fdvIf, fdvOk := d.GetOk("force_detach_volumes") fdv := false @@ -836,8 +837,8 @@ func resourceMetalDeviceDelete(ctx context.Context, d *schema.ResourceData, meta start := time.Now() resp, err := client.Devices.Delete(d.Id(), fdv) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } resId, resIdOk := d.GetOk("deployed_hardware_reservation_id") @@ -847,7 +848,7 @@ func resourceMetalDeviceDelete(ctx context.Context, d *schema.ResourceData, meta // avoid "context: deadline exceeded" timeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start) - err := waitUntilReservationProvisionable(ctx, client, resId.(string), d.Id(), 10*time.Second, timeout, 3*time.Second) + err := internal.WaitUntilReservationProvisionable(ctx, client, resId.(string), d.Id(), 10*time.Second, timeout, 3*time.Second) if err != nil { return err } @@ -864,8 +865,8 @@ func waitForActiveDevice(ctx context.Context, d *schema.ResourceData, meta inter Pending: pending, Target: targets, Refresh: func() (interface{}, string, error) { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal device, _, err := client.Devices.Get(d.Id(), &packngo.GetOptions{Includes: []string{"project"}}) if err == nil { @@ -880,11 +881,11 @@ func waitForActiveDevice(ctx context.Context, d *schema.ResourceData, meta inter } // Wait for the device so we can get the networking attributes that show up after a while. - state, err := waitForDeviceAttribute(ctx, d, stateConf) + state, err := internal.WaitForDeviceAttribute(ctx, d, stateConf) if err != nil { d.SetId("") - fErr := friendlyError(err) - if isForbidden(fErr) { + fErr := internal.FriendlyError(err) + if internal.IsForbidden(fErr) { // If the device doesn't get to the active state, we can't recover it from here. return errors.New("provisioning time limit exceeded; the Equinix Metal team will investigate") diff --git a/equinix/resource_metal_device_acc_test.go b/equinix/resource_metal_device_acc_test.go index 030f33766..7ef1eac7f 100644 --- a/equinix/resource_metal_device_acc_test.go +++ b/equinix/resource_metal_device_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -538,7 +539,7 @@ func TestAccMetalDevice_allowChangesErrorOnUnsupportedAttribute(t *testing.T) { } func testAccMetalDeviceCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_device" { @@ -574,7 +575,7 @@ func testAccMetalDeviceExists(n string, device *packngo.Device) resource.TestChe return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundDevice, _, err := client.Devices.Get(rs.Primary.ID, nil) if err != nil { @@ -1036,7 +1037,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { newResource: false, handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - w.Header().Add("X-Request-Id", "needed for friendlyError") + w.Header().Add("X-Request-Id", "needed for FriendlyError") w.WriteHeader(http.StatusForbidden) }, }, @@ -1048,7 +1049,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { newResource: false, handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - w.Header().Add("X-Request-Id", "needed for friendlyError") + w.Header().Add("X-Request-Id", "needed for FriendlyError") w.WriteHeader(http.StatusNotFound) }, }, @@ -1060,7 +1061,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { newResource: true, handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - w.Header().Add("X-Request-Id", "needed for friendlyError") + w.Header().Add("X-Request-Id", "needed for FriendlyError") w.WriteHeader(http.StatusForbidden) }, }, @@ -1072,7 +1073,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { newResource: true, handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - w.Header().Add("X-Request-Id", "needed for friendlyError") + w.Header().Add("X-Request-Id", "needed for FriendlyError") w.WriteHeader(http.StatusNotFound) }, }, @@ -1084,7 +1085,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { newResource: true, handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - w.Header().Add("X-Request-Id", "needed for friendlyError") + w.Header().Add("X-Request-Id", "needed for FriendlyError") w.WriteHeader(http.StatusBadRequest) }, }, @@ -1103,7 +1104,7 @@ func TestAccMetalDevice_readErrorHandling(t *testing.T) { } mockAPI := httptest.NewServer(http.HandlerFunc(tt.args.handler)) - meta := &Config{ + meta := &internal.Config{ BaseURL: mockAPI.URL, Token: "fakeTokenForMock", } @@ -1132,8 +1133,8 @@ func testAccWaitForMetalDeviceActive(project, deviceHostName string) resource.Im meta := testAccProvider.Meta() rd := new(schema.ResourceData) - meta.(*Config).addModuleToMetalUserAgent(rd) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(rd) + client := meta.(*internal.Config).Metal devices, _, err := client.Devices.List(rs.Primary.ID, &packngo.ListOptions{Search: deviceHostName}) if err != nil { return "", fmt.Errorf("error while fetching devices for project [%s], error: %w", rs.Primary.ID, err) diff --git a/equinix/resource_metal_device_network_type.go b/equinix/resource_metal_device_network_type.go index 022252151..b8d000261 100644 --- a/equinix/resource_metal_device_network_type.go +++ b/equinix/resource_metal_device_network_type.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -71,8 +72,8 @@ func getAndPossiblySetNetworkType(d *schema.ResourceData, c *packngo.Client, tar } func resourceMetalDeviceNetworkTypeCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal ntype := d.Get("type").(string) err := getAndPossiblySetNetworkType(d, client, ntype) @@ -84,14 +85,14 @@ func resourceMetalDeviceNetworkTypeCreate(d *schema.ResourceData, meta interface } func resourceMetalDeviceNetworkTypeRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal _, devNType, err := getDevIDandNetworkType(d, client) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) - if isNotFound(err) { + if internal.IsNotFound(err) { log.Printf("[WARN] Device (%s) for Network Type request not found, removing from state", d.Id()) d.SetId("") return nil @@ -113,8 +114,8 @@ func resourceMetalDeviceNetworkTypeRead(d *schema.ResourceData, meta interface{} } func resourceMetalDeviceNetworkTypeUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal ntype := d.Get("type").(string) if d.HasChange("type") { diff --git a/equinix/resource_metal_gateway.go b/equinix/resource_metal_gateway.go index 19959bc99..93f179e9b 100644 --- a/equinix/resource_metal_gateway.go +++ b/equinix/resource_metal_gateway.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "time" @@ -93,8 +94,8 @@ func resourceMetalGateway() *schema.Resource { } func resourceMetalGatewayCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal _, hasIPReservation := d.GetOk("ip_reservation_id") _, hasSubnetSize := d.GetOk("private_ipv4_subnet_size") @@ -120,8 +121,8 @@ func resourceMetalGatewayCreate(d *schema.ResourceData, meta interface{}) error } func resourceMetalGatewayRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal mgId := d.Id() includes := &packngo.GetOptions{Includes: []string{"project", "ip_reservation", "virtual_network", "vrf"}} @@ -152,11 +153,11 @@ func resourceMetalGatewayRead(d *schema.ResourceData, meta interface{}) error { } func resourceMetalGatewayDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.MetalGateways.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } deleteWaiter := getGatewayStateWaiter( @@ -168,7 +169,7 @@ func resourceMetalGatewayDelete(d *schema.ResourceData, meta interface{}) error ) _, err = deleteWaiter.WaitForState() - if ignoreResponseErrors(httpForbidden, httpNotFound)(nil, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(nil, err) != nil { return fmt.Errorf("Error deleting Metal Gateway %s: %s", d.Id(), err) } diff --git a/equinix/resource_metal_gateway_acc_test.go b/equinix/resource_metal_gateway_acc_test.go index 43f242118..bfa32bb7a 100644 --- a/equinix/resource_metal_gateway_acc_test.go +++ b/equinix/resource_metal_gateway_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -98,7 +99,7 @@ resource "equinix_metal_gateway" "test" { } func testAccMetalGatewayCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_gateway" { diff --git a/equinix/resource_metal_ip_attachment.go b/equinix/resource_metal_ip_attachment.go index 0da861885..7c696b072 100644 --- a/equinix/resource_metal_ip_attachment.go +++ b/equinix/resource_metal_ip_attachment.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "path" @@ -34,8 +35,8 @@ func resourceMetalIPAttachment() *schema.Resource { } func resourceMetalIPAttachmentCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal deviceID := d.Get("device_id").(string) ipa := d.Get("cidr_notation").(string) @@ -51,14 +52,14 @@ func resourceMetalIPAttachmentCreate(d *schema.ResourceData, meta interface{}) e } func resourceMetalIPAttachmentRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal assignment, _, err := client.DeviceIPs.Get(d.Id(), nil) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the IP attachment was already destroyed, mark as succesfully gone. - if isNotFound(err) { + if internal.IsNotFound(err) { log.Printf("[WARN] IP attachment (%q) not found, removing from state", d.Id()) d.SetId("") return nil @@ -87,12 +88,12 @@ func resourceMetalIPAttachmentRead(d *schema.ResourceData, meta interface{}) err } func resourceMetalIPAttachmentDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.DeviceIPs.Unassign(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } d.SetId("") diff --git a/equinix/resource_metal_ip_attachment_acc_test.go b/equinix/resource_metal_ip_attachment_acc_test.go index 993ff9950..749ead4ad 100644 --- a/equinix/resource_metal_ip_attachment_acc_test.go +++ b/equinix/resource_metal_ip_attachment_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -127,7 +128,7 @@ resource "equinix_metal_ip_attachment" "test" { } func testAccMetalIPAttachmentCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_ip_attachment" { diff --git a/equinix/resource_metal_organization.go b/equinix/resource_metal_organization.go index 24030a89a..843e0d92c 100644 --- a/equinix/resource_metal_organization.go +++ b/equinix/resource_metal_organization.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "regexp" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -100,8 +101,8 @@ func createMetalOrganizationAddressResourceSchema() map[string]*schema.Schema { } func resourceMetalOrganizationCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal createRequest := &packngo.OrganizationCreateRequest{ Name: d.Get("name").(string), @@ -126,7 +127,7 @@ func resourceMetalOrganizationCreate(d *schema.ResourceData, meta interface{}) e org, _, err := client.Organizations.Create(createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(org.ID) @@ -135,15 +136,15 @@ func resourceMetalOrganizationCreate(d *schema.ResourceData, meta interface{}) e } func resourceMetalOrganizationRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal key, _, err := client.Organizations.Get(d.Id(), &packngo.GetOptions{Includes: []string{"address"}}) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the project somehow already destroyed, mark as succesfully gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil @@ -166,8 +167,8 @@ func resourceMetalOrganizationRead(d *schema.ResourceData, meta interface{}) err } func resourceMetalOrganizationUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal changes := getResourceDataChangedKeys([]string{"name", "description", "website", "twitter", "logo", "address"}, d) updateRequest := &packngo.OrganizationUpdateRequest{} @@ -196,19 +197,19 @@ func resourceMetalOrganizationUpdate(d *schema.ResourceData, meta interface{}) e _, _, err := client.Organizations.Update(d.Id(), updateRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } return resourceMetalOrganizationRead(d, meta) } func resourceMetalOrganizationDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.Organizations.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } d.SetId("") diff --git a/equinix/resource_metal_organization_acc_test.go b/equinix/resource_metal_organization_acc_test.go index 255dfdac3..e4c8dc68c 100644 --- a/equinix/resource_metal_organization_acc_test.go +++ b/equinix/resource_metal_organization_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "testing" @@ -123,7 +124,7 @@ func TestAccMetalOrganization_importBasic(t *testing.T) { } func testAccMetalOrganizationCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_organization" { @@ -147,7 +148,7 @@ func testAccMetalOrganizationExists(n string, org *packngo.Organization) resourc return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundOrg, _, err := client.Organizations.Get(rs.Primary.ID, &packngo.GetOptions{Includes: []string{"address", "primary_owner"}}) if err != nil { diff --git a/equinix/resource_metal_organization_member.go b/equinix/resource_metal_organization_member.go index 6bee73909..cb9d9ad59 100644 --- a/equinix/resource_metal_organization_member.go +++ b/equinix/resource_metal_organization_member.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "path" @@ -117,20 +118,20 @@ func resourceMetalOrganizationMember() *schema.Resource { } func resourceMetalOrganizationMemberCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal email := d.Get("invitee").(string) createRequest := &packngo.InvitationCreateRequest{ Invitee: email, - Roles: convertStringArr(d.Get("roles").(*schema.Set).List()), - ProjectsIDs: convertStringArr(d.Get("projects_ids").(*schema.Set).List()), + Roles: internal.ConvertStringArr(d.Get("roles").(*schema.Set).List()), + ProjectsIDs: internal.ConvertStringArr(d.Get("projects_ids").(*schema.Set).List()), Message: strings.TrimSpace(d.Get("message").(string)), } orgID := d.Get("organization_id").(string) _, _, err := client.Invitations.Create(orgID, createRequest, nil) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(fmt.Sprintf("%s:%s", email, orgID)) @@ -154,7 +155,7 @@ func findMember(invitee string, members []packngo.Member, invitations []packngo. } func resourceMetalOrganizationMemberRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal parts := strings.Split(d.Id(), ":") invitee := parts[0] orgID := parts[1] @@ -162,9 +163,9 @@ func resourceMetalOrganizationMemberRead(d *schema.ResourceData, meta interface{ listOpts := &packngo.ListOptions{Includes: []string{"user"}} invitations, _, err := client.Invitations.List(orgID, listOpts) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the org was destroyed, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -173,9 +174,9 @@ func resourceMetalOrganizationMemberRead(d *schema.ResourceData, meta interface{ members, _, err := client.Members.List(orgID, &packngo.GetOptions{Includes: []string{"user"}}) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the org was destroyed, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -195,8 +196,8 @@ func resourceMetalOrganizationMemberRead(d *schema.ResourceData, meta interface{ } return setMap(d, map[string]interface{}{ "state": "active", - "roles": stringArrToIfArr(member.Member.Roles), - "projects_ids": stringArrToIfArr(projectIDs), + "roles": internal.StringArrToIfArr(member.Member.Roles), + "projects_ids": internal.StringArrToIfArr(projectIDs), "organization_id": path.Base(member.Member.Organization.URL), }) } else if member.isInvitation() { @@ -219,14 +220,14 @@ func resourceMetalOrganizationMemberRead(d *schema.ResourceData, meta interface{ } func resourceMetalOrganizationMemberDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Config).metal + client := meta.(*internal.Config).Metal listOpts := &packngo.ListOptions{Includes: []string{"user"}} invitations, _, err := client.Invitations.List(d.Get("organization_id").(string), listOpts) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the org was destroyed, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -236,9 +237,9 @@ func resourceMetalOrganizationMemberDelete(d *schema.ResourceData, meta interfac orgID := d.Get("organization_id").(string) org, _, err := client.Organizations.Get(orgID, &packngo.GetOptions{Includes: []string{"members", "members.user"}}) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the org was destroyed, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -254,9 +255,9 @@ func resourceMetalOrganizationMemberDelete(d *schema.ResourceData, meta interfac if member.isMember() { _, err = client.Members.Delete(orgID, member.Member.ID) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the member was deleted, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -265,9 +266,9 @@ func resourceMetalOrganizationMemberDelete(d *schema.ResourceData, meta interfac } else if member.isInvitation() { _, err = client.Invitations.Delete(member.Invitation.ID) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the invitation was deleted, mark as gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil } diff --git a/equinix/resource_metal_port.go b/equinix/resource_metal_port.go index 375897ec8..6ede2714f 100644 --- a/equinix/resource_metal_port.go +++ b/equinix/resource_metal_port.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "log" "time" @@ -14,10 +15,6 @@ Race conditions: - Bonding a bond port where underlying eth port has vlans assigned, and those vlans are being removed in the same terraform run */ -var ( - l2Types = []string{"layer2-individual", "layer2-bonded"} - l3Types = []string{"layer3", "hybrid", "hybrid-bonded"} -) func resourceMetalPort() *schema.Resource { return &schema.Resource{ @@ -119,23 +116,23 @@ func resourceMetalPort() *schema.Resource { func resourceMetalPortUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { start := time.Now() - cpr, _, err := getClientPortResource(d, meta) + cpr, _, err := internal.GetClientPortResource(d, meta) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } - for _, f := range [](func(*ClientPortResource) error){ - portSanityChecks, - batchVlans(ctx, start, true), - makeDisbond, - convertToL2, - makeBond, - convertToL3, - batchVlans(ctx, start, false), - updateNativeVlan, + for _, f := range [](func(*internal.ClientPortResource) error){ + internal.PortSanityChecks, + internal.BatchVlans(ctx, start, true), + internal.MakeDisbond, + internal.ConvertToL2, + internal.MakeBond, + internal.ConvertToL3, + internal.BatchVlans(ctx, start, false), + internal.UpdateNativeVlan, } { if err := f(cpr); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -143,12 +140,12 @@ func resourceMetalPortUpdate(ctx context.Context, d *schema.ResourceData, meta i } func resourceMetalPortRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal - port, err := getPortByResourceData(d, client) + port, err := internal.GetPortByResourceData(d, client) if err != nil { - if isNotFound(err) || isForbidden(err) { + if internal.IsNotFound(err) || internal.IsForbidden(err) { log.Printf("[WARN] Port (%s) not accessible, removing from state", d.Id()) d.SetId("") @@ -165,8 +162,8 @@ func resourceMetalPortRead(ctx context.Context, d *schema.ResourceData, meta int "bonded": port.Data.Bonded, "disbond_supported": port.DisbondOperationSupported, } - l2 := contains(l2Types, port.NetworkType) - l3 := contains(l3Types, port.NetworkType) + l2 := internal.Contains(internal.L2Types, port.NetworkType) + l3 := internal.Contains(internal.L3Types, port.NetworkType) if l2 { m["layer2"] = true @@ -201,8 +198,8 @@ func resourceMetalPortDelete(ctx context.Context, d *schema.ResourceData, meta i resetRaw, resetOk := d.GetOk("reset_on_delete") if resetOk && resetRaw.(bool) { start := time.Now() - cpr, resp, err := getClientPortResource(d, meta) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { + cpr, resp, err := internal.GetClientPortResource(d, meta) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { return err } @@ -221,17 +218,17 @@ func resourceMetalPortDelete(ctx context.Context, d *schema.ResourceData, meta i }); err != nil { return err } - for _, f := range [](func(*ClientPortResource) error){ - batchVlans(ctx, start, true), - makeBond, - convertToL3, + for _, f := range [](func(*internal.ClientPortResource) error){ + internal.BatchVlans(ctx, start, true), + internal.MakeBond, + internal.ConvertToL3, } { if err := f(cpr); err != nil { return err } } // TODO(displague) error or warn? - if warn := portProperlyDestroyed(cpr.Port); warn != nil { + if warn := internal.PortProperlyDestroyed(cpr.Port); warn != nil { log.Printf("[WARN] %s\n", warn) } } diff --git a/equinix/resource_metal_port_acc_test.go b/equinix/resource_metal_port_acc_test.go index 71274d4f5..4f2580eb5 100644 --- a/equinix/resource_metal_port_acc_test.go +++ b/equinix/resource_metal_port_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "regexp" "testing" @@ -354,7 +355,7 @@ func TestAccMetalPort_hybridBonded(t *testing.T) { } func testAccMetalPortDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal port_ids := []string{} @@ -371,7 +372,7 @@ func testAccMetalPortDestroyed(s *terraform.State) error { if err != nil { return fmt.Errorf("Error getting port %s during destroy check", pid) } - err = portProperlyDestroyed(p) + err = internal.PortProperlyDestroyed(p) if err != nil { return err } @@ -391,8 +392,8 @@ func testAccWaitForPortActive(deviceName, portName string) resource.ImportStateI meta := testAccProvider.Meta() rd := new(schema.ResourceData) - meta.(*Config).addModuleToMetalUserAgent(rd) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(rd) + client := meta.(*internal.Config).Metal device, _, err := client.Devices.Get(rs.Primary.ID, &packngo.GetOptions{Includes: []string{"ports"}}) if err != nil { return "", fmt.Errorf("error while fetching device with Id [%s], error: %w", rs.Primary.ID, err) diff --git a/equinix/resource_metal_port_vlan_attachment.go b/equinix/resource_metal_port_vlan_attachment.go index d537c0d7e..0657cd265 100644 --- a/equinix/resource_metal_port_vlan_attachment.go +++ b/equinix/resource_metal_port_vlan_attachment.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" @@ -65,8 +66,8 @@ func resourceMetalPortVlanAttachment() *schema.Resource { } func resourceMetalPortVlanAttachmentCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal deviceID := d.Get("device_id").(string) pName := d.Get("port_name").(string) vlanVNID := d.Get("vlan_vnid").(int) @@ -158,17 +159,17 @@ func resourceMetalPortVlanAttachmentCreate(d *schema.ResourceData, meta interfac } func resourceMetalPortVlanAttachmentRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal deviceID := d.Get("device_id").(string) pName := d.Get("port_name").(string) vlanVNID := d.Get("vlan_vnid").(int) dev, _, err := client.Devices.Get(deviceID, &packngo.GetOptions{Includes: []string{"virtual_networks,project,native_virtual_network"}}) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) - if isNotFound(err) { + if internal.IsNotFound(err) { log.Printf("[WARN] Device (%s) for Port Vlan Attachment not found, removing from state", d.Id()) d.SetId("") return nil @@ -212,8 +213,8 @@ func resourceMetalPortVlanAttachmentRead(d *schema.ResourceData, meta interface{ } func resourceMetalPortVlanAttachmentUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal if d.HasChange("native") { native := d.Get("native").(bool) portID := d.Get("port_id").(string) @@ -235,14 +236,14 @@ func resourceMetalPortVlanAttachmentUpdate(d *schema.ResourceData, meta interfac } func resourceMetalPortVlanAttachmentDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal pID := d.Get("port_id").(string) vlanID := d.Get("vlan_id").(string) native := d.Get("native").(bool) if native { _, resp, err := client.DevicePorts.UnassignNative(pID) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { return err } } @@ -251,7 +252,7 @@ func resourceMetalPortVlanAttachmentDelete(d *schema.ResourceData, meta interfac metalMutexKV.Lock(lockId) defer metalMutexKV.Unlock(lockId) portPtr, resp, err := client.DevicePorts.Unassign(par) - if ignoreResponseErrors(httpForbidden, httpNotFound, isNotAssigned)(resp, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound, internal.IsNotAssigned)(resp, err) != nil { return err } forceBond := d.Get("force_bond").(bool) @@ -260,11 +261,11 @@ func resourceMetalPortVlanAttachmentDelete(d *schema.ResourceData, meta interfac portName := d.Get("port_name").(string) port, err := client.DevicePorts.GetPortByName(deviceID, portName) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } _, _, err = client.DevicePorts.Bond(port, false) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } return nil diff --git a/equinix/resource_metal_port_vlan_attachment_acc_test.go b/equinix/resource_metal_port_vlan_attachment_acc_test.go index 2cc9b8081..5b7a69e10 100644 --- a/equinix/resource_metal_port_vlan_attachment_acc_test.go +++ b/equinix/resource_metal_port_vlan_attachment_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "path" "strings" @@ -346,7 +347,7 @@ func TestAccMetalPortVlanAttachment_hybridMultipleVlans(t *testing.T) { } func testAccMetalPortVlanAttachmentCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal device_id := "" vlan_id := "" diff --git a/equinix/resource_metal_project.go b/equinix/resource_metal_project.go index d02528ec7..830d31291 100644 --- a/equinix/resource_metal_project.go +++ b/equinix/resource_metal_project.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "path" "regexp" @@ -123,8 +124,8 @@ func expandBGPConfig(d *schema.ResourceData) packngo.CreateBGPConfigRequest { } func resourceMetalProjectCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal createRequest := &packngo.ProjectCreateRequest{ Name: d.Get("name").(string), @@ -133,7 +134,7 @@ func resourceMetalProjectCreate(d *schema.ResourceData, meta interface{}) error project, _, err := client.Projects.Create(createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(project.ID) @@ -143,7 +144,7 @@ func resourceMetalProjectCreate(d *schema.ResourceData, meta interface{}) error bgpCR := expandBGPConfig(d) _, err := client.BGPConfig.Create(project.ID, bgpCR) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -152,22 +153,22 @@ func resourceMetalProjectCreate(d *schema.ResourceData, meta interface{}) error pur := packngo.ProjectUpdateRequest{BackendTransfer: &backendTransfer} _, _, err := client.Projects.Update(project.ID, &pur) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } return resourceMetalProjectRead(d, meta) } func resourceMetalProjectRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal proj, _, err := client.Projects.Get(d.Id(), nil) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the project somehow already destroyed, mark as successfully gone. - if isNotFound(err) { + if internal.IsNotFound(err) { d.SetId("") return nil @@ -193,7 +194,7 @@ func resourceMetalProjectRead(d *schema.ResourceData, meta interface{}) error { if bgpConf.ID != "" { err := d.Set("bgp_config", flattenBGPConfig(bgpConf)) if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) return err } } @@ -232,8 +233,8 @@ func flattenBGPConfig(l *packngo.BGPConfig) []map[string]interface{} { } func resourceMetalProjectUpdate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal updateRequest := &packngo.ProjectUpdateRequest{} if d.HasChange("name") { pName := d.Get("name").(string) @@ -255,7 +256,7 @@ func resourceMetalProjectUpdate(d *schema.ResourceData, meta interface{}) error bgpCreateRequest := expandBGPConfig(d) _, err := client.BGPConfig.Create(d.Id(), bgpCreateRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } else { if len(oldarr) == 1 { @@ -269,14 +270,14 @@ func resourceMetalProjectUpdate(d *schema.ResourceData, meta interface{}) error "}", m["deployment_type"].(string), m["md5"].(string), m["asn"].(int)) - errStr := fmt.Errorf("BGP Config can not be removed from a project, please add back\n%s", bgpConfStr) - return friendlyError(errStr) + errStr := fmt.Errorf("BGP internal.Config can not be removed from a project, please add back\n%s", bgpConfStr) + return internal.FriendlyError(errStr) } } } else { _, _, err := client.Projects.Update(d.Id(), updateRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } @@ -284,12 +285,12 @@ func resourceMetalProjectUpdate(d *schema.ResourceData, meta interface{}) error } func resourceMetalProjectDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.Projects.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } d.SetId("") diff --git a/equinix/resource_metal_project_acc_test.go b/equinix/resource_metal_project_acc_test.go index ea4e22c31..e6c0c27b9 100644 --- a/equinix/resource_metal_project_acc_test.go +++ b/equinix/resource_metal_project_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -135,8 +136,8 @@ func TestAccMetalProject_errorHandling(t *testing.T) { } mockEquinix := Provider() mockEquinix.ConfigureContextFunc = func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { - config := Config{ - metal: &packngo.Client{Projects: mockMetalProjectService}, + config := internal.Config{ + Metal: &packngo.Client{Projects: mockMetalProjectService}, } return &config, nil } @@ -167,8 +168,8 @@ func TestAccMetalProject_apiErrorHandling(t *testing.T) { } mockEquinix := Provider() mockEquinix.ConfigureContextFunc = func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { - config := Config{ - metal: &packngo.Client{Projects: mockMetalProjectService}, + config := internal.Config{ + Metal: &packngo.Client{Projects: mockMetalProjectService}, } return &config, nil } @@ -346,7 +347,7 @@ func TestAccMetalProject_BGPUpdate(t *testing.T) { } func testAccMetalProjectCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_project" { @@ -370,7 +371,7 @@ func testAccMetalProjectExists(n string, project *packngo.Project) resource.Test return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundProject, _, err := client.Projects.Get(rs.Primary.ID, nil) if err != nil { diff --git a/equinix/resource_metal_project_api_key.go b/equinix/resource_metal_project_api_key.go index bedc97452..949c46221 100644 --- a/equinix/resource_metal_project_api_key.go +++ b/equinix/resource_metal_project_api_key.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -47,8 +48,8 @@ func resourceMetalProjectAPIKey() *schema.Resource { } func resourceMetalAPIKeyCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal projectId := "" @@ -65,7 +66,7 @@ func resourceMetalAPIKeyCreate(d *schema.ResourceData, meta interface{}) error { apiKey, _, err := client.APIKeys.Create(createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(apiKey.ID) @@ -82,8 +83,8 @@ func projectIdFromResourceData(d *schema.ResourceData) string { } func resourceMetalAPIKeyRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal projectId := projectIdFromResourceData(d) @@ -101,10 +102,10 @@ func resourceMetalAPIKeyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - err = friendlyError(err) + err = internal.FriendlyError(err) // If the key is somehow already destroyed, mark as // succesfully gone - if isNotFound(err) { + if internal.IsNotFound(err) { log.Printf("[WARN] Project APIKey (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -133,12 +134,12 @@ func resourceMetalAPIKeyRead(d *schema.ResourceData, meta interface{}) error { } func resourceMetalAPIKeyDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.APIKeys.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } d.SetId("") diff --git a/equinix/resource_metal_project_api_key_acc_test.go b/equinix/resource_metal_project_api_key_acc_test.go index d6262342d..d0cd613fb 100644 --- a/equinix/resource_metal_project_api_key_acc_test.go +++ b/equinix/resource_metal_project_api_key_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -44,7 +45,7 @@ resource "equinix_metal_project_api_key" "test" { } func testAccMetalProjectAPIKeyCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_project_api_key" { continue diff --git a/equinix/resource_metal_project_ssh_key.go b/equinix/resource_metal_project_ssh_key.go deleted file mode 100644 index 845d9d0fb..000000000 --- a/equinix/resource_metal_project_ssh_key.go +++ /dev/null @@ -1,25 +0,0 @@ -package equinix - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func resourceMetalProjectSSHKey() *schema.Resource { - pkeySchema := metalSSHKeyCommonFields() - pkeySchema["project_id"] = &schema.Schema{ - Type: schema.TypeString, - Description: "The ID of parent project", - ForceNew: true, - Required: true, - } - return &schema.Resource{ - Create: resourceMetalSSHKeyCreate, - Read: resourceMetalSSHKeyRead, - Update: resourceMetalSSHKeyUpdate, - Delete: resourceMetalSSHKeyDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Schema: pkeySchema, - } -} diff --git a/equinix/resource_metal_reserved_ip_block.go b/equinix/resource_metal_reserved_ip_block.go index 04ff8c593..57e40be09 100644 --- a/equinix/resource_metal_reserved_ip_block.go +++ b/equinix/resource_metal_reserved_ip_block.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "encoding/json" "fmt" @@ -129,7 +130,7 @@ func resourceMetalReservedIPBlock() *schema.Resource { } return fromState == fromHCL }, - StateFunc: toLower, + StateFunc: internal.ToLower, } reservedBlockSchema["description"] = &schema.Schema{ Type: schema.TypeString, @@ -232,8 +233,8 @@ func resourceMetalReservedIPBlock() *schema.Resource { } func resourceMetalReservedIPBlockCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal quantity := d.Get("quantity").(int) typ := d.Get("type").(string) @@ -315,8 +316,8 @@ func resourceMetalReservedIPBlockCreate(ctx context.Context, d *schema.ResourceD } func resourceMetalReservedIPBlockUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal id := d.Id() req := &packngo.IPAddressUpdateRequest{} if d.HasChange("tags") { @@ -457,8 +458,8 @@ func loadBlock(d *schema.ResourceData, reservedBlock *packngo.IPAddressReservati } func resourceMetalReservedIPBlockRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal id := d.Id() getOpts := &packngo.GetOptions{Includes: []string{"facility", "metro", "project", "vrf"}} @@ -466,8 +467,8 @@ func resourceMetalReservedIPBlockRead(ctx context.Context, d *schema.ResourceDat reservedBlock, _, err := client.ProjectIPs.Get(id, getOpts) if err != nil { - err = friendlyError(err) - if isNotFound(err) { + err = internal.FriendlyError(err) + if internal.IsNotFound(err) { log.Printf("[WARN] Reserved IP Block (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -488,14 +489,14 @@ func resourceMetalReservedIPBlockRead(ctx context.Context, d *schema.ResourceDat } func resourceMetalReservedIPBlockDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal id := d.Id() resp, err := client.ProjectIPs.Remove(id) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { return fmt.Errorf("error deleting IP reservation block %s: %s", id, err) } diff --git a/equinix/resource_metal_reserved_ip_block_acc_test.go b/equinix/resource_metal_reserved_ip_block_acc_test.go index f10143592..ddeeef17d 100644 --- a/equinix/resource_metal_reserved_ip_block_acc_test.go +++ b/equinix/resource_metal_reserved_ip_block_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "bytes" "fmt" "regexp" @@ -210,7 +211,7 @@ func TestAccMetalReservedIPBlock_importBasic(t *testing.T) { } func testAccMetalReservedIPBlockCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_reserved_ip_block" { diff --git a/equinix/resource_metal_spot_market_request.go b/equinix/resource_metal_spot_market_request.go index 2052ce43d..a4b064e98 100644 --- a/equinix/resource_metal_spot_market_request.go +++ b/equinix/resource_metal_spot_market_request.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -49,7 +50,7 @@ func resourceMetalSpotMarketRequest() *schema.Resource { if err != nil { return false } - // suppress diff if the difference between existing and new bid price + // suppress diff if the internal.Difference between existing and new bid price // is less than 2% diffThreshold := .02 priceDiff := oldF / newF @@ -109,7 +110,7 @@ func resourceMetalSpotMarketRequest() *schema.Resource { Optional: true, ForceNew: true, ConflictsWith: []string{"facilities"}, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "instance_parameters": { Type: schema.TypeList, @@ -213,8 +214,8 @@ func resourceMetalSpotMarketRequest() *schema.Resource { } func resourceMetalSpotMarketRequestCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal var waitForDevices bool metro := d.Get("metro").(string) @@ -356,13 +357,13 @@ func resourceMetalSpotMarketRequestCreate(ctx context.Context, d *schema.Resourc } func resourceMetalSpotMarketRequestRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal smr, _, err := client.SpotMarketRequests.Get(d.Id(), &packngo.GetOptions{Includes: []string{"project", "devices", "facilities", "metro"}}) if err != nil { - err = friendlyError(err) - if isNotFound(err) { + err = internal.FriendlyError(err) + if internal.IsNotFound(err) { log.Printf("[WARN] SpotMarketRequest (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -396,8 +397,8 @@ func resourceMetalSpotMarketRequestRead(ctx context.Context, d *schema.ResourceD } func resourceMetalSpotMarketRequestDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal var waitForDevices bool if val, ok := d.GetOk("wait_for_devices"); ok { @@ -426,19 +427,19 @@ func resourceMetalSpotMarketRequestDelete(ctx context.Context, d *schema.Resourc for _, d := range smr.Devices { resp, err := client.Devices.Delete(d.ID, true) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { return err } } } resp, err := client.SpotMarketRequests.Delete(d.Id(), true) - return ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) + return internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) } func resourceStateRefreshFunc(d *schema.ResourceData, meta interface{}) retry.StateRefreshFunc { return func() (interface{}, string, error) { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal smr, _, err := client.SpotMarketRequests.Get(d.Id(), &packngo.GetOptions{Includes: []string{"project", "devices", "facilities", "metro"}}) if err != nil { diff --git a/equinix/resource_metal_spot_market_request_acc_test.go b/equinix/resource_metal_spot_market_request_acc_test.go index 7291f401a..c596c5461 100644 --- a/equinix/resource_metal_spot_market_request_acc_test.go +++ b/equinix/resource_metal_spot_market_request_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -40,7 +41,7 @@ func TestAccMetalSpotMarketRequest_basic(t *testing.T) { } func testAccMetalSpotMarketRequestCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_spot_market_request" { @@ -64,7 +65,7 @@ func testAccCheckMetalSpotMarketRequestExists(n string, key *packngo.SpotMarketR return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundKey, _, err := client.SpotMarketRequests.Get(rs.Primary.ID, &packngo.GetOptions{Includes: []string{"project", "devices", "facilities", "metro"}}) if err != nil { diff --git a/equinix/resource_metal_user_api_key_acc_test.go b/equinix/resource_metal_user_api_key_acc_test.go index 4b348963a..0392fbdfa 100644 --- a/equinix/resource_metal_user_api_key_acc_test.go +++ b/equinix/resource_metal_user_api_key_acc_test.go @@ -69,7 +69,7 @@ func TestAccMetalUserAPIKey_basic(t *testing.T) { } func testAccMetalUserAPIKeyCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_user_api_key" { continue diff --git a/equinix/resource_metal_virtual_circuit.go b/equinix/resource_metal_virtual_circuit.go index 7d9ded70e..19165ec74 100644 --- a/equinix/resource_metal_virtual_circuit.go +++ b/equinix/resource_metal_virtual_circuit.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -139,8 +140,8 @@ func resourceMetalVirtualCircuit() *schema.Resource { } func resourceMetalVirtualCircuitCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal vncr := packngo.VCCreateRequest{ VirtualNetworkID: d.Get("vlan_id").(string), Name: d.Get("name").(string), @@ -160,7 +161,7 @@ func resourceMetalVirtualCircuitCreate(ctx context.Context, d *schema.ResourceDa tags := d.Get("tags.#").(int) if tags > 0 { - vncr.Tags = convertStringArr(d.Get("tags").([]interface{})) + vncr.Tags = internal.ConvertStringArr(d.Get("tags").([]interface{})) } if nniVlan, ok := d.GetOk("nni_vlan"); ok { @@ -199,8 +200,8 @@ func resourceMetalVirtualCircuitCreate(ctx context.Context, d *schema.ResourceDa } func resourceMetalVirtualCircuitRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal vcId := d.Id() vc, _, err := client.VirtualCircuits.Get( @@ -280,8 +281,8 @@ func getVCStateWaiter(client *packngo.Client, id string, timeout time.Duration, } func resourceMetalVirtualCircuitUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal ur := packngo.VCUpdateRequest{} if d.HasChange("vlan_id") { @@ -315,25 +316,25 @@ func resourceMetalVirtualCircuitUpdate(ctx context.Context, d *schema.ResourceDa } ur.Tags = &sts default: - return friendlyError(fmt.Errorf("garbage in tags: %s", ts)) + return internal.FriendlyError(fmt.Errorf("garbage in tags: %s", ts)) } } if !reflect.DeepEqual(ur, packngo.VCUpdateRequest{}) { if _, _, err := client.VirtualCircuits.Update(d.Id(), &ur, nil); err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } } return resourceMetalVirtualCircuitRead(ctx, d, meta) } func resourceMetalVirtualCircuitDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.VirtualCircuits.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } deleteWaiter := getVCStateWaiter( @@ -345,7 +346,7 @@ func resourceMetalVirtualCircuitDelete(ctx context.Context, d *schema.ResourceDa ) _, err = deleteWaiter.WaitForStateContext(ctx) - if ignoreResponseErrors(httpForbidden, httpNotFound)(nil, err) != nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(nil, err) != nil { return fmt.Errorf("Error deleting virtual circuit %s: %s", d.Id(), err) } d.SetId("") diff --git a/equinix/resource_metal_virtual_circuit_acc_test.go b/equinix/resource_metal_virtual_circuit_acc_test.go index 13a111734..95914e2ea 100644 --- a/equinix/resource_metal_virtual_circuit_acc_test.go +++ b/equinix/resource_metal_virtual_circuit_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "os" @@ -59,7 +60,7 @@ func testSweepVirtualCircuits(region string) error { } func testAccMetalVirtualCircuitCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_virtual_circuit" { diff --git a/equinix/resource_metal_vlan.go b/equinix/resource_metal_vlan.go index 5cfcd3a5a..ece75e7f0 100644 --- a/equinix/resource_metal_vlan.go +++ b/equinix/resource_metal_vlan.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "errors" "path" @@ -62,7 +63,7 @@ func resourceMetalVlan() *schema.Resource { } return old == new }, - StateFunc: toLower, + StateFunc: internal.ToLower, }, "vxlan": { Type: schema.TypeInt, @@ -76,18 +77,18 @@ func resourceMetalVlan() *schema.Resource { } func resourceMetalVlanCreate(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal facRaw, facOk := d.GetOk("facility") metroRaw, metroOk := d.GetOk("metro") vxlanRaw, vxlanOk := d.GetOk("vxlan") if !facOk && !metroOk { - return friendlyError(errors.New("one of facility or metro must be configured")) + return internal.FriendlyError(errors.New("one of facility or metro must be configured")) } if facOk && vxlanOk { - return friendlyError(errors.New("you can set vxlan only for metro vlans")) + return internal.FriendlyError(errors.New("you can set vxlan only for metro vlans")) } createRequest := &packngo.VirtualNetworkCreateRequest{ @@ -103,21 +104,21 @@ func resourceMetalVlanCreate(d *schema.ResourceData, meta interface{}) error { } vlan, _, err := client.ProjectVirtualNetworks.Create(createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(vlan.ID) return resourceMetalVlanRead(d, meta) } func resourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal vlan, _, err := client.ProjectVirtualNetworks.Get(d.Id(), &packngo.GetOptions{Includes: []string{"assigned_to"}}) if err != nil { - err = friendlyError(err) - if isNotFound(err) { + err = internal.FriendlyError(err) + if internal.IsNotFound(err) { d.SetId("") return nil } @@ -133,13 +134,13 @@ func resourceMetalVlanRead(d *schema.ResourceData, meta interface{}) error { } func resourceMetalVlanDelete(d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal id := d.Id() vlan, resp, err := client.ProjectVirtualNetworks.Get(id, &packngo.GetOptions{Includes: []string{"instances", "instances.network_ports.virtual_networks", "internet_gateway"}}) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } else if err != nil { // missing vlans are deleted return nil @@ -156,8 +157,8 @@ func resourceMetalVlanDelete(d *schema.ResourceData, meta interface{}) error { if aID == id { _, resp, err := client.Ports.Unassign(p.ID, id) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) != nil { - return friendlyError(err) + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) != nil { + return internal.FriendlyError(err) } } } @@ -166,5 +167,5 @@ func resourceMetalVlanDelete(d *schema.ResourceData, meta interface{}) error { // TODO(displague) do we need to unassign gateway connections before delete? - return friendlyError(ignoreResponseErrors(httpForbidden, httpNotFound)(client.ProjectVirtualNetworks.Delete(id))) + return internal.FriendlyError(internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(client.ProjectVirtualNetworks.Delete(id))) } diff --git a/equinix/resource_metal_vlan_acc_test.go b/equinix/resource_metal_vlan_acc_test.go index 6e395f63e..3df26599f 100644 --- a/equinix/resource_metal_vlan_acc_test.go +++ b/equinix/resource_metal_vlan_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "testing" @@ -133,7 +134,7 @@ func testAccCheckMetalVlanExists(n string, vlan *packngo.VirtualNetwork) resourc return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundVlan, _, err := client.ProjectVirtualNetworks.Get(rs.Primary.ID, nil) if err != nil { @@ -150,7 +151,7 @@ func testAccCheckMetalVlanExists(n string, vlan *packngo.VirtualNetwork) resourc } func testAccMetalVlanCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_vlan" { diff --git a/equinix/resource_metal_vrf.go b/equinix/resource_metal_vrf.go index 71b92aa5f..95f4a7954 100644 --- a/equinix/resource_metal_vrf.go +++ b/equinix/resource_metal_vrf.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/packethost/packngo" @@ -56,21 +57,21 @@ func resourceMetalVRF() *schema.Resource { } func resourceMetalVRFCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal createRequest := &packngo.VRFCreateRequest{ Name: d.Get("name").(string), Description: d.Get("description").(string), Metro: d.Get("metro").(string), LocalASN: d.Get("local_asn").(int), - IPRanges: expandSetToStringList(d.Get("ip_ranges").(*schema.Set)), + IPRanges: internal.ExpandSetToStringList(d.Get("ip_ranges").(*schema.Set)), } projectId := d.Get("project_id").(string) vrf, _, err := client.VRFs.Create(projectId, createRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } d.SetId(vrf.ID) @@ -79,8 +80,8 @@ func resourceMetalVRFCreate(ctx context.Context, d *schema.ResourceData, meta in } func resourceMetalVRFUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal sPtr := func(s string) *string { return &s } iPtr := func(i int) *int { return &i } @@ -96,27 +97,27 @@ func resourceMetalVRFUpdate(ctx context.Context, d *schema.ResourceData, meta in updateRequest.LocalASN = iPtr(d.Get("local_asn").(int)) } if d.HasChange("ip_ranges") { - ipRanges := expandSetToStringList(d.Get("ip_ranges").(*schema.Set)) + ipRanges := internal.ExpandSetToStringList(d.Get("ip_ranges").(*schema.Set)) updateRequest.IPRanges = &ipRanges } _, _, err := client.VRFs.Update(d.Id(), updateRequest) if err != nil { - return friendlyError(err) + return internal.FriendlyError(err) } return resourceMetalVRFRead(ctx, d, meta) } func resourceMetalVRFRead(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal getOpts := &packngo.GetOptions{Includes: []string{"project", "metro"}} vrf, _, err := client.VRFs.Get(d.Id(), getOpts) if err != nil { - if isNotFound(err) || isForbidden(err) { + if internal.IsNotFound(err) || internal.IsForbidden(err) { log.Printf("[WARN] VRF (%s) not accessible, removing from state", d.Id()) d.SetId("") @@ -137,13 +138,13 @@ func resourceMetalVRFRead(ctx context.Context, d *schema.ResourceData, meta inte } func resourceMetalVRFDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) error { - meta.(*Config).addModuleToMetalUserAgent(d) - client := meta.(*Config).metal + meta.(*internal.Config).AddModuleToMetalUserAgent(d) + client := meta.(*internal.Config).Metal resp, err := client.VRFs.Delete(d.Id()) - if ignoreResponseErrors(httpForbidden, httpNotFound)(resp, err) == nil { + if internal.IgnoreResponseErrors(internal.HttpForbidden, internal.HttpNotFound)(resp, err) == nil { d.SetId("") } - return friendlyError(err) + return internal.FriendlyError(err) } diff --git a/equinix/resource_metal_vrf_acc_test.go b/equinix/resource_metal_vrf_acc_test.go index caf5831a1..2e0a52db2 100644 --- a/equinix/resource_metal_vrf_acc_test.go +++ b/equinix/resource_metal_vrf_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "log" "os" @@ -296,7 +297,7 @@ func TestAccMetalVRFConfig_withConnection(t *testing.T) { } func testAccMetalVRFCheckDestroyed(s *terraform.State) error { - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal for _, rs := range s.RootModule().Resources { if rs.Type != "equinix_metal_vrf" { @@ -320,7 +321,7 @@ func testAccMetalVRFExists(n string, vrf *packngo.VRF) resource.TestCheckFunc { return fmt.Errorf("No Record ID is set") } - client := testAccProvider.Meta().(*Config).metal + client := testAccProvider.Meta().(*internal.Config).Metal foundResource, _, err := client.VRFs.Get(rs.Primary.ID, nil) if err != nil { diff --git a/equinix/resource_network_acl_template.go b/equinix/resource_network_acl_template.go index 2e5888729..4c6c2e02a 100644 --- a/equinix/resource_network_acl_template.go +++ b/equinix/resource_network_acl_template.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -224,8 +225,8 @@ func networkACLTemplateDeviceDetailsSchema() map[string]*schema.Schema { } func resourceNetworkACLTemplateCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics template := createACLTemplate(d) uuid, err := client.CreateACLTemplate(template) @@ -238,8 +239,8 @@ func resourceNetworkACLTemplateCreate(ctx context.Context, d *schema.ResourceDat } func resourceNetworkACLTemplateRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics template, err := client.GetACLTemplate(d.Id()) if err != nil { @@ -258,8 +259,8 @@ func resourceNetworkACLTemplateRead(ctx context.Context, d *schema.ResourceData, } func resourceNetworkACLTemplateUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics template := createACLTemplate(d) if err := client.ReplaceACLTemplate(d.Id(), template); err != nil { @@ -270,8 +271,8 @@ func resourceNetworkACLTemplateUpdate(ctx context.Context, d *schema.ResourceDat } func resourceNetworkACLTemplateDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics if devID, ok := d.GetOk(networkACLTemplateSchemaNames["DeviceUUID"]); ok { if err := client.NewDeviceUpdateRequest(devID.(string)).WithACLTemplate("").Execute(); err != nil { diff --git a/equinix/resource_network_acl_template_acc_test.go b/equinix/resource_network_acl_template_acc_test.go index 19e24e665..addd8b5f2 100644 --- a/equinix/resource_network_acl_template_acc_test.go +++ b/equinix/resource_network_acl_template_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -27,7 +28,7 @@ func testSweepNetworkACLTemplate(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - templates, err := config.ne.GetACLTemplates() + templates, err := config.Ne.GetACLTemplates() if err != nil { log.Printf("[INFO][SWEEPER_LOG] error fetching Network ACL Templates list: %s", err) return err @@ -38,7 +39,7 @@ func testSweepNetworkACLTemplate(region string) error { nonSweepableCount++ continue } - if err := config.ne.DeleteACLTemplate(ne.StringValue(template.UUID)); err != nil { + if err := config.Ne.DeleteACLTemplate(ne.StringValue(template.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting NetworkACLTemplate resource %s (%s): %s", ne.StringValue(template.UUID), ne.StringValue(template.Name), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for NetworkACLTemplate resource %s (%s)", ne.StringValue(template.UUID), ne.StringValue(template.Name)) @@ -143,7 +144,7 @@ func testAccNetworkACLTemplateExists(resourceName string, template *ne.ACLTempla if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_network_bgp.go b/equinix/resource_network_bgp.go index cbd6fbae8..12859a543 100644 --- a/equinix/resource_network_bgp.go +++ b/equinix/resource_network_bgp.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "net/http" @@ -121,8 +122,8 @@ func createNetworkBGPResourceSchema() map[string]*schema.Schema { } func resourceNetworkBGPCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics bgp := createNetworkBGPConfiguration(d) existingBGP, err := client.GetBGPConfigurationForConnection(ne.StringValue(bgp.ConnectionUUID)) @@ -151,8 +152,8 @@ func resourceNetworkBGPCreate(ctx context.Context, d *schema.ResourceData, m int } func resourceNetworkBGPRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics bgp, err := client.GetBGPConfiguration(d.Id()) if err != nil { @@ -165,8 +166,8 @@ func resourceNetworkBGPRead(ctx context.Context, d *schema.ResourceData, m inter } func resourceNetworkBGPUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics bgpConfig := createNetworkBGPConfiguration(d) if err := createNetworkBGPUpdateRequest(client.NewBGPConfigurationUpdateRequest, &bgpConfig).Execute(); err != nil { diff --git a/equinix/resource_network_bgp_acc_test.go b/equinix/resource_network_bgp_acc_test.go index ad8a04bc8..0535ca3bf 100644 --- a/equinix/resource_network_bgp_acc_test.go +++ b/equinix/resource_network_bgp_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -128,7 +129,7 @@ func testAccNeBGPExists(resourceName string, bgpConfig *ne.BGPConfiguration) res if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_network_device.go b/equinix/resource_network_device.go index bdefb4b56..8283c447e 100644 --- a/equinix/resource_network_device.go +++ b/equinix/resource_network_device.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "io" @@ -874,8 +875,8 @@ func createVendorConfigurationSchema() map[string]*schema.Schema { } func resourceNetworkDeviceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics primary, secondary := createNetworkDevices(d) var err error @@ -927,8 +928,8 @@ func resourceNetworkDeviceCreate(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkDeviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics var err error var primary, secondary *ne.Device @@ -953,8 +954,8 @@ func resourceNetworkDeviceRead(ctx context.Context, d *schema.ResourceData, m in } func resourceNetworkDeviceUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics supportedChanges := []string{ neDeviceSchemaNames["Name"], neDeviceSchemaNames["TermLength"], @@ -989,8 +990,8 @@ func resourceNetworkDeviceUpdate(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkDeviceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics waitConfigs := []*retry.StateChangeConf{ createNetworkDeviceStatusDeleteWaitConfiguration(client.GetDevice, d.Id(), 5*time.Second, d.Timeout(schema.TimeoutDelete)), @@ -1070,7 +1071,7 @@ func createNetworkDevices(d *schema.ResourceData) (*ne.Device, *ne.Device) { primary.AccountNumber = ne.String(v.(string)) } if v, ok := d.GetOk(neDeviceSchemaNames["Notifications"]); ok { - primary.Notifications = expandSetToStringList(v.(*schema.Set)) + primary.Notifications = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := d.GetOk(neDeviceSchemaNames["PurchaseOrderNumber"]); ok { primary.PurchaseOrderNumber = ne.String(v.(string)) @@ -1092,7 +1093,7 @@ func createNetworkDevices(d *schema.ResourceData) (*ne.Device, *ne.Device) { } primary.IsSelfManaged = ne.Bool(d.Get(neDeviceSchemaNames["IsSelfManaged"]).(bool)) if v, ok := d.GetOk(neDeviceSchemaNames["VendorConfiguration"]); ok { - primary.VendorConfiguration = expandInterfaceMapToStringMap(v.(map[string]interface{})) + primary.VendorConfiguration = internal.ExpandInterfaceMapToStringMap(v.(map[string]interface{})) } if v, ok := d.GetOk(neDeviceSchemaNames["WanInterfaceId"]); ok { primary.WanInterfaceId = ne.String(v.(string)) @@ -1316,7 +1317,7 @@ func expandNetworkDeviceSecondary(devices []interface{}) *ne.Device { transformed.AccountNumber = ne.String(v.(string)) } if v, ok := device[neDeviceSchemaNames["Notifications"]]; ok { - transformed.Notifications = expandSetToStringList(v.(*schema.Set)) + transformed.Notifications = internal.ExpandSetToStringList(v.(*schema.Set)) } if v, ok := device[neDeviceSchemaNames["AdditionalBandwidth"]]; ok && !isEmpty(v) { transformed.AdditionalBandwidth = ne.Int(v.(int)) @@ -1325,7 +1326,7 @@ func expandNetworkDeviceSecondary(devices []interface{}) *ne.Device { transformed.WanInterfaceId = ne.String(v.(string)) } if v, ok := device[neDeviceSchemaNames["VendorConfiguration"]]; ok { - transformed.VendorConfiguration = expandInterfaceMapToStringMap(v.(map[string]interface{})) + transformed.VendorConfiguration = internal.ExpandInterfaceMapToStringMap(v.(map[string]interface{})) } if v, ok := device[neDeviceSchemaNames["UserPublicKey"]]; ok { userKeys := expandNetworkDeviceUserKeys(v.(*schema.Set)) @@ -1496,7 +1497,7 @@ func fillNetworkDeviceUpdateRequest(updateReq ne.DeviceUpdateRequest, changes ma case neDeviceSchemaNames["TermLength"]: updateReq.WithTermLength(changeValue.(int)) case neDeviceSchemaNames["Notifications"]: - updateReq.WithNotifications(expandSetToStringList(changeValue.(*schema.Set))) + updateReq.WithNotifications(internal.ExpandSetToStringList(changeValue.(*schema.Set))) case neDeviceSchemaNames["AdditionalBandwidth"]: updateReq.WithAdditionalBandwidth(changeValue.(int)) case neDeviceSchemaNames["ACLTemplateUUID"]: diff --git a/equinix/resource_network_device_acc_test.go b/equinix/resource_network_device_acc_test.go index 5f4bc3100..b3369f42e 100644 --- a/equinix/resource_network_device_acc_test.go +++ b/equinix/resource_network_device_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -46,7 +47,7 @@ func testSweepNetworkDevice(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - devices, err := config.ne.GetDevices([]string{ + devices, err := config.Ne.GetDevices([]string{ ne.DeviceStateInitializing, ne.DeviceStateProvisioned, ne.DeviceStateProvisioning, @@ -68,7 +69,7 @@ func testSweepNetworkDevice(region string) error { if ne.StringValue(device.RedundancyType) != "PRIMARY" { continue } - if err := config.ne.DeleteDevice(ne.StringValue(device.UUID)); err != nil { + if err := config.Ne.DeleteDevice(ne.StringValue(device.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting NetworkDevice resource %s (%s): %s", ne.StringValue(device.UUID), ne.StringValue(device.Name), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for NetworkDevice resource %s (%s)", ne.StringValue(device.UUID), ne.StringValue(device.Name)) @@ -906,7 +907,7 @@ func testAccNeDeviceExists(resourceName string, device *ne.Device) resource.Test if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne resp, err := client.GetDevice(rs.Primary.ID) if err != nil { return fmt.Errorf("error when fetching network device '%s': %s", rs.Primary.ID, err) @@ -921,7 +922,7 @@ func testAccNeDeviceSecondaryExists(primary, secondary *ne.Device) resource.Test if ne.StringValue(primary.RedundantUUID) == "" { return fmt.Errorf("secondary device UUID is not set") } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne resp, err := client.GetDevice(ne.StringValue(primary.RedundantUUID)) if err != nil { return fmt.Errorf("error when fetching network device '%s': %s", ne.StringValue(primary.RedundantUUID), err) @@ -940,7 +941,7 @@ func testAccNeDevicePairExists(resourceName string, primary, secondary *ne.Devic if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne resp, err := client.GetDevice(rs.Primary.ID) if err != nil { return fmt.Errorf("error when fetching primary network device '%s': %s", rs.Primary.ID, err) @@ -1130,7 +1131,7 @@ func testAccNeDeviceACL(resourceName string, device *ne.Device) resource.TestChe } templateId := rs.Primary.ID deviceID := ne.StringValue(device.UUID) - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if ne.StringValue(device.ACLTemplateUUID) != rs.Primary.ID { return fmt.Errorf("acl_template_id for device %s does not match %v - %v", deviceID, ne.StringValue(device.ACLTemplateUUID), templateId) } diff --git a/equinix/resource_network_device_link.go b/equinix/resource_network_device_link.go index ac77036c9..dbad8e07a 100644 --- a/equinix/resource_network_device_link.go +++ b/equinix/resource_network_device_link.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "time" @@ -220,8 +221,8 @@ func createNetworkDeviceLinkConnectionResourceSchema() map[string]*schema.Schema } func resourceNetworkDeviceLinkCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics link := createNetworkDeviceLink(d) uuid, err := client.CreateDeviceLinkGroup(link) @@ -242,8 +243,8 @@ func resourceNetworkDeviceLinkCreate(ctx context.Context, d *schema.ResourceData } func resourceNetworkDeviceLinkRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics link, err := client.GetDeviceLinkGroup(d.Id()) if err != nil { @@ -266,8 +267,8 @@ func resourceNetworkDeviceLinkRead(ctx context.Context, d *schema.ResourceData, } func resourceNetworkDeviceLinkUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics changes := getResourceDataChangedKeys([]string{ networkDeviceLinkSchemaNames["Name"], networkDeviceLinkSchemaNames["Subnet"], @@ -304,8 +305,8 @@ func resourceNetworkDeviceLinkUpdate(ctx context.Context, d *schema.ResourceData } func resourceNetworkDeviceLinkDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics if err := client.DeleteDeviceLinkGroup(d.Id()); err != nil { if isRestNotFoundError(err) { @@ -489,7 +490,7 @@ func networkDeviceLinkDeviceKey(v interface{}) string { } func networkDeviceLinkDeviceHash(v interface{}) int { - return hashcodeString(networkDeviceLinkDeviceKey(v)) + return internal.HashcodeString(networkDeviceLinkDeviceKey(v)) } func networkDeviceLinkConnectionKey(v interface{}) string { @@ -511,5 +512,5 @@ func networkDeviceLinkConnectionKey(v interface{}) string { } func networkDeviceLinkConnectionHash(v interface{}) int { - return hashcodeString(networkDeviceLinkConnectionKey(v)) + return internal.HashcodeString(networkDeviceLinkConnectionKey(v)) } diff --git a/equinix/resource_network_device_link_acc_test.go b/equinix/resource_network_device_link_acc_test.go index 0a4901fb4..3ccf29629 100644 --- a/equinix/resource_network_device_link_acc_test.go +++ b/equinix/resource_network_device_link_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -28,7 +29,7 @@ func testSweepNetworkDeviceLink(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - links, err := config.ne.GetDeviceLinkGroups() + links, err := config.Ne.GetDeviceLinkGroups() if err != nil { log.Printf("[INFO][SWEEPER_LOG] error fetching device links list: %s", err) return err @@ -39,7 +40,7 @@ func testSweepNetworkDeviceLink(region string) error { nonSweepableCount++ continue } - if err := config.ne.DeleteDeviceLinkGroup(ne.StringValue(link.UUID)); err != nil { + if err := config.Ne.DeleteDeviceLinkGroup(ne.StringValue(link.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting NetworkDeviceLink resource %s (%s): %s", ne.StringValue(link.UUID), ne.StringValue(link.Name), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for NetworkDeviceLink resource %s (%s)", ne.StringValue(link.UUID), ne.StringValue(link.Name)) @@ -157,7 +158,7 @@ func testAccNeDeviceLinkExists(resourceName string, deviceLink *ne.DeviceLinkGro if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_network_device_test.go b/equinix/resource_network_device_test.go index 60db2674a..c61db7b1c 100644 --- a/equinix/resource_network_device_test.go +++ b/equinix/resource_network_device_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "io" @@ -143,7 +144,7 @@ func TestNetworkDevice_updateResourceData(t *testing.T) { assert.Empty(t, d.Get(neDeviceSchemaNames["LicenseToken"]), "LicenseToken is empty") assert.Equal(t, ne.StringValue(inputPrimary.ACLTemplateUUID), d.Get(neDeviceSchemaNames["ACLTemplateUUID"]), "ACLTemplateUUID matches") assert.Equal(t, ne.StringValue(inputPrimary.AccountNumber), d.Get(neDeviceSchemaNames["AccountNumber"]), "AccountNumber matches") - assert.Equal(t, inputPrimary.Notifications, expandSetToStringList(d.Get(neDeviceSchemaNames["Notifications"]).(*schema.Set)), "Notifications matches") + assert.Equal(t, inputPrimary.Notifications, internal.ExpandSetToStringList(d.Get(neDeviceSchemaNames["Notifications"]).(*schema.Set)), "Notifications matches") assert.Equal(t, ne.StringValue(inputPrimary.PurchaseOrderNumber), d.Get(neDeviceSchemaNames["PurchaseOrderNumber"]), "PurchaseOrderNumber matches") assert.Equal(t, ne.IntValue(inputPrimary.TermLength), d.Get(neDeviceSchemaNames["TermLength"]), "TermLength matches") assert.Equal(t, ne.IntValue(inputPrimary.AdditionalBandwidth), d.Get(neDeviceSchemaNames["AdditionalBandwidth"]), "AdditionalBandwidth matches") @@ -152,7 +153,7 @@ func TestNetworkDevice_updateResourceData(t *testing.T) { assert.Empty(t, d.Get(neDeviceSchemaNames["WanInterfaceId"]), "Wan Interface Id is empty") assert.Equal(t, ne.IntValue(inputPrimary.CoreCount), d.Get(neDeviceSchemaNames["CoreCount"]), "CoreCount matches") assert.Equal(t, ne.BoolValue(inputPrimary.IsSelfManaged), d.Get(neDeviceSchemaNames["IsSelfManaged"]), "IsSelfManaged matches") - assert.Equal(t, inputPrimary.VendorConfiguration, expandInterfaceMapToStringMap(d.Get(neDeviceSchemaNames["VendorConfiguration"]).(map[string]interface{})), "VendorConfiguration matches") + assert.Equal(t, inputPrimary.VendorConfiguration, internal.ExpandInterfaceMapToStringMap(d.Get(neDeviceSchemaNames["VendorConfiguration"]).(map[string]interface{})), "VendorConfiguration matches") assert.Equal(t, inputPrimary.UserPublicKey, expandNetworkDeviceUserKeys(d.Get(neDeviceSchemaNames["UserPublicKey"]).(*schema.Set))[0], "UserPublicKey matches") assert.Equal(t, ne.IntValue(inputPrimary.ASN), d.Get(neDeviceSchemaNames["ASN"]), "ASN matches") assert.Equal(t, ne.StringValue(inputPrimary.ZoneCode), d.Get(neDeviceSchemaNames["ZoneCode"]), "ZoneCode matches") @@ -296,7 +297,7 @@ func TestNetworkDevice_expandSecondary(t *testing.T) { LicenseFile: ne.String(input[0].(map[string]interface{})[neDeviceSchemaNames["LicenseFile"]].(string)), ACLTemplateUUID: ne.String(input[0].(map[string]interface{})[neDeviceSchemaNames["ACLTemplateUUID"]].(string)), AccountNumber: ne.String(input[0].(map[string]interface{})[neDeviceSchemaNames["AccountNumber"]].(string)), - Notifications: expandSetToStringList(input[0].(map[string]interface{})[neDeviceSchemaNames["Notifications"]].(*schema.Set)), + Notifications: internal.ExpandSetToStringList(input[0].(map[string]interface{})[neDeviceSchemaNames["Notifications"]].(*schema.Set)), AdditionalBandwidth: ne.Int(input[0].(map[string]interface{})[neDeviceSchemaNames["AdditionalBandwidth"]].(int)), VendorConfiguration: map[string]string{ "key": "value", diff --git a/equinix/resource_network_file.go b/equinix/resource_network_file.go index 96dd4b23d..179bb3c52 100644 --- a/equinix/resource_network_file.go +++ b/equinix/resource_network_file.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "github.com/equinix/ne-go" @@ -111,8 +112,8 @@ func createNetworkFileSchema() map[string]*schema.Schema { } func resourceNetworkFileCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics fileRequest := createFileRequest(d) uuid, err := client.UploadFile(fileRequest["MetroCode"], fileRequest["DeviceTypeCode"], fileRequest["ProcessType"], @@ -127,8 +128,8 @@ func resourceNetworkFileCreate(ctx context.Context, d *schema.ResourceData, m in } func resourceNetworkFileRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics file, err := client.GetFile(d.Id()) if err != nil { diff --git a/equinix/resource_network_file_acc_test.go b/equinix/resource_network_file_acc_test.go index e66f30cf5..40d646805 100644 --- a/equinix/resource_network_file_acc_test.go +++ b/equinix/resource_network_file_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "fmt" "testing" @@ -65,7 +66,7 @@ func testAccNetworkFileExists(resourceName string, file *ne.File) resource.TestC if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_network_ssh_key.go b/equinix/resource_network_ssh_key.go index 788e0efe8..2e0ca3d19 100644 --- a/equinix/resource_network_ssh_key.go +++ b/equinix/resource_network_ssh_key.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "net/http" @@ -76,8 +77,8 @@ func createNetworkSSHKeyResourceSchema() map[string]*schema.Schema { } func resourceNetworkSSHKeyCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics key := createNetworkSSHKey(d) uuid, err := client.CreateSSHPublicKey(key) @@ -90,8 +91,8 @@ func resourceNetworkSSHKeyCreate(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkSSHKeyRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics key, err := client.GetSSHPublicKey(d.Id()) if err != nil { @@ -110,8 +111,8 @@ func resourceNetworkSSHKeyRead(ctx context.Context, d *schema.ResourceData, m in } func resourceNetworkSSHKeyDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics if err := client.DeleteSSHPublicKey(d.Id()); err != nil { if restErr, ok := err.(rest.Error); ok { diff --git a/equinix/resource_network_ssh_key_acc_test.go b/equinix/resource_network_ssh_key_acc_test.go index 9c71b2f80..f00f0ef6b 100644 --- a/equinix/resource_network_ssh_key_acc_test.go +++ b/equinix/resource_network_ssh_key_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -27,7 +28,7 @@ func testSweepNetworkSSHKey(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - keys, err := config.ne.GetSSHPublicKeys() + keys, err := config.Ne.GetSSHPublicKeys() if err != nil { log.Printf("[INFO][SWEEPER_LOG] error fetching NetworkSSHKey list: %s", err) return err @@ -38,7 +39,7 @@ func testSweepNetworkSSHKey(region string) error { nonSweepableCount++ continue } - if err := config.ne.DeleteSSHPublicKey(ne.StringValue(key.UUID)); err != nil { + if err := config.Ne.DeleteSSHPublicKey(ne.StringValue(key.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting NetworkSSHKey resource %s (%s): %s", ne.StringValue(key.UUID), ne.StringValue(key.Name), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for NetworkSSHKey resource %s (%s)", ne.StringValue(key.UUID), ne.StringValue(key.Name)) @@ -96,7 +97,7 @@ func testAccNetworkSSHKeyExists(resourceName string, key *ne.SSHPublicKey) resou if !ok { return fmt.Errorf("resource not found: %s", resourceName) } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } diff --git a/equinix/resource_network_ssh_user.go b/equinix/resource_network_ssh_user.go index 8bf775e42..211f83313 100644 --- a/equinix/resource_network_ssh_user.go +++ b/equinix/resource_network_ssh_user.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" @@ -74,8 +75,8 @@ func createNetworkSSHUserResourceSchema() map[string]*schema.Schema { } func resourceNetworkSSHUserCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics user := createNetworkSSHUser(d) @@ -102,8 +103,8 @@ func resourceNetworkSSHUserCreate(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkSSHUserRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics user, err := client.GetSSHUser(d.Id()) if err != nil { @@ -116,8 +117,8 @@ func resourceNetworkSSHUserRead(ctx context.Context, d *schema.ResourceData, m i } func resourceNetworkSSHUserUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics updateReq := client.NewSSHUserUpdateRequest(d.Id()) if v, ok := d.GetOk(networkSSHUserSchemaNames["Password"]); ok && d.HasChange(networkSSHUserSchemaNames["Password"]) { @@ -125,8 +126,8 @@ func resourceNetworkSSHUserUpdate(ctx context.Context, d *schema.ResourceData, m } if d.HasChange(networkSSHUserSchemaNames["DeviceUUIDs"]) { a, b := d.GetChange(networkSSHUserSchemaNames["DeviceUUIDs"]) - aList := expandSetToStringList(a.(*schema.Set)) - bList := expandSetToStringList(b.(*schema.Set)) + aList := internal.ExpandSetToStringList(a.(*schema.Set)) + bList := internal.ExpandSetToStringList(b.(*schema.Set)) updateReq.WithDeviceChange(aList, bList) } if err := updateReq.Execute(); err != nil { @@ -137,8 +138,8 @@ func resourceNetworkSSHUserUpdate(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkSSHUserDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(*Config).ne - m.(*Config).addModuleToNEUserAgent(&client, d) + client := m.(*internal.Config).Ne + m.(*internal.Config).AddModuleToNEUserAgent(&client, d) var diags diag.Diagnostics if err := client.DeleteSSHUser(d.Id()); err != nil { return diag.FromErr(err) @@ -158,7 +159,7 @@ func createNetworkSSHUser(d *schema.ResourceData) ne.SSHUser { user.Password = ne.String(v.(string)) } if v, ok := d.GetOk(networkSSHUserSchemaNames["DeviceUUIDs"]); ok { - user.DeviceUUIDs = expandSetToStringList(v.(*schema.Set)) + user.DeviceUUIDs = internal.ExpandSetToStringList(v.(*schema.Set)) } return user } diff --git a/equinix/resource_network_ssh_user_acc_test.go b/equinix/resource_network_ssh_user_acc_test.go index f118b4949..57a0a3014 100644 --- a/equinix/resource_network_ssh_user_acc_test.go +++ b/equinix/resource_network_ssh_user_acc_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "context" "fmt" "log" @@ -29,7 +30,7 @@ func testSweepNetworkSSHUser(region string) error { log.Printf("[INFO][SWEEPER_LOG] error loading configuration: %s", err) return err } - users, err := config.ne.GetSSHUsers() + users, err := config.Ne.GetSSHUsers() if err != nil { log.Printf("[INFO][SWEEPER_LOG] error fetching NetworkSSHUser list: %s", err) return err @@ -38,7 +39,7 @@ func testSweepNetworkSSHUser(region string) error { if !isSweepableTestResource(ne.StringValue(user.Username)) { continue } - if err := config.ne.DeleteSSHUser(ne.StringValue(user.UUID)); err != nil { + if err := config.Ne.DeleteSSHUser(ne.StringValue(user.UUID)); err != nil { log.Printf("[INFO][SWEEPER_LOG] error deleting NetworkSSHUser resource %s (%s): %s", ne.StringValue(user.UUID), ne.StringValue(user.Username), err) } else { log.Printf("[INFO][SWEEPER_LOG] sent delete request for NetworkSSHUser resource %s (%s)", ne.StringValue(user.UUID), ne.StringValue(user.Username)) @@ -78,7 +79,7 @@ func testAccNeSSHUserExists(resourceName string, user *ne.SSHUser) resource.Test if rs.Primary.ID == "" { return fmt.Errorf("resource has no ID attribute set") } - client := testAccProvider.Meta().(*Config).ne + client := testAccProvider.Meta().(*internal.Config).Ne resp, err := client.GetSSHUser(rs.Primary.ID) if err != nil { return fmt.Errorf("error when fetching SSH user '%s': %s", rs.Primary.ID, err) diff --git a/equinix/resource_network_ssh_user_test.go b/equinix/resource_network_ssh_user_test.go index 9145ccefe..0c7d4997f 100644 --- a/equinix/resource_network_ssh_user_test.go +++ b/equinix/resource_network_ssh_user_test.go @@ -1,6 +1,7 @@ package equinix import ( + "github.com/equinix/terraform-provider-equinix/equinix/internal" "testing" "github.com/equinix/ne-go" @@ -44,5 +45,5 @@ func TestNetworkSSHUser_updateResourceData(t *testing.T) { assert.Nil(t, err, "Update of resource data does not return error") assert.Equal(t, ne.StringValue(input.Username), d.Get(networkSSHUserSchemaNames["Username"]), "Username matches") assert.Equal(t, ne.StringValue(input.Password), d.Get(networkSSHUserSchemaNames["Password"]), "Password matches") - assert.Equal(t, input.DeviceUUIDs, expandSetToStringList(d.Get(networkSSHUserSchemaNames["DeviceUUIDs"]).(*schema.Set)), "DeviceUUIDs matches") + assert.Equal(t, input.DeviceUUIDs, internal.ExpandSetToStringList(d.Get(networkSSHUserSchemaNames["DeviceUUIDs"]).(*schema.Set)), "DeviceUUIDs matches") } diff --git a/equinix/utils.go b/equinix/utils.go deleted file mode 100644 index 3ac610b68..000000000 --- a/equinix/utils.go +++ /dev/null @@ -1,75 +0,0 @@ -package equinix - -import ( - "strconv" - "strings" -) - -func contains(s []string, e string) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - -func stringArrToIfArr(sli []string) []interface{} { - var arr []interface{} - for _, v := range sli { - arr = append(arr, v) - } - return arr -} - -func convertStringArr(ifaceArr []interface{}) []string { - var arr []string - for _, v := range ifaceArr { - if v == nil { - continue - } - arr = append(arr, v.(string)) - } - return arr -} - -func convertIntArr(ifaceArr []interface{}) []string { - var arr []string - for _, v := range ifaceArr { - if v == nil { - continue - } - arr = append(arr, strconv.Itoa(v.(int))) - } - return arr -} - -func convertIntArr2(ifaceArr []interface{}) []int { - var arr []int - for _, v := range ifaceArr { - if v == nil { - continue - } - arr = append(arr, v.(int)) - } - return arr -} - -func toLower(v interface{}) string { - return strings.ToLower(v.(string)) -} - -// from https://stackoverflow.com/a/45428032 -func difference(a, b []string) []string { - mb := make(map[string]struct{}, len(b)) - for _, x := range b { - mb[x] = struct{}{} - } - var diff []string - for _, x := range a { - if _, found := mb[x]; !found { - diff = append(diff, x) - } - } - return diff -}