From 67e172f7ebb290647012da89617f6c2fa946f670 Mon Sep 17 00:00:00 2001
From: thogarty <139183873+thogarty@users.noreply.github.com>
Date: Fri, 19 Apr 2024 11:05:33 -0700
Subject: [PATCH] refactor: fabric connection equinix sdk go migration (#606)
* Removed all references to `fabric-go` and replaced with feature parity
of `equinix-sdk-go/fabricv4`
* Using reference to branch `equinix-sdk-go-migration` in code review on
equinix-sdk-go/fabricv4 repo
* Patches in this branch are necessary to resolve issues where the
Fabric APIs are not adhering to API specs
* Tickets have been cut for Fabric Teams to resolve; just using patching
as short term fix
* Use Getters+Setters for all setting and retrieval of
`equinix-sdk-go/fabricv4` structs
* Improve request creation by only setting attributes on Go structs when
they are given in the Terraform. Removes zero valued entries in API
requests causing unintended side effects
* Updated acceptance tests to account for SDK update.
* Updated config to create `equinix-sdk-go/fabricv4` using correct auth
method
* Instantiated `equinix-sdk-go/fabricv4` with the correct user agent for
Terraform to be used in metrics
* Handling error type assertions properly to avoid chaining errors
during runtime
---
docs/resources/equinix_fabric_cloud_router.md | 7 +-
docs/resources/equinix_fabric_connection.md | 7 +-
...ata_source_fabric_cloud_router_acc_test.go | 2 +-
.../data_source_fabric_connection_acc_test.go | 6 +-
.../data_source_fabric_network_acc_test.go | 2 +-
equinix/data_source_fabric_port_acc_test.go | 44 +-
..._source_fabric_service_profile_acc_test.go | 9 +-
equinix/resource_fabric_cloud_router.go | 299 +++--
.../resource_fabric_cloud_router_acc_test.go | 12 +-
equinix/resource_fabric_connection.go | 1056 ++++++++---------
.../resource_fabric_connection_acc_test.go | 25 +-
equinix/resource_fabric_network.go | 209 ++--
equinix/resource_fabric_network_acc_test.go | 11 +-
equinix/resource_fabric_port.go | 259 ++--
equinix/resource_fabric_routing_protocol.go | 623 +++++-----
...source_fabric_routing_protocol_acc_test.go | 11 +-
equinix/resource_fabric_service_profile.go | 825 +++++++------
...esource_fabric_service_profile_acc_test.go | 24 +-
internal/config/config.go | 85 +-
internal/errors/errors.go | 34 +-
.../schema/fabric_common_mapping_helpers.go | 320 ++---
21 files changed, 1924 insertions(+), 1946 deletions(-)
diff --git a/docs/resources/equinix_fabric_cloud_router.md b/docs/resources/equinix_fabric_cloud_router.md
index dd638782f..43c889194 100644
--- a/docs/resources/equinix_fabric_cloud_router.md
+++ b/docs/resources/equinix_fabric_cloud_router.md
@@ -51,7 +51,6 @@ resource "equinix_fabric_cloud_router" "new_cloud_router"{
- `location` (Block Set, Min: 1, Max: 1) Fabric Cloud Router location (see [below for nested schema](#nestedblock--location))
- `name` (String) Fabric Cloud Router name. An alpha-numeric 24 characters string which can include only hyphens and underscores
- `notifications` (Block List, Min: 1) Preferences for notifications on Fabric Cloud Router configuration or status changes (see [below for nested schema](#nestedblock--notifications))
-- `order` (Block Set, Min: 1, Max: 1) Order information related to this Fabric Cloud Router (see [below for nested schema](#nestedblock--order))
- `package` (Block Set, Min: 1, Max: 1) Fabric Cloud Router Package Type (see [below for nested schema](#nestedblock--package))
- `project` (Block Set, Min: 1, Max: 1) Customer resource hierarchy project information. Applicable to customers onboarded to Equinix Identity and Access Management. For more information see Identity and Access Management: Projects (see [below for nested schema](#nestedblock--project))
- `type` (String) Defines the FCR type like; XF_ROUTER
@@ -60,6 +59,7 @@ resource "equinix_fabric_cloud_router" "new_cloud_router"{
- `description` (String) Customer-provided Fabric Cloud Router description
- `href` (String) Fabric Cloud Router URI information
+- `order` (Block Set, Min: 1, Max: 1) Order information related to this Fabric Cloud Router (see [below for nested schema](#nestedblock--order))
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
- `uuid` (String) Equinix-assigned Fabric Cloud Router identifier
@@ -112,10 +112,13 @@ Optional:
Optional:
+- `purchase_order_number` (String) Purchase order number
+
+Read-Only:
+
- `billing_tier` (String) Billing tier for connection bandwidth
- `order_id` (String) Order Identification
- `order_number` (String) Order Reference Number
-- `purchase_order_number` (String) Purchase order number
diff --git a/docs/resources/equinix_fabric_connection.md b/docs/resources/equinix_fabric_connection.md
index 0ba251a64..fd836288f 100644
--- a/docs/resources/equinix_fabric_connection.md
+++ b/docs/resources/equinix_fabric_connection.md
@@ -663,7 +663,6 @@ Port to IBM Connections could be modified from IBM Service Provider Side by usin
- `bandwidth` (Number) Connection bandwidth in Mbps
- `name` (String) Connection name. An alpha-numeric 24 characters string which can include only hyphens and underscores
- `notifications` (Block List, Min: 1) Preferences for notifications on connection configuration or status changes (see [below for nested schema](#nestedblock--notifications))
-- `order` (Block Set, Min: 1, Max: 1) Order details (see [below for nested schema](#nestedblock--order))
- `type` (String) Defines the connection type like EVPL_VC, EPL_VC, IPWAN_VC, IP_VC, ACCESS_EPL_VC, EVPLAN_VC, EPLAN_VC, EIA_VC, EC_VC
- `z_side` (Block Set, Min: 1, Max: 1) Destination or Provider side connection configuration object of the multi-segment connection (see [below for nested schema](#nestedblock--z_side))
@@ -671,6 +670,7 @@ Port to IBM Connections could be modified from IBM Service Provider Side by usin
- `additional_info` (List of Map of String) Connection additional information
- `description` (String) Customer-provided connection description
+- `order` (Block Set, Min: 1, Max: 1) Order details (see [below for nested schema](#nestedblock--order))
- `project` (Block Set, Max: 1) Project information (see [below for nested schema](#nestedblock--project))
- `redundancy` (Block Set, Max: 1) Connection Redundancy Configuration (see [below for nested schema](#nestedblock--redundancy))
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
@@ -909,10 +909,13 @@ Optional:
Optional:
+- `purchase_order_number` (String) Purchase order number
+
+Read-Only:
+
- `billing_tier` (String) Billing tier for connection bandwidth
- `order_id` (String) Order Identification
- `order_number` (String) Order Reference Number
-- `purchase_order_number` (String) Purchase order number
diff --git a/equinix/data_source_fabric_cloud_router_acc_test.go b/equinix/data_source_fabric_cloud_router_acc_test.go
index 396727edc..08881d295 100644
--- a/equinix/data_source_fabric_cloud_router_acc_test.go
+++ b/equinix/data_source_fabric_cloud_router_acc_test.go
@@ -11,7 +11,7 @@ import (
func TestAccDataSourceFabricCloudRouter_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
ExternalProviders: acceptance.TestExternalProviders,
Providers: acceptance.TestAccProviders,
Steps: []resource.TestStep{
diff --git a/equinix/data_source_fabric_connection_acc_test.go b/equinix/data_source_fabric_connection_acc_test.go
index 1cb4adbe3..d463fbeea 100644
--- a/equinix/data_source_fabric_connection_acc_test.go
+++ b/equinix/data_source_fabric_connection_acc_test.go
@@ -11,11 +11,11 @@ func TestAccFabricDataSourceConnection_PFCR(t *testing.T) {
ports := GetFabricEnvPorts(t)
var aSidePortUuid, zSidePortUuid string
if len(ports) > 0 {
- aSidePortUuid = ports["pfcr"]["dot1q"][0].Uuid
- zSidePortUuid = ports["pfcr"]["dot1q"][1].Uuid
+ aSidePortUuid = ports["pfcr"]["dot1q"][0].GetUuid()
+ zSidePortUuid = ports["pfcr"]["dot1q"][1].GetUuid()
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: CheckConnectionDelete,
Steps: []resource.TestStep{
diff --git a/equinix/data_source_fabric_network_acc_test.go b/equinix/data_source_fabric_network_acc_test.go
index 9267cb5c6..274cefe6a 100644
--- a/equinix/data_source_fabric_network_acc_test.go
+++ b/equinix/data_source_fabric_network_acc_test.go
@@ -10,7 +10,7 @@ import (
func TestAccDataSourceFabricNetwork_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
ExternalProviders: acceptance.TestExternalProviders,
Providers: acceptance.TestAccProviders,
Steps: []resource.TestStep{
diff --git a/equinix/data_source_fabric_port_acc_test.go b/equinix/data_source_fabric_port_acc_test.go
index 67bb92a17..d43606312 100644
--- a/equinix/data_source_fabric_port_acc_test.go
+++ b/equinix/data_source_fabric_port_acc_test.go
@@ -3,7 +3,7 @@ package equinix_test
import (
"encoding/json"
"fmt"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"os"
"testing"
@@ -15,7 +15,7 @@ const (
FabricDedicatedPortEnvVar = "TF_ACC_FABRIC_DEDICATED_PORTS"
)
-type EnvPorts map[string]map[string][]v4.Port
+type EnvPorts map[string]map[string][]fabricv4.PortResponse
func GetFabricEnvPorts(t *testing.T) EnvPorts {
var ports EnvPorts
@@ -28,27 +28,29 @@ func GetFabricEnvPorts(t *testing.T) EnvPorts {
func TestAccDataSourceFabricPort_PNFV(t *testing.T) {
ports := GetFabricEnvPorts(t)
- var port v4.Port
+ var port fabricv4.PortResponse
var portType, portState, portEncapsulationType, portRedundancyPriority string
if len(ports) > 0 {
port = ports["pnfv"]["dot1q"][0]
- portType = string(*port.Type_)
- portState = string(*port.State)
- portEncapsulationType = port.Encapsulation.Type_
- portRedundancyPriority = string(*port.Redundancy.Priority)
+ portType = string(port.GetType())
+ portState = string(port.GetState())
+ portEncapsulation := port.GetEncapsulation()
+ portEncapsulationType = string(portEncapsulation.GetType())
+ portRedundancy := port.GetRedundancy()
+ portRedundancyPriority = string(portRedundancy.GetPriority())
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
ExternalProviders: acceptance.TestExternalProviders,
Providers: acceptance.TestAccProviders,
Steps: []resource.TestStep{
{
- Config: testDataSourceFabricPort(port.Uuid),
+ Config: testDataSourceFabricPort(port.GetUuid()),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
- "data.equinix_fabric_port.test", "id", port.Uuid),
+ "data.equinix_fabric_port.test", "id", port.GetUuid()),
resource.TestCheckResourceAttr(
- "data.equinix_fabric_port.test", "name", port.Name),
+ "data.equinix_fabric_port.test", "name", port.GetName()),
resource.TestCheckResourceAttrSet(
"data.equinix_fabric_port.test", "bandwidth"),
resource.TestCheckResourceAttrSet(
@@ -79,27 +81,29 @@ func testDataSourceFabricPort(port_uuid string) string {
func TestAccDataSourceFabricPorts_PNFV(t *testing.T) {
ports := GetFabricEnvPorts(t)
- var port v4.Port
+ var port fabricv4.PortResponse
var portType, portState, portEncapsulationType, portRedundancyPriority string
if len(ports) > 0 {
port = ports["pnfv"]["dot1q"][0]
- portType = string(*port.Type_)
- portState = string(*port.State)
- portEncapsulationType = port.Encapsulation.Type_
- portRedundancyPriority = string(*port.Redundancy.Priority)
+ portType = string(port.GetType())
+ portState = string(port.GetState())
+ portEncapsulation := port.GetEncapsulation()
+ portEncapsulationType = string(portEncapsulation.GetType())
+ portRedundancy := port.GetRedundancy()
+ portRedundancyPriority = string(portRedundancy.GetPriority())
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
ExternalProviders: acceptance.TestExternalProviders,
Providers: acceptance.TestAccProviders,
Steps: []resource.TestStep{
{
- Config: testDataSourceFabricPorts(port.Name),
+ Config: testDataSourceFabricPorts(port.GetName()),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
- "data.equinix_fabric_ports.test", "id", port.Uuid),
+ "data.equinix_fabric_ports.test", "id", port.GetUuid()),
resource.TestCheckResourceAttr(
- "data.equinix_fabric_ports.test", "data.0.name", port.Name),
+ "data.equinix_fabric_ports.test", "data.0.name", port.GetName()),
resource.TestCheckResourceAttrSet(
"data.equinix_fabric_ports.test", "data.0.bandwidth"),
resource.TestCheckResourceAttrSet(
diff --git a/equinix/data_source_fabric_service_profile_acc_test.go b/equinix/data_source_fabric_service_profile_acc_test.go
index 5b9123ddc..e41e48508 100644
--- a/equinix/data_source_fabric_service_profile_acc_test.go
+++ b/equinix/data_source_fabric_service_profile_acc_test.go
@@ -70,13 +70,14 @@ func TestAccFabricReadServiceProfileByUuid_PFCR(t *testing.T) {
var portUuid, portMetroCode, portType string
if len(ports) > 0 {
port := ports["pfcr"]["dot1q"][0]
- portUuid = port.Uuid
- portMetroCode = port.Location.MetroCode
- portType = string(*port.Type_)
+ portUuid = port.GetUuid()
+ portMetroCodeLocation := port.GetLocation()
+ portMetroCode = portMetroCodeLocation.GetMetroCode()
+ portType = string(port.GetType())
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkServiceProfileDelete,
Steps: []resource.TestStep{
diff --git a/equinix/resource_fabric_cloud_router.go b/equinix/resource_fabric_cloud_router.go
index 44beca30e..380e0c11f 100644
--- a/equinix/resource_fabric_cloud_router.go
+++ b/equinix/resource_fabric_cloud_router.go
@@ -3,6 +3,7 @@ package equinix
import (
"context"
"fmt"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
@@ -16,7 +17,6 @@ import (
"github.com/equinix/terraform-provider-equinix/internal/config"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
)
@@ -143,7 +143,8 @@ func fabricCloudRouterResourceSchema() map[string]*schema.Schema {
},
"order": {
Type: schema.TypeSet,
- Required: true,
+ Computed: true,
+ Optional: true,
Description: "Order information related to this Fabric Cloud Router",
MaxItems: 1,
Elem: &schema.Resource{
@@ -207,86 +208,85 @@ func resourceFabricCloudRouter() *schema.Resource {
}
}
-func accountCloudRouterTerraToGo(accountList []interface{}) v4.SimplifiedAccount {
- sa := v4.SimplifiedAccount{}
- for _, ll := range accountList {
- llMap := ll.(map[string]interface{})
- ac := llMap["account_number"].(int)
- sa = v4.SimplifiedAccount{AccountNumber: int64(ac)}
+func accountCloudRouterTerraformToGo(accountList []interface{}) fabricv4.SimplifiedAccount {
+ if accountList == nil {
+ return fabricv4.SimplifiedAccount{}
}
- return sa
-}
-func locationCloudRouterTerraToGo(locationList []interface{}) v4.SimplifiedLocationWithoutIbx {
- sl := v4.SimplifiedLocationWithoutIbx{}
- for _, ll := range locationList {
- llMap := ll.(map[string]interface{})
- mc := llMap["metro_code"].(string)
- sl = v4.SimplifiedLocationWithoutIbx{MetroCode: mc}
- }
- return sl
+ simplifiedAccount := fabricv4.SimplifiedAccount{}
+ accountMap := accountList[0].(map[string]interface{})
+ accountNumber := int64(accountMap["account_number"].(int))
+ simplifiedAccount.SetAccountNumber(accountNumber)
+
+ return simplifiedAccount
}
-func packageCloudRouterTerraToGo(packageList []interface{}) v4.CloudRouterPackageType {
- p := v4.CloudRouterPackageType{}
- for _, pl := range packageList {
- plMap := pl.(map[string]interface{})
- code := plMap["code"].(string)
- p = v4.CloudRouterPackageType{Code: code}
+
+func packageCloudRouterTerraformToGo(packageList []interface{}) fabricv4.CloudRouterPostRequestPackage {
+ if packageList == nil || len(packageList) == 0 {
+ return fabricv4.CloudRouterPostRequestPackage{}
}
- return p
+
+ package_ := fabricv4.CloudRouterPostRequestPackage{}
+ packageMap := packageList[0].(map[string]interface{})
+ code := fabricv4.CloudRouterPostRequestPackageCode(packageMap["code"].(string))
+ package_.SetCode(code)
+
+ return package_
}
-func projectCloudRouterTerraToGo(projectRequest []interface{}) v4.Project {
- if projectRequest == nil {
- return v4.Project{}
- }
- mappedPr := v4.Project{}
- for _, pr := range projectRequest {
- prMap := pr.(map[string]interface{})
- projectId := prMap["project_id"].(string)
- mappedPr = v4.Project{ProjectId: projectId}
+func projectCloudRouterTerraformToGo(projectTerraform []interface{}) fabricv4.Project {
+ if projectTerraform == nil || len(projectTerraform) == 0 {
+ return fabricv4.Project{}
}
- return mappedPr
+ project := fabricv4.Project{}
+ projectMap := projectTerraform[0].(map[string]interface{})
+ projectId := projectMap["project_id"].(string)
+ project.SetProjectId(projectId)
+
+ return project
}
func resourceFabricCloudRouterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+
+ createCloudRouterRequest := fabricv4.CloudRouterPostRequest{}
+
+ createCloudRouterRequest.SetName(d.Get("name").(string))
+
+ type_ := fabricv4.CloudRouterPostRequestType(d.Get("type").(string))
+ createCloudRouterRequest.SetType(type_)
+
schemaNotifications := d.Get("notifications").([]interface{})
- notifications := equinix_fabric_schema.NotificationsToFabric(schemaNotifications)
+ notifications := equinix_fabric_schema.NotificationsTerraformToGo(schemaNotifications)
+ createCloudRouterRequest.SetNotifications(notifications)
+
schemaAccount := d.Get("account").(*schema.Set).List()
- account := accountCloudRouterTerraToGo(schemaAccount)
+ account := accountCloudRouterTerraformToGo(schemaAccount)
+ createCloudRouterRequest.SetAccount(account)
+
schemaLocation := d.Get("location").(*schema.Set).List()
- location := locationCloudRouterTerraToGo(schemaLocation)
- project := v4.Project{}
+ location := equinix_fabric_schema.LocationWithoutIBXTerraformToGo(schemaLocation)
+ createCloudRouterRequest.SetLocation(location)
+
schemaProject := d.Get("project").(*schema.Set).List()
- if len(schemaProject) != 0 {
- project = projectCloudRouterTerraToGo(schemaProject)
- }
+ project := projectCloudRouterTerraformToGo(schemaProject)
+ createCloudRouterRequest.SetProject(project)
+
schemaPackage := d.Get("package").(*schema.Set).List()
- packages := packageCloudRouterTerraToGo(schemaPackage)
-
- createRequest := v4.CloudRouterPostRequest{
- Name: d.Get("name").(string),
- Type_: d.Get("type").(string),
- Location: &location,
- Notifications: notifications,
- Package_: &packages,
- Account: &account,
- Project: &project,
- }
+ package_ := packageCloudRouterTerraformToGo(schemaPackage)
+ createCloudRouterRequest.SetPackage(package_)
- if v, ok := d.GetOk("order"); ok {
- order := equinix_fabric_schema.OrderToFabric(v.(*schema.Set).List())
- createRequest.Order = &order
+ if orderTerraform, ok := d.GetOk("order"); ok {
+ order := equinix_fabric_schema.OrderTerraformToGo(orderTerraform.(*schema.Set).List())
+ createCloudRouterRequest.SetOrder(order)
}
start := time.Now()
- fcr, _, err := client.CloudRoutersApi.CreateCloudRouter(ctx, createRequest)
+ fcr, _, err := client.CloudRoutersApi.CreateCloudRouter(ctx).CloudRouterPostRequest(createCloudRouterRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(fcr.Uuid)
+ d.SetId(fcr.GetUuid())
createTimeout := d.Timeout(schema.TimeoutCreate) - 30*time.Second - time.Since(start)
- if _, err = waitUntilCloudRouterIsProvisioned(d.Id(), meta, ctx, createTimeout); err != nil {
+ if _, err = waitUntilCloudRouterIsProvisioned(d.Id(), meta, d, ctx, createTimeout); err != nil {
return diag.Errorf("error waiting for Cloud Router (%s) to be created: %s", d.Id(), err)
}
@@ -294,9 +294,8 @@ func resourceFabricCloudRouterCreate(ctx context.Context, d *schema.ResourceData
}
func resourceFabricCloudRouterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- CloudRouter, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, d.Id())
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ cloudRouter, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, d.Id()).Execute()
if err != nil {
log.Printf("[WARN] Fabric Cloud Router %s not found , error %s", d.Id(), err)
if !strings.Contains(err.Error(), "500") {
@@ -304,82 +303,83 @@ func resourceFabricCloudRouterRead(ctx context.Context, d *schema.ResourceData,
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(CloudRouter.Uuid)
- return setCloudRouterMap(d, CloudRouter)
+ d.SetId(cloudRouter.GetUuid())
+ return setCloudRouterMap(d, cloudRouter)
}
-func setCloudRouterMap(d *schema.ResourceData, fcr v4.CloudRouter) diag.Diagnostics {
+func setCloudRouterMap(d *schema.ResourceData, fcr *fabricv4.CloudRouter) diag.Diagnostics {
diags := diag.Diagnostics{}
+ package_ := fcr.GetPackage()
+ location := fcr.GetLocation()
+ changeLog := fcr.GetChangeLog()
+ account := fcr.GetAccount()
+ notifications := fcr.GetNotifications()
+ project := fcr.GetProject()
+ order := fcr.GetOrder()
err := equinix_schema.SetMap(d, map[string]interface{}{
- "name": fcr.Name,
- "href": fcr.Href,
- "type": fcr.Type_,
- "state": fcr.State,
- "package": packageCloudRouterGoToTerra(fcr.Package_),
- "location": equinix_fabric_schema.LocationWithoutIBXToTerra(fcr.Location),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(fcr.ChangeLog),
- "account": accountCloudRouterToTerra(fcr.Account),
- "notifications": equinix_fabric_schema.NotificationsToTerra(fcr.Notifications),
- "project": equinix_fabric_schema.ProjectToTerra(fcr.Project),
- "equinix_asn": fcr.EquinixAsn,
- "bgp_ipv4_routes_count": fcr.BgpIpv4RoutesCount,
- "bgp_ipv6_routes_count": fcr.BgpIpv6RoutesCount,
- "distinct_ipv4_prefixes_count": fcr.DistinctIpv4PrefixesCount,
- "distinct_ipv6_prefixes_count": fcr.DistinctIpv6PrefixesCount,
- "connections_count": fcr.ConnectionsCount,
- "order": equinix_fabric_schema.OrderToTerra(fcr.Order),
+ "name": fcr.GetName(),
+ "href": fcr.GetHref(),
+ "type": string(fcr.GetType()),
+ "state": string(fcr.GetState()),
+ "package": packageCloudRouterGoToTerraform(&package_),
+ "location": equinix_fabric_schema.LocationWithoutIBXGoToTerraform(&location),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog),
+ "account": accountCloudRouterGoToTerraform(&account),
+ "notifications": equinix_fabric_schema.NotificationsGoToTerraform(notifications),
+ "project": equinix_fabric_schema.ProjectGoToTerraform(&project),
+ "equinix_asn": fcr.GetEquinixAsn(),
+ "bgp_ipv4_routes_count": fcr.GetBgpIpv4RoutesCount(),
+ "bgp_ipv6_routes_count": fcr.GetBgpIpv6RoutesCount(),
+ "distinct_ipv4_prefixes_count": fcr.GetDistinctIpv4PrefixesCount(),
+ "distinct_ipv6_prefixes_count": fcr.GetDistinctIpv6PrefixesCount(),
+ "connections_count": fcr.GetConnectionsCount(),
+ "order": equinix_fabric_schema.OrderGoToTerraform(&order),
})
if err != nil {
return diag.FromErr(err)
}
return diags
}
-func accountCloudRouterToTerra(account *v4.SimplifiedAccount) *schema.Set {
+func accountCloudRouterGoToTerraform(account *fabricv4.SimplifiedAccount) *schema.Set {
if account == nil {
return nil
}
- accounts := []*v4.SimplifiedAccount{account}
- mappedAccounts := make([]interface{}, len(accounts))
- for i, account := range accounts {
- mappedAccounts[i] = map[string]interface{}{
- "account_number": int(account.AccountNumber),
- }
+
+ mappedAccount := map[string]interface{}{
+ "account_number": int(account.GetAccountNumber()),
}
+
accountSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: equinix_fabric_schema.AccountSch()}),
- mappedAccounts,
+ []interface{}{mappedAccount},
)
return accountSet
}
-func packageCloudRouterGoToTerra(packageType *v4.CloudRouterPackageType) *schema.Set {
- packageTypes := []*v4.CloudRouterPackageType{packageType}
- mappedPackages := make([]interface{}, len(packageTypes))
- for i, packageType := range packageTypes {
- mappedPackages[i] = map[string]interface{}{
- "code": packageType.Code,
- }
+func packageCloudRouterGoToTerraform(packageType *fabricv4.CloudRouterPostRequestPackage) *schema.Set {
+ mappedPackage := map[string]interface{}{
+ "code": string(packageType.GetCode()),
}
packageSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: fabricCloudRouterPackageSch()}),
- mappedPackages,
+ []interface{}{mappedPackage},
)
return packageSet
}
-func getCloudRouterUpdateRequest(conn v4.CloudRouter, d *schema.ResourceData) (v4.CloudRouterChangeOperation, error) {
- changeOps := v4.CloudRouterChangeOperation{}
- existingName := conn.Name
- existingPackage := conn.Package_.Code
- updateNameVal := d.Get("name")
- updatePackageVal := d.Get("conn.Package_.Code")
+func getCloudRouterUpdateRequest(conn *fabricv4.CloudRouter, d *schema.ResourceData) (fabricv4.CloudRouterChangeOperation, error) {
+ changeOps := fabricv4.CloudRouterChangeOperation{}
+ existingName := conn.GetName()
+ existingPackage := conn.GetPackage()
+ updateNameVal := d.Get("name").(string)
+ updatePackageVal := d.Get("package.0.code").(string)
- log.Printf("existing name %s, existing Package %s, Update Name Request %s, Update Package Request %s ",
- existingName, existingPackage, updateNameVal, updatePackageVal)
+ log.Printf("[INFO] existing name %s, existing package code %s, new name %s, new package code %s ",
+ existingName, existingPackage.GetCode(), updateNameVal, updatePackageVal)
if existingName != updateNameVal {
- changeOps = v4.CloudRouterChangeOperation{Op: "replace", Path: "/name", Value: &updateNameVal}
- } else if existingPackage != updatePackageVal {
- changeOps = v4.CloudRouterChangeOperation{Op: "replace", Path: "/package", Value: &updatePackageVal}
+ changeOps = fabricv4.CloudRouterChangeOperation{Op: "replace", Path: "/name", Value: updateNameVal}
+ } else if string(existingPackage.GetCode()) != updatePackageVal {
+ changeOps = fabricv4.CloudRouterChangeOperation{Op: "replace", Path: "/package/code", Value: updatePackageVal}
} else {
return changeOps, fmt.Errorf("nothing to update for the connection %s", existingName)
}
@@ -387,11 +387,10 @@ func getCloudRouterUpdateRequest(conn v4.CloudRouter, d *schema.ResourceData) (v
}
func resourceFabricCloudRouterUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- dbConn, err := waitUntilCloudRouterIsProvisioned(d.Id(), meta, ctx, updateTimeout)
+ dbConn, err := waitUntilCloudRouterIsProvisioned(d.Id(), meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
@@ -403,14 +402,14 @@ func resourceFabricCloudRouterUpdate(ctx context.Context, d *schema.ResourceData
if err != nil {
return diag.FromErr(err)
}
- updates := []v4.CloudRouterChangeOperation{update}
- _, _, err = client.CloudRoutersApi.UpdateCloudRouterByUuid(ctx, updates, d.Id())
+ updates := []fabricv4.CloudRouterChangeOperation{update}
+ _, _, err = client.CloudRoutersApi.UpdateCloudRouterByUuid(ctx, d.Id()).CloudRouterChangeOperation(updates).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- updateFg := v4.CloudRouter{}
+
updateTimeout = d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- updateFg, err = waitForCloudRouterUpdateCompletion(d.Id(), meta, ctx, updateTimeout)
+ updateCloudRouter, err := waitForCloudRouterUpdateCompletion(d.Id(), meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
@@ -419,21 +418,21 @@ func resourceFabricCloudRouterUpdate(ctx context.Context, d *schema.ResourceData
return diag.FromErr(fmt.Errorf("errored while waiting for successful Fabric Cloud Router update, error %v", err))
}
- d.SetId(updateFg.Uuid)
- return setCloudRouterMap(d, updateFg)
+ d.SetId(updateCloudRouter.GetUuid())
+ return setCloudRouterMap(d, updateCloudRouter)
}
-func waitForCloudRouterUpdateCompletion(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.CloudRouter, error) {
+func waitForCloudRouterUpdateCompletion(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.CloudRouter, error) {
log.Printf("Waiting for Cloud Router update to complete, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
- Target: []string{string(v4.PROVISIONED_CloudRouterAccessPointState)},
+ Target: []string{string(fabricv4.CLOUDROUTERACCESSPOINTSTATE_PROVISIONED)},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -441,30 +440,30 @@ func waitForCloudRouterUpdateCompletion(uuid string, meta interface{}, ctx conte
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.CloudRouter{}
+ var dbConn *fabricv4.CloudRouter
if err == nil {
- dbConn = inter.(v4.CloudRouter)
+ dbConn = inter.(*fabricv4.CloudRouter)
}
return dbConn, err
}
-func waitUntilCloudRouterIsProvisioned(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.CloudRouter, error) {
+func waitUntilCloudRouterIsProvisioned(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.CloudRouter, error) {
log.Printf("Waiting for Cloud Router to be provisioned, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.PROVISIONING_CloudRouterAccessPointState),
+ string(fabricv4.CLOUDROUTERACCESSPOINTSTATE_PROVISIONING),
},
Target: []string{
- string(v4.PROVISIONED_CloudRouterAccessPointState),
+ string(fabricv4.CLOUDROUTERACCESSPOINTSTATE_PROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -472,55 +471,55 @@ func waitUntilCloudRouterIsProvisioned(uuid string, meta interface{}, ctx contex
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.CloudRouter{}
+ var dbConn *fabricv4.CloudRouter
if err == nil {
- dbConn = inter.(v4.CloudRouter)
+ dbConn = inter.(*fabricv4.CloudRouter)
}
return dbConn, err
}
func resourceFabricCloudRouterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
diags := diag.Diagnostics{}
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
- _, err := client.CloudRoutersApi.DeleteCloudRouterByUuid(ctx, d.Id())
+ _, err := client.CloudRoutersApi.DeleteCloudRouterByUuid(ctx, d.Id()).Execute()
if err != nil {
- errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError)
- if ok {
- // EQ-3040055 = There is an existing update in REQUESTED state
- if equinix_errors.HasModelErrorCode(errors, "EQ-3040055") {
- return diags
+ if genericError, ok := err.(*fabricv4.GenericOpenAPIError); ok {
+ if fabricErrs, ok := genericError.Model().([]fabricv4.Error); ok {
+ // EQ-3040055 = There is an existing update in REQUESTED state
+ if equinix_errors.HasErrorCode(fabricErrs, "EQ-3040055") {
+ return diags
+ }
}
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
deleteTimeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start)
- err = WaitUntilCloudRouterDeprovisioned(d.Id(), meta, ctx, deleteTimeout)
+ err = WaitUntilCloudRouterDeprovisioned(d.Id(), meta, d, ctx, deleteTimeout)
if err != nil {
return diag.FromErr(fmt.Errorf("API call failed while waiting for resource deletion. Error %v", err))
}
return diags
}
-func WaitUntilCloudRouterDeprovisioned(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) error {
+func WaitUntilCloudRouterDeprovisioned(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for Fabric Cloud Router to be deprovisioned, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.DEPROVISIONING_CloudRouterAccessPointState),
+ string(fabricv4.CLOUDROUTERACCESSPOINTSTATE_DEPROVISIONING),
},
Target: []string{
- string(v4.DEPROVISIONED_CloudRouterAccessPointState),
+ string(fabricv4.CLOUDROUTERACCESSPOINTSTATE_DEPROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.CloudRoutersApi.GetCloudRouterByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
diff --git a/equinix/resource_fabric_cloud_router_acc_test.go b/equinix/resource_fabric_cloud_router_acc_test.go
index 43060e9e3..4b55e1aa9 100644
--- a/equinix/resource_fabric_cloud_router_acc_test.go
+++ b/equinix/resource_fabric_cloud_router_acc_test.go
@@ -3,15 +3,12 @@ package equinix_test
import (
"context"
"fmt"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"testing"
"time"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
-
"github.com/equinix/terraform-provider-equinix/equinix"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
- "github.com/equinix/terraform-provider-equinix/internal/config"
-
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)
@@ -29,7 +26,7 @@ func testSweepCloudRouters(region string) error {
func TestAccCloudRouterCreateOnlyRequiredParameters_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkCloudRouterDelete,
Steps: []resource.TestStep{
@@ -103,7 +100,7 @@ func testAccCloudRouterCreateOnlyRequiredParameterConfig_PFCR(name string) strin
func TestAccCloudRouterCreateMixedParameters_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkCloudRouterDelete,
Steps: []resource.TestStep{
@@ -172,12 +169,11 @@ func testAccCloudRouterCreateMixedParameterConfig_PFCR() string {
func checkCloudRouterDelete(s *terraform.State) error {
ctx := context.Background()
- ctx = context.WithValue(ctx, v4.ContextAccessToken, acceptance.TestAccProvider.Meta().(*config.Config).FabricAuthToken)
for _, rs := range s.RootModule().Resources {
if rs.Type != "equinix_fabric_cloud_router" {
continue
}
- err := equinix.WaitUntilCloudRouterDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), ctx, 10*time.Minute)
+ err := equinix.WaitUntilCloudRouterDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), &schema.ResourceData{}, ctx, 10*time.Minute)
if err != nil {
return fmt.Errorf("API call failed while waiting for resource deletion")
}
diff --git a/equinix/resource_fabric_connection.go b/equinix/resource_fabric_connection.go
index 96b00019c..0b52e1ea8 100644
--- a/equinix/resource_fabric_connection.go
+++ b/equinix/resource_fabric_connection.go
@@ -3,7 +3,6 @@ package equinix
import (
"context"
"fmt"
- "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"log"
"strings"
"time"
@@ -14,10 +13,11 @@ import (
"github.com/equinix/terraform-provider-equinix/internal/config"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func fabricConnectionResourceSchema() map[string]*schema.Schema {
@@ -25,8 +25,8 @@ func fabricConnectionResourceSchema() map[string]*schema.Schema {
"type": {
Type: schema.TypeString,
Required: true,
- ValidateFunc: validation.StringInSlice([]string{"EVPL_VC", "EPL_VC", "IP_VC", "IPWAN_VC", "ACCESS_EPL_VC", "EVPLAN_VC", "EPLAN_VC", "EIA_VC", "EC_VC"}, false),
- Description: "Defines the connection type like EVPL_VC, EPL_VC, IPWAN_VC, IP_VC, ACCESS_EPL_VC, EVPLAN_VC, EPLAN_VC, EIA_VC, EC_VC",
+ ValidateFunc: validation.StringInSlice([]string{"EVPL_VC", "EPL_VC", "IP_VC", "IPWAN_VC", "ACCESS_EPL_VC", "EVPLAN_VC", "EPLAN_VC", "EIA_VC", "IA_VC", "EC_VC"}, false),
+ Description: "Defines the connection type like EVPL_VC, EPL_VC, IPWAN_VC, IP_VC, ACCESS_EPL_VC, EVPLAN_VC, EPLAN_VC, EIA_VC, IA_VC, EC_VC",
},
"name": {
Type: schema.TypeString,
@@ -36,7 +36,8 @@ func fabricConnectionResourceSchema() map[string]*schema.Schema {
},
"order": {
Type: schema.TypeSet,
- Required: true,
+ Optional: true,
+ Computed: true,
Description: "Order details",
MaxItems: 1,
Elem: &schema.Resource{
@@ -355,8 +356,8 @@ func serviceProfileSch() map[string]*schema.Schema {
"type": {
Type: schema.TypeString,
Required: true,
- ValidateFunc: validation.StringInSlice([]string{"L2_PROFILE", "L3_PROFILE", "ECIA_PROFILE", "ECMC_PROFILE"}, true),
- Description: "Service profile type - L2_PROFILE, L3_PROFILE, ECIA_PROFILE, ECMC_PROFILE",
+ ValidateFunc: validation.StringInSlice([]string{"L2_PROFILE", "L3_PROFILE", "ECIA_PROFILE", "ECMC_PROFILE", "IA_PROFILE"}, true),
+ Description: "Service profile type - L2_PROFILE, L3_PROFILE, ECIA_PROFILE, ECMC_PROFILE, IA_PROFILE",
},
"name": {
Type: schema.TypeString,
@@ -611,96 +612,67 @@ func resourceFabricConnection() *schema.Resource {
}
func resourceFabricConnectionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- conType := v4.ConnectionType(d.Get("type").(string))
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+
+ createConnectionRequest := fabricv4.ConnectionPostRequest{}
+
+ name := d.Get("name").(string)
+ createConnectionRequest.SetName(name)
+
+ conType := d.Get("type").(string)
+ createConnectionRequest.SetType(fabricv4.ConnectionType(conType))
+
+ if orderSchema, ok := d.GetOk("order"); ok {
+ order := equinix_fabric_schema.OrderTerraformToGo(orderSchema.(*schema.Set).List())
+ createConnectionRequest.SetOrder(order)
+ }
+
schemaNotifications := d.Get("notifications").([]interface{})
- notifications := equinix_fabric_schema.NotificationsToFabric(schemaNotifications)
- schemaRedundancy := d.Get("redundancy").(*schema.Set).List()
- red := connectionRedundancyToFabric(schemaRedundancy)
- schemaOrder := d.Get("order").(*schema.Set).List()
- order := equinix_fabric_schema.OrderToFabric(schemaOrder)
- aside := d.Get("a_side").(*schema.Set).List()
- terraConfigProject := d.Get("project").(*schema.Set).List()
- project := equinix_fabric_schema.ProjectToFabric(terraConfigProject)
- additionalInfoTerraConfig := d.Get("additional_info").([]interface{})
- additionalInfo := additionalInfoTerraToGo(additionalInfoTerraConfig)
- connectionASide := v4.ConnectionSide{}
- for _, as := range aside {
- asideMap := as.(map[string]interface{})
- accessPoint := asideMap["access_point"].(*schema.Set).List()
- serviceTokenRequest := asideMap["service_token"].(*schema.Set).List()
- additionalInfoRequest := asideMap["additional_info"].([]interface{})
-
- if len(accessPoint) != 0 {
- ap := accessPointToFabric(accessPoint)
- connectionASide = v4.ConnectionSide{AccessPoint: &ap}
- }
- if len(serviceTokenRequest) != 0 {
- mappedServiceToken, err := serviceTokenToFabric(serviceTokenRequest)
- if err != nil {
- return diag.FromErr(err)
- }
- connectionASide = v4.ConnectionSide{ServiceToken: &mappedServiceToken}
- }
- if len(additionalInfoRequest) != 0 {
- mappedAdditionalInfo := additionalInfoTerraToGo(additionalInfoRequest)
- connectionASide = v4.ConnectionSide{AdditionalInfo: mappedAdditionalInfo}
- }
+ notifications := equinix_fabric_schema.NotificationsTerraformToGo(schemaNotifications)
+ createConnectionRequest.SetNotifications(notifications)
+
+ bandwidth := d.Get("bandwidth").(int)
+ createConnectionRequest.SetBandwidth(int32(bandwidth))
+
+ if schemaRedundancy, ok := d.GetOk("redundancy"); ok {
+ redundancy := connectionRedundancyTerraformToGo(schemaRedundancy.(*schema.Set).List())
+ createConnectionRequest.SetRedundancy(redundancy)
}
- zside := d.Get("z_side").(*schema.Set).List()
- connectionZSide := v4.ConnectionSide{}
- for _, as := range zside {
- zsideMap := as.(map[string]interface{})
- accessPoint := zsideMap["access_point"].(*schema.Set).List()
- serviceTokenRequest := zsideMap["service_token"].(*schema.Set).List()
- additionalInfoRequest := zsideMap["additional_info"].([]interface{})
- if len(accessPoint) != 0 {
- ap := accessPointToFabric(accessPoint)
- connectionZSide = v4.ConnectionSide{AccessPoint: &ap}
- }
- if len(serviceTokenRequest) != 0 {
- mappedServiceToken, err := serviceTokenToFabric(serviceTokenRequest)
- if err != nil {
- return diag.FromErr(err)
- }
- connectionZSide = v4.ConnectionSide{ServiceToken: &mappedServiceToken}
- }
- if len(additionalInfoRequest) != 0 {
- mappedAdditionalInfo := additionalInfoTerraToGo(additionalInfoRequest)
- connectionZSide = v4.ConnectionSide{AdditionalInfo: mappedAdditionalInfo}
- }
+ if terraConfigProject, ok := d.GetOk("project"); ok {
+ project := equinix_fabric_schema.ProjectTerraformToGo(terraConfigProject.(*schema.Set).List())
+ createConnectionRequest.SetProject(project)
}
- createRequest := v4.ConnectionPostRequest{
- Name: d.Get("name").(string),
- Type_: &conType,
- Order: &order,
- Notifications: notifications,
- Bandwidth: int32(d.Get("bandwidth").(int)),
- AdditionalInfo: additionalInfo,
- Redundancy: &red,
- ASide: &connectionASide,
- ZSide: &connectionZSide,
- Project: project,
+ additionalInfoTerraConfig, ok := d.GetOk("additional_info")
+ if ok {
+ additionalInfo := additionalInfoTerraformToGo(additionalInfoTerraConfig.([]interface{}))
+ createConnectionRequest.SetAdditionalInfo(additionalInfo)
}
+ aSide := d.Get("a_side").(*schema.Set).List()
+ connectionASide := connectionSideTerraformToGo(aSide)
+ createConnectionRequest.SetASide(connectionASide)
+
+ zSide := d.Get("z_side").(*schema.Set).List()
+ connectionZSide := connectionSideTerraformToGo(zSide)
+ createConnectionRequest.SetZSide(connectionZSide)
+
start := time.Now()
- conn, _, err := client.ConnectionsApi.CreateConnection(ctx, createRequest)
+ conn, _, err := client.ConnectionsApi.CreateConnection(ctx).ConnectionPostRequest(createConnectionRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(conn.Uuid)
+ d.SetId(conn.GetUuid())
createTimeout := d.Timeout(schema.TimeoutCreate) - 30*time.Second - time.Since(start)
- if err = waitUntilConnectionIsCreated(d.Id(), meta, ctx, createTimeout); err != nil {
+ if err = waitUntilConnectionIsCreated(d.Id(), meta, d, ctx, createTimeout); err != nil {
return diag.Errorf("error waiting for connection (%s) to be created: %s", d.Id(), err)
}
- awsSecrets, hasAWSSecrets := additionalInfoContainsAWSSecrets(additionalInfoTerraConfig)
+ awsSecrets, hasAWSSecrets := additionalInfoContainsAWSSecrets(additionalInfoTerraConfig.([]interface{}))
if hasAWSSecrets {
- patchChangeOperation := []v4.ConnectionChangeOperation{
+ patchChangeOperation := []fabricv4.ConnectionChangeOperation{
{
Op: "add",
Path: "",
@@ -708,13 +680,13 @@ func resourceFabricConnectionCreate(ctx context.Context, d *schema.ResourceData,
},
}
- _, _, patchErr := client.ConnectionsApi.UpdateConnectionByUuid(ctx, patchChangeOperation, conn.Uuid)
+ _, _, patchErr := client.ConnectionsApi.UpdateConnectionByUuid(ctx, *conn.Uuid).ConnectionChangeOperation(patchChangeOperation).Execute()
if patchErr != nil {
return diag.FromErr(equinix_errors.FormatFabricError(patchErr))
}
createTimeout := d.Timeout(schema.TimeoutCreate) - 30*time.Second - time.Since(start)
- if _, statusChangeErr := waitForConnectionProviderStatusChange(d.Id(), meta, ctx, createTimeout); statusChangeErr != nil {
+ if _, statusChangeErr := waitForConnectionProviderStatusChange(d.Id(), meta, d, ctx, createTimeout); statusChangeErr != nil {
return diag.Errorf("error waiting for AWS Approval for connection %s: %v", d.Id(), statusChangeErr)
}
}
@@ -739,9 +711,8 @@ func additionalInfoContainsAWSSecrets(info []interface{}) ([]interface{}, bool)
}
func resourceFabricConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- conn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, d.Id(), nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ conn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, d.Id()).Execute()
if err != nil {
log.Printf("[WARN] Connection %s not found , error %s", d.Id(), err)
if !strings.Contains(err.Error(), "500") {
@@ -749,49 +720,59 @@ func resourceFabricConnectionRead(ctx context.Context, d *schema.ResourceData, m
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(conn.Uuid)
+ d.SetId(conn.GetUuid())
return setFabricMap(d, conn)
}
-func setFabricMap(d *schema.ResourceData, conn v4.Connection) diag.Diagnostics {
+func setFabricMap(d *schema.ResourceData, conn *fabricv4.Connection) diag.Diagnostics {
diags := diag.Diagnostics{}
connection := make(map[string]interface{})
- connection["name"] = conn.Name
- connection["bandwidth"] = conn.Bandwidth
- connection["href"] = conn.Href
- connection["is_remote"] = conn.IsRemote
- connection["type"] = conn.Type_
- connection["state"] = conn.State
- connection["direction"] = conn.Direction
+ connection["name"] = conn.GetName()
+ connection["bandwidth"] = conn.GetBandwidth()
+ connection["href"] = conn.GetHref()
+ connection["is_remote"] = conn.GetIsRemote()
+ connection["type"] = string(conn.GetType())
+ connection["state"] = string(conn.GetState())
+ connection["direction"] = conn.GetDirection()
if conn.Operation != nil {
- connection["operation"] = connectionOperationToTerra(conn.Operation)
+ operation := conn.GetOperation()
+ connection["operation"] = connectionOperationGoToTerraform(&operation)
}
if conn.Order != nil {
- connection["order"] = equinix_fabric_schema.OrderToTerra(conn.Order)
+ order := conn.GetOrder()
+ connection["order"] = equinix_fabric_schema.OrderGoToTerraform(&order)
}
if conn.ChangeLog != nil {
- connection["change_log"] = equinix_fabric_schema.ChangeLogToTerra(conn.ChangeLog)
+ changeLog := conn.GetChangeLog()
+ connection["change_log"] = equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog)
}
if conn.Redundancy != nil {
- connection["redundancy"] = connectionRedundancyToTerra(conn.Redundancy)
+ redundancy := conn.GetRedundancy()
+ connection["redundancy"] = connectionRedundancyGoToTerraform(&redundancy)
}
if conn.Notifications != nil {
- connection["notifications"] = equinix_fabric_schema.NotificationsToTerra(conn.Notifications)
+ notifications := conn.GetNotifications()
+ connection["notifications"] = equinix_fabric_schema.NotificationsGoToTerraform(notifications)
}
if conn.Account != nil {
- connection["account"] = equinix_fabric_schema.AccountToTerra(conn.Account)
+ account := conn.GetAccount()
+ connection["account"] = equinix_fabric_schema.AccountGoToTerraform(&account)
}
- if conn.ASide != nil {
- connection["a_side"] = connectionSideToTerra(conn.ASide)
+ if &conn.ASide != nil {
+ aSide := conn.GetASide()
+ connection["a_side"] = connectionSideGoToTerraform(&aSide)
}
- if conn.ZSide != nil {
- connection["z_side"] = connectionSideToTerra(conn.ZSide)
+ if &conn.ZSide != nil {
+ zSide := conn.GetZSide()
+ connection["z_side"] = connectionSideGoToTerraform(&zSide)
}
if conn.AdditionalInfo != nil {
- connection["additional_info"] = additionalInfoToTerra(conn.AdditionalInfo)
+ additionalInfo := conn.GetAdditionalInfo()
+ connection["additional_info"] = additionalInfoGoToTerraform(additionalInfo)
}
if conn.Project != nil {
- connection["project"] = equinix_fabric_schema.ProjectToTerra(conn.Project)
+ project := conn.GetProject()
+ connection["project"] = equinix_fabric_schema.ProjectGoToTerraform(&project)
}
err := equinix_schema.SetMap(d, connection)
if err != nil {
@@ -801,11 +782,10 @@ 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.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- dbConn, err := verifyConnectionCreated(d.Id(), meta, ctx, updateTimeout)
+ dbConn, err := verifyConnectionCreated(d.Id(), meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
@@ -822,13 +802,13 @@ func resourceFabricConnectionUpdate(ctx context.Context, d *schema.ResourceData,
updatedConn := dbConn
for _, update := range updateRequests {
- _, _, err := client.ConnectionsApi.UpdateConnectionByUuid(ctx, update, d.Id())
+ _, _, err := client.ConnectionsApi.UpdateConnectionByUuid(ctx, d.Id()).ConnectionChangeOperation(update).Execute()
if err != nil {
diags = append(diags, diag.Diagnostic{Severity: 0, Summary: fmt.Sprintf("connection property update request error: %v [update payload: %v] (other updates will be successful if the payload is not shown)", equinix_errors.FormatFabricError(err), update)})
continue
}
- var waitFunction func(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Connection, error)
+ var waitFunction func(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Connection, error)
if update[0].Op == "replace" {
// Update type is either name or bandwidth
waitFunction = waitForConnectionUpdateCompletion
@@ -838,7 +818,7 @@ func resourceFabricConnectionUpdate(ctx context.Context, d *schema.ResourceData,
}
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- conn, err := waitFunction(d.Id(), meta, ctx, updateTimeout)
+ conn, err := waitFunction(d.Id(), meta, d, ctx, updateTimeout)
if err != nil {
diags = append(diags, diag.Diagnostic{Severity: 0, Summary: fmt.Sprintf("connection property update completion timeout error: %v [update payload: %v] (other updates will be successful if the payload is not shown)", err, update)})
@@ -847,23 +827,25 @@ func resourceFabricConnectionUpdate(ctx context.Context, d *schema.ResourceData,
}
}
- d.SetId(updatedConn.Uuid)
+ d.SetId(updatedConn.GetUuid())
return append(diags, setFabricMap(d, updatedConn)...)
}
-func waitForConnectionUpdateCompletion(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Connection, error) {
+func waitForConnectionUpdateCompletion(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Connection, error) {
log.Printf("[DEBUG] Waiting for connection update to complete, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Target: []string{"COMPLETED"},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
updatableState := ""
- if dbConn.Change.Status == "COMPLETED" {
- updatableState = dbConn.Change.Status
+ change := dbConn.GetChange()
+ status := change.GetStatus()
+ if string(status) == "COMPLETED" {
+ updatableState = string(status)
}
return dbConn, updatableState, nil
},
@@ -873,32 +855,32 @@ func waitForConnectionUpdateCompletion(uuid string, meta interface{}, ctx contex
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.Connection{}
+ var dbConn *fabricv4.Connection
if err == nil {
- dbConn = inter.(v4.Connection)
+ dbConn = inter.(*fabricv4.Connection)
}
return dbConn, err
}
-func waitUntilConnectionIsCreated(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) error {
+func waitUntilConnectionIsCreated(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for connection to be created, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.PROVISIONING_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_PROVISIONING),
},
Target: []string{
- string(v4.PENDING_ConnectionState),
- string(v4.PROVISIONED_ConnectionState),
- string(v4.ACTIVE_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_PENDING),
+ string(fabricv4.CONNECTIONSTATE_PROVISIONED),
+ string(fabricv4.CONNECTIONSTATE_ACTIVE),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -910,23 +892,25 @@ func waitUntilConnectionIsCreated(uuid string, meta interface{}, ctx context.Con
return err
}
-func waitForConnectionProviderStatusChange(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Connection, error) {
+func waitForConnectionProviderStatusChange(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Connection, error) {
log.Printf("DEBUG: wating for provider status to update. Connection uuid: %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.PENDING_APPROVAL_ProviderStatus),
- string(v4.PROVISIONING_ProviderStatus),
+ string(fabricv4.PROVIDERSTATUS_PENDING_APPROVAL),
+ string(fabricv4.PROVIDERSTATUS_PROVISIONING),
},
Target: []string{
- string(v4.PROVISIONED_ProviderStatus),
+ string(fabricv4.PROVIDERSTATUS_PROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.Operation.ProviderStatus), nil
+ operation := dbConn.GetOperation()
+ providerStatus := operation.GetProviderStatus()
+ return dbConn, string(providerStatus), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -934,29 +918,29 @@ func waitForConnectionProviderStatusChange(uuid string, meta interface{}, ctx co
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.Connection{}
+ var dbConn *fabricv4.Connection
if err == nil {
- dbConn = inter.(v4.Connection)
+ dbConn = inter.(*fabricv4.Connection)
}
return dbConn, err
}
-func verifyConnectionCreated(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Connection, error) {
+func verifyConnectionCreated(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Connection, error) {
log.Printf("Waiting for connection to be in created state, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Target: []string{
- string(v4.ACTIVE_ConnectionState),
- string(v4.PROVISIONED_ConnectionState),
- string(v4.PENDING_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_ACTIVE),
+ string(fabricv4.CONNECTIONSTATE_PROVISIONED),
+ string(fabricv4.CONNECTIONSTATE_PENDING),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -964,55 +948,55 @@ func verifyConnectionCreated(uuid string, meta interface{}, ctx context.Context,
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.Connection{}
+ var dbConn *fabricv4.Connection
if err == nil {
- dbConn = inter.(v4.Connection)
+ dbConn = inter.(*fabricv4.Connection)
}
return dbConn, err
}
func resourceFabricConnectionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
diags := diag.Diagnostics{}
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
- _, _, err := client.ConnectionsApi.DeleteConnectionByUuid(ctx, d.Id())
+ _, _, err := client.ConnectionsApi.DeleteConnectionByUuid(ctx, d.Id()).Execute()
if err != nil {
- errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError)
- if ok {
- // EQ-3142509 = Connection already deleted
- if equinix_errors.HasModelErrorCode(errors, "EQ-3142509") {
- return diags
+ if genericError, ok := err.(*fabricv4.GenericOpenAPIError); ok {
+ if fabricErrs, ok := genericError.Model().([]fabricv4.Error); ok {
+ // EQ-3142509 = Connection already deleted
+ if equinix_errors.HasErrorCode(fabricErrs, "EQ-3142509") {
+ return diags
+ }
}
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
deleteTimeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start)
- err = WaitUntilConnectionDeprovisioned(d.Id(), meta, ctx, deleteTimeout)
+ err = WaitUntilConnectionDeprovisioned(d.Id(), meta, d, ctx, deleteTimeout)
if err != nil {
return diag.FromErr(fmt.Errorf("API call failed while waiting for resource deletion. Error %v", err))
}
return diags
}
-func WaitUntilConnectionDeprovisioned(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) error {
+func WaitUntilConnectionDeprovisioned(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for connection to be deprovisioned, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.DEPROVISIONING_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_DEPROVISIONING),
},
Target: []string{
- string(v4.DEPROVISIONED_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_DEPROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ConnectionsApi.GetConnectionByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
- return dbConn, string(*dbConn.State), nil
+ return dbConn, string(dbConn.GetState()), nil
},
Timeout: timeout,
Delay: 30 * time.Second,
@@ -1023,507 +1007,501 @@ func WaitUntilConnectionDeprovisioned(uuid string, meta interface{}, ctx context
return err
}
-func connectionRedundancyToFabric(schemaRedundancy []interface{}) v4.ConnectionRedundancy {
- if schemaRedundancy == nil {
- return v4.ConnectionRedundancy{}
- }
- red := v4.ConnectionRedundancy{}
- for _, r := range schemaRedundancy {
- redundancyMap := r.(map[string]interface{})
- connectionPriority := v4.ConnectionPriority(redundancyMap["priority"].(string))
- redundancyGroup := redundancyMap["group"].(string)
- red = v4.ConnectionRedundancy{
- Priority: &connectionPriority,
- Group: redundancyGroup,
- }
+func connectionRedundancyTerraformToGo(redundancyTerraform []interface{}) fabricv4.ConnectionRedundancy {
+ if redundancyTerraform == nil || len(redundancyTerraform) == 0 {
+ return fabricv4.ConnectionRedundancy{}
}
- return red
+ var redundancy fabricv4.ConnectionRedundancy
+
+ redundancyMap := redundancyTerraform[0].(map[string]interface{})
+ connectionPriority := redundancyMap["priority"].(string)
+ redundancyGroup := redundancyMap["group"].(string)
+ redundancy.SetPriority(fabricv4.ConnectionPriority(connectionPriority))
+ redundancy.SetGroup(redundancyGroup)
+
+ return redundancy
}
-func connectionRedundancyToTerra(redundancy *v4.ConnectionRedundancy) *schema.Set {
+func connectionRedundancyGoToTerraform(redundancy *fabricv4.ConnectionRedundancy) *schema.Set {
if redundancy == nil {
return nil
}
- redundancies := []*v4.ConnectionRedundancy{redundancy}
- mappedRedundancys := make([]interface{}, len(redundancies))
- for _, redundancy := range redundancies {
- mappedRedundancy := make(map[string]interface{})
- mappedRedundancy["group"] = redundancy.Group
- mappedRedundancy["priority"] = string(*redundancy.Priority)
- mappedRedundancys = append(mappedRedundancys, mappedRedundancy)
- }
+ mappedRedundancy := make(map[string]interface{})
+ mappedRedundancy["group"] = redundancy.GetGroup()
+ mappedRedundancy["priority"] = string(redundancy.GetPriority())
redundancySet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: connectionRedundancySch()}),
- mappedRedundancys,
+ []interface{}{mappedRedundancy},
)
return redundancySet
}
-func serviceTokenToFabric(serviceTokenRequest []interface{}) (v4.ServiceToken, error) {
- mappedST := v4.ServiceToken{}
- for _, str := range serviceTokenRequest {
- stMap := str.(map[string]interface{})
- stType := stMap["type"].(string)
- uuid := stMap["uuid"].(string)
- if stType != "" {
- if stType != "VC_TOKEN" {
- return v4.ServiceToken{}, fmt.Errorf("invalid service token type in config. Must be: VC_TOKEN; Received: %s", stType)
- }
- stTypeObj := v4.ServiceTokenType(stType)
- mappedST = v4.ServiceToken{Uuid: uuid, Type_: &stTypeObj}
- } else {
- mappedST = v4.ServiceToken{Uuid: uuid}
- }
+func serviceTokenTerraformToGo(serviceTokenList []interface{}) fabricv4.ServiceToken {
+ if serviceTokenList == nil || len(serviceTokenList) == 0 {
+ return fabricv4.ServiceToken{}
+ }
+
+ var serviceToken fabricv4.ServiceToken
+ serviceTokenMap := serviceTokenList[0].(map[string]interface{})
+ serviceTokenType := serviceTokenMap["type"].(string)
+ uuid := serviceTokenMap["uuid"].(string)
+ serviceToken.SetType(fabricv4.ServiceTokenType(serviceTokenType))
+ serviceToken.SetUuid(uuid)
+ return serviceToken
+}
+
+func additionalInfoTerraformToGo(additionalInfoList []interface{}) []fabricv4.ConnectionSideAdditionalInfo {
+ if additionalInfoList == nil || len(additionalInfoList) == 0 {
+ return nil
}
- return mappedST, nil
+
+ mappedAdditionalInfoList := make([]fabricv4.ConnectionSideAdditionalInfo, len(additionalInfoList))
+ for index, additionalInfo := range additionalInfoList {
+ additionalInfoMap := additionalInfo.(map[string]interface{})
+ key := additionalInfoMap["key"].(string)
+ value := additionalInfoMap["value"].(string)
+
+ additionalInfo := fabricv4.ConnectionSideAdditionalInfo{}
+ additionalInfo.SetKey(key)
+ additionalInfo.SetValue(value)
+ mappedAdditionalInfoList[index] = additionalInfo
+ }
+ return mappedAdditionalInfoList
}
-func additionalInfoTerraToGo(additionalInfoRequest []interface{}) []v4.ConnectionSideAdditionalInfo {
- var mappedaiArray []v4.ConnectionSideAdditionalInfo
- for _, ai := range additionalInfoRequest {
- aiMap := ai.(map[string]interface{})
- key := aiMap["key"].(string)
- value := aiMap["value"].(string)
- mappedai := v4.ConnectionSideAdditionalInfo{Key: key, Value: value}
- mappedaiArray = append(mappedaiArray, mappedai)
+func connectionSideTerraformToGo(connectionSideTerraform []interface{}) fabricv4.ConnectionSide {
+ if connectionSideTerraform == nil || len(connectionSideTerraform) == 0 {
+ return fabricv4.ConnectionSide{}
+ }
+
+ var connectionSide fabricv4.ConnectionSide
+
+ connectionSideMap := connectionSideTerraform[0].(map[string]interface{})
+ accessPoint := connectionSideMap["access_point"].(*schema.Set).List()
+ serviceTokenRequest := connectionSideMap["service_token"].(*schema.Set).List()
+ additionalInfoRequest := connectionSideMap["additional_info"].([]interface{})
+ if len(accessPoint) != 0 {
+ ap := accessPointTerraformToGo(accessPoint)
+ connectionSide.SetAccessPoint(ap)
}
- return mappedaiArray
+ if len(serviceTokenRequest) != 0 {
+ serviceToken := serviceTokenTerraformToGo(serviceTokenRequest)
+ connectionSide.SetServiceToken(serviceToken)
+ }
+ if len(additionalInfoRequest) != 0 {
+ accessPointAdditionalInfo := additionalInfoTerraformToGo(additionalInfoRequest)
+ connectionSide.SetAdditionalInfo(accessPointAdditionalInfo)
+ }
+
+ return connectionSide
}
-func accessPointToFabric(accessPointRequest []interface{}) v4.AccessPoint {
- accessPoint := v4.AccessPoint{}
- for _, ap := range accessPointRequest {
- accessPointMap := ap.(map[string]interface{})
- portList := accessPointMap["port"].(*schema.Set).List()
- profileList := accessPointMap["profile"].(*schema.Set).List()
- locationList := accessPointMap["location"].(*schema.Set).List()
- virtualdeviceList := accessPointMap["virtual_device"].(*schema.Set).List()
- interfaceList := accessPointMap["interface"].(*schema.Set).List()
- networkList := accessPointMap["network"].(*schema.Set).List()
- typeVal := accessPointMap["type"].(string)
- authenticationKey := accessPointMap["authentication_key"].(string)
- if authenticationKey != "" {
- accessPoint.AuthenticationKey = authenticationKey
- }
- providerConnectionId := accessPointMap["provider_connection_id"].(string)
- if providerConnectionId != "" {
- accessPoint.ProviderConnectionId = providerConnectionId
+func accessPointTerraformToGo(accessPointTerraform []interface{}) fabricv4.AccessPoint {
+ if accessPointTerraform == nil || len(accessPointTerraform) == 0 {
+ return fabricv4.AccessPoint{}
+ }
+
+ var accessPoint fabricv4.AccessPoint
+ accessPointMap := accessPointTerraform[0].(map[string]interface{})
+ portList := accessPointMap["port"].(*schema.Set).List()
+ profileList := accessPointMap["profile"].(*schema.Set).List()
+ locationList := accessPointMap["location"].(*schema.Set).List()
+ virtualDeviceList := accessPointMap["virtual_device"].(*schema.Set).List()
+ interfaceList := accessPointMap["interface"].(*schema.Set).List()
+ networkList := accessPointMap["network"].(*schema.Set).List()
+ typeVal := accessPointMap["type"].(string)
+ authenticationKey := accessPointMap["authentication_key"].(string)
+ if authenticationKey != "" {
+ accessPoint.SetAuthenticationKey(authenticationKey)
+ }
+ providerConnectionId := accessPointMap["provider_connection_id"].(string)
+ if providerConnectionId != "" {
+ accessPoint.SetProviderConnectionId(providerConnectionId)
+ }
+ sellerRegion := accessPointMap["seller_region"].(string)
+ if sellerRegion != "" {
+ accessPoint.SetSellerRegion(sellerRegion)
+ }
+ peeringTypeRaw := accessPointMap["peering_type"].(string)
+ if peeringTypeRaw != "" {
+ peeringType := fabricv4.PeeringType(peeringTypeRaw)
+ accessPoint.SetPeeringType(peeringType)
+ }
+ cloudRouterRequest := accessPointMap["router"].(*schema.Set).List()
+ if len(cloudRouterRequest) == 0 {
+ log.Print("[DEBUG] The router attribute was not used, attempting to revert to deprecated gateway attribute")
+ cloudRouterRequest = accessPointMap["gateway"].(*schema.Set).List()
+ }
+
+ if len(cloudRouterRequest) != 0 {
+ cloudRouter := cloudRouterTerraformToGo(cloudRouterRequest)
+ if cloudRouter.GetUuid() != "" {
+ accessPoint.SetRouter(cloudRouter)
}
- sellerRegion := accessPointMap["seller_region"].(string)
- if sellerRegion != "" {
- accessPoint.SellerRegion = sellerRegion
- }
- peeringTypeRaw := accessPointMap["peering_type"].(string)
- if peeringTypeRaw != "" {
- peeringType := v4.PeeringType(peeringTypeRaw)
- accessPoint.PeeringType = &peeringType
- }
- cloudRouterRequest := accessPointMap["router"].(*schema.Set).List()
- if len(cloudRouterRequest) == 0 {
- log.Print("[DEBUG] The router attribute was not used, attempting to revert to deprecated gateway attribute")
- cloudRouterRequest = accessPointMap["gateway"].(*schema.Set).List()
+ }
+ accessPoint.SetType(fabricv4.AccessPointType(typeVal))
+ if len(portList) != 0 {
+ port := portTerraformToGo(portList)
+ if port.GetUuid() != "" {
+ accessPoint.SetPort(port)
}
+ }
- if len(cloudRouterRequest) != 0 {
- mappedGWr := cloudRouterToFabric(cloudRouterRequest)
- if mappedGWr.Uuid != "" {
- accessPoint.Router = &mappedGWr
- }
- }
- apt := v4.AccessPointType(typeVal)
- accessPoint.Type_ = &apt
- if len(portList) != 0 {
- port := portToFabric(portList)
- if port.Uuid != "" {
- accessPoint.Port = &port
- }
+ if len(networkList) != 0 {
+ network := networkTerraformToGo(networkList)
+ if network.GetUuid() != "" {
+ accessPoint.SetNetwork(network)
}
+ }
+ linkProtocolList := accessPointMap["link_protocol"].(*schema.Set).List()
- if len(networkList) != 0 {
- network := networkToFabric(networkList)
- if network.Uuid != "" {
- accessPoint.Network = &network
- }
+ if len(linkProtocolList) != 0 {
+ linkProtocol := linkProtocolTerraformToGo(linkProtocolList)
+ if linkProtocol.GetType().Ptr() != nil {
+ accessPoint.SetLinkProtocol(linkProtocol)
}
- linkProtocolList := accessPointMap["link_protocol"].(*schema.Set).List()
+ }
- if len(linkProtocolList) != 0 {
- slp := linkProtocolToFabric(linkProtocolList)
- if slp.Type_ != nil {
- accessPoint.LinkProtocol = &slp
- }
+ if len(profileList) != 0 {
+ serviceProfile := simplifiedServiceProfileTerraformToGo(profileList)
+ if serviceProfile.GetUuid() != "" {
+ accessPoint.SetProfile(serviceProfile)
}
+ }
- if len(profileList) != 0 {
- ssp := simplifiedServiceProfileToFabric(profileList)
- if ssp.Uuid != "" {
- accessPoint.Profile = &ssp
- }
- }
+ if len(locationList) != 0 {
+ location := equinix_fabric_schema.LocationTerraformToGo(locationList)
+ accessPoint.SetLocation(location)
+ }
- if len(locationList) != 0 {
- sl := equinix_fabric_schema.LocationToFabric(locationList)
- accessPoint.Location = &sl
- }
+ if len(virtualDeviceList) != 0 {
+ virtualDevice := virtualDeviceTerraformToGo(virtualDeviceList)
+ accessPoint.SetVirtualDevice(virtualDevice)
+ }
- if len(virtualdeviceList) != 0 {
- vd := virtualdeviceToFabric(virtualdeviceList)
- accessPoint.VirtualDevice = &vd
- }
+ if len(interfaceList) != 0 {
+ interface_ := interfaceTerraformToGo(interfaceList)
+ accessPoint.SetInterface(interface_)
+ }
- if len(interfaceList) != 0 {
- il := interfaceToFabric(interfaceList)
- accessPoint.Interface_ = &il
- }
+ return accessPoint
+}
+func cloudRouterTerraformToGo(cloudRouterRequest []interface{}) fabricv4.CloudRouter {
+ if cloudRouterRequest == nil || len(cloudRouterRequest) == 0 {
+ return fabricv4.CloudRouter{}
}
- return accessPoint
+ var cloudRouter fabricv4.CloudRouter
+ cloudRouterMap := cloudRouterRequest[0].(map[string]interface{})
+ uuid := cloudRouterMap["uuid"].(string)
+ cloudRouter.SetUuid(uuid)
+
+ return cloudRouter
}
-func cloudRouterToFabric(cloudRouterRequest []interface{}) v4.CloudRouter {
- if cloudRouterRequest == nil {
- return v4.CloudRouter{}
+func linkProtocolTerraformToGo(linkProtocolList []interface{}) fabricv4.SimplifiedLinkProtocol {
+ if linkProtocolList == nil || len(linkProtocolList) == 0 {
+ return fabricv4.SimplifiedLinkProtocol{}
}
- cloudRouterMapped := v4.CloudRouter{}
- for _, crr := range cloudRouterRequest {
- crrMap := crr.(map[string]interface{})
- cruuid := crrMap["uuid"].(string)
- cloudRouterMapped = v4.CloudRouter{Uuid: cruuid}
+
+ var linkProtocol fabricv4.SimplifiedLinkProtocol
+ lpMap := linkProtocolList[0].(map[string]interface{})
+ lpType := lpMap["type"].(string)
+ lpVlanSTag := int32(lpMap["vlan_s_tag"].(int))
+ lpVlanTag := int32(lpMap["vlan_tag"].(int))
+ lpVlanCTag := int32(lpMap["vlan_c_tag"].(int))
+ log.Printf("[DEBUG] linkProtocolMap: %v", lpMap)
+
+ linkProtocol.SetType(fabricv4.LinkProtocolType(lpType))
+ if lpVlanSTag != 0 {
+ linkProtocol.SetVlanSTag(lpVlanSTag)
+ }
+ if lpVlanTag != 0 {
+ linkProtocol.SetVlanTag(lpVlanTag)
+ }
+ if lpVlanCTag != 0 {
+ linkProtocol.SetVlanCTag(lpVlanCTag)
}
- return cloudRouterMapped
-}
-func linkProtocolToFabric(linkProtocolList []interface{}) v4.SimplifiedLinkProtocol {
- slp := v4.SimplifiedLinkProtocol{}
- for _, lp := range linkProtocolList {
- lpMap := lp.(map[string]interface{})
- lpType := lpMap["type"].(string)
- lpVlanSTag := lpMap["vlan_s_tag"].(int)
- lpVlanTag := lpMap["vlan_tag"].(int)
- lpVlanCTag := lpMap["vlan_c_tag"].(int)
- lpt := v4.LinkProtocolType(lpType)
- slp = v4.SimplifiedLinkProtocol{Type_: &lpt, VlanSTag: int32(lpVlanSTag), VlanTag: int32(lpVlanTag), VlanCTag: int32(lpVlanCTag)}
- }
- return slp
+ return linkProtocol
}
-func networkToFabric(networkList []interface{}) v4.SimplifiedNetwork {
- p := v4.SimplifiedNetwork{}
- for _, pl := range networkList {
- plMap := pl.(map[string]interface{})
- uuid := plMap["uuid"].(string)
- p = v4.SimplifiedNetwork{Uuid: uuid}
+func networkTerraformToGo(networkList []interface{}) fabricv4.SimplifiedNetwork {
+ if networkList == nil || len(networkList) == 0 {
+ return fabricv4.SimplifiedNetwork{}
}
- return p
+ var network fabricv4.SimplifiedNetwork
+ networkListMap := networkList[0].(map[string]interface{})
+ uuid := networkListMap["uuid"].(string)
+ network.SetUuid(uuid)
+ return network
}
-func simplifiedServiceProfileToFabric(profileList []interface{}) v4.SimplifiedServiceProfile {
- ssp := v4.SimplifiedServiceProfile{}
- for _, pl := range profileList {
- plMap := pl.(map[string]interface{})
- ptype := plMap["type"].(string)
- spte := v4.ServiceProfileTypeEnum(ptype)
- uuid := plMap["uuid"].(string)
- ssp = v4.SimplifiedServiceProfile{Uuid: uuid, Type_: &spte}
-
+func simplifiedServiceProfileTerraformToGo(profileList []interface{}) fabricv4.SimplifiedServiceProfile {
+ if profileList == nil || len(profileList) == 0 {
+ return fabricv4.SimplifiedServiceProfile{}
}
- return ssp
+
+ var serviceProfile fabricv4.SimplifiedServiceProfile
+ profileListMap := profileList[0].(map[string]interface{})
+ profileType := profileListMap["type"].(string)
+ uuid := profileListMap["uuid"].(string)
+ serviceProfile.SetType(fabricv4.ServiceProfileTypeEnum(profileType))
+ serviceProfile.SetUuid(uuid)
+ return serviceProfile
}
-func virtualdeviceToFabric(virtualdeviceList []interface{}) v4.VirtualDevice {
- vd := v4.VirtualDevice{}
- for _, ll := range virtualdeviceList {
- llMap := ll.(map[string]interface{})
- hr := llMap["href"].(string)
- tp := llMap["type"].(string)
- ud := llMap["uuid"].(string)
- na := llMap["name"].(string)
- vd = v4.VirtualDevice{Href: hr, Type_: tp, Uuid: ud, Name: na}
- }
- return vd
+func virtualDeviceTerraformToGo(virtualDeviceList []interface{}) fabricv4.VirtualDevice {
+ if virtualDeviceList == nil || len(virtualDeviceList) == 0 {
+ return fabricv4.VirtualDevice{}
+ }
+
+ var virtualDevice fabricv4.VirtualDevice
+ virtualDeviceMap := virtualDeviceList[0].(map[string]interface{})
+ href := virtualDeviceMap["href"].(string)
+ type_ := virtualDeviceMap["type"].(string)
+ uuid := virtualDeviceMap["uuid"].(string)
+ name := virtualDeviceMap["name"].(string)
+ virtualDevice.SetHref(href)
+ virtualDevice.SetType(fabricv4.VirtualDeviceType(type_))
+ virtualDevice.SetUuid(uuid)
+ virtualDevice.SetName(name)
+
+ return virtualDevice
}
-func interfaceToFabric(interfaceList []interface{}) v4.ModelInterface {
- il := v4.ModelInterface{}
- for _, ll := range interfaceList {
- llMap := ll.(map[string]interface{})
- ud := llMap["uuid"].(string)
- tp := llMap["type"].(string)
- id := llMap["id"].(int)
- il = v4.ModelInterface{Type_: tp, Uuid: ud, Id: int32(id)}
+func interfaceTerraformToGo(interfaceList []interface{}) fabricv4.Interface {
+ if interfaceList == nil || len(interfaceList) == 0 {
+ return fabricv4.Interface{}
}
- return il
+
+ var interface_ fabricv4.Interface
+ interfaceMap := interfaceList[0].(map[string]interface{})
+ uuid := interfaceMap["uuid"].(string)
+ type_ := interfaceMap["type"].(string)
+ id := interfaceMap["id"].(int)
+ interface_.SetUuid(uuid)
+ interface_.SetType(fabricv4.InterfaceType(type_))
+ interface_.SetId(int32(id))
+
+ return interface_
}
-func connectionOperationToTerra(operation *v4.ConnectionOperation) *schema.Set {
+func connectionOperationGoToTerraform(operation *fabricv4.ConnectionOperation) *schema.Set {
if operation == nil {
return nil
}
- operations := []*v4.ConnectionOperation{operation}
- mappedOperations := make([]interface{}, len(operations))
- for _, operation := range operations {
- mappedOperation := make(map[string]interface{})
- mappedOperation["provider_status"] = string(*operation.ProviderStatus)
- mappedOperation["equinix_status"] = string(*operation.EquinixStatus)
- if operation.Errors != nil {
- mappedOperation["errors"] = equinix_fabric_schema.ErrorToTerra(operation.Errors)
- }
- mappedOperations = append(mappedOperations, mappedOperation)
+
+ mappedOperation := make(map[string]interface{})
+ mappedOperation["provider_status"] = string(operation.GetProviderStatus())
+ mappedOperation["equinix_status"] = string(operation.GetEquinixStatus())
+ if operation.Errors != nil {
+ mappedOperation["errors"] = equinix_fabric_schema.ErrorGoToTerraform(operation.GetErrors())
}
operationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: operationSch()}),
- mappedOperations,
+ []interface{}{mappedOperation},
)
return operationSet
}
-func serviceTokenToTerra(serviceToken *v4.ServiceToken) *schema.Set {
+func serviceTokenGoToTerraform(serviceToken *fabricv4.ServiceToken) *schema.Set {
if serviceToken == nil {
return nil
}
- serviceTokens := []*v4.ServiceToken{serviceToken}
- mappedServiceTokens := make([]interface{}, len(serviceTokens))
- for _, serviceToken := range serviceTokens {
- mappedServiceToken := make(map[string]interface{})
- if serviceToken.Type_ != nil {
- mappedServiceToken["type"] = string(*serviceToken.Type_)
- }
- mappedServiceToken["href"] = serviceToken.Href
- mappedServiceToken["uuid"] = serviceToken.Uuid
- mappedServiceTokens = append(mappedServiceTokens, mappedServiceToken)
+ mappedServiceToken := make(map[string]interface{})
+ if serviceToken.Type != nil {
+ mappedServiceToken["type"] = string(serviceToken.GetType())
}
+ mappedServiceToken["href"] = serviceToken.GetHref()
+ mappedServiceToken["uuid"] = serviceToken.GetUuid()
+
serviceTokenSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: serviceTokenSch()}),
- mappedServiceTokens,
+ []interface{}{mappedServiceToken},
)
return serviceTokenSet
}
-func connectionSideToTerra(connectionSide *v4.ConnectionSide) *schema.Set {
- connectionSides := []*v4.ConnectionSide{connectionSide}
- mappedConnectionSides := make([]interface{}, len(connectionSides))
- for _, connectionSide := range connectionSides {
- mappedConnectionSide := make(map[string]interface{})
- serviceTokenSet := serviceTokenToTerra(connectionSide.ServiceToken)
- if serviceTokenSet != nil {
- mappedConnectionSide["service_token"] = serviceTokenSet
- }
- mappedConnectionSide["access_point"] = accessPointToTerra(connectionSide.AccessPoint)
- mappedConnectionSides = append(mappedConnectionSides, mappedConnectionSide)
+func connectionSideGoToTerraform(connectionSide *fabricv4.ConnectionSide) *schema.Set {
+ mappedConnectionSide := make(map[string]interface{})
+ serviceToken := connectionSide.GetServiceToken()
+ serviceTokenSet := serviceTokenGoToTerraform(&serviceToken)
+ if serviceTokenSet != nil {
+ mappedConnectionSide["service_token"] = serviceTokenSet
}
+ accessPoint := connectionSide.GetAccessPoint()
+ mappedConnectionSide["access_point"] = accessPointGoToTerraform(&accessPoint)
connectionSideSet := schema.NewSet(
schema.HashResource(connectionSideSch()),
- mappedConnectionSides,
+ []interface{}{mappedConnectionSide},
)
return connectionSideSet
}
-func additionalInfoToTerra(additionalInfol []v4.ConnectionSideAdditionalInfo) []map[string]interface{} {
- if additionalInfol == nil {
+func additionalInfoGoToTerraform(additionalInfo []fabricv4.ConnectionSideAdditionalInfo) []map[string]interface{} {
+ if additionalInfo == nil {
return nil
}
- mappedadditionalInfol := make([]map[string]interface{}, len(additionalInfol))
- for index, additionalInfo := range additionalInfol {
- mappedadditionalInfol[index] = map[string]interface{}{
- "key": additionalInfo.Key,
- "value": additionalInfo.Value,
+ mappedAdditionalInfo := make([]map[string]interface{}, len(additionalInfo))
+ for index, additionalInfo := range additionalInfo {
+ mappedAdditionalInfo[index] = map[string]interface{}{
+ "key": additionalInfo.GetKey(),
+ "value": additionalInfo.GetValue(),
}
}
- return mappedadditionalInfol
+ return mappedAdditionalInfo
}
-func cloudRouterToTerra(cloudRouter *v4.CloudRouter) *schema.Set {
+func cloudRouterGoToTerraform(cloudRouter *fabricv4.CloudRouter) *schema.Set {
if cloudRouter == nil {
return nil
}
- cloudRouters := []*v4.CloudRouter{cloudRouter}
- mappedCloudRouters := make([]interface{}, len(cloudRouters))
- for _, cloudRouter := range cloudRouters {
- mappedCloudRouter := make(map[string]interface{})
- mappedCloudRouter["uuid"] = cloudRouter.Uuid
- mappedCloudRouter["href"] = cloudRouter.Href
- mappedCloudRouters = append(mappedCloudRouters, mappedCloudRouter)
- }
+ mappedCloudRouter := make(map[string]interface{})
+ mappedCloudRouter["uuid"] = cloudRouter.GetUuid()
+ mappedCloudRouter["href"] = cloudRouter.GetHref()
+
linkedProtocolSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: equinix_fabric_schema.ProjectSch()}),
- mappedCloudRouters)
+ []interface{}{mappedCloudRouter})
return linkedProtocolSet
}
-func virtualDeviceToTerra(virtualDevice *v4.VirtualDevice) *schema.Set {
+func virtualDeviceGoToTerraform(virtualDevice *fabricv4.VirtualDevice) *schema.Set {
if virtualDevice == nil {
return nil
}
- virtualDevices := []*v4.VirtualDevice{virtualDevice}
- mappedVirtualDevices := make([]interface{}, len(virtualDevices))
- for _, virtualDevice := range virtualDevices {
- mappedVirtualDevice := make(map[string]interface{})
- mappedVirtualDevice["name"] = virtualDevice.Name
- mappedVirtualDevice["href"] = virtualDevice.Href
- mappedVirtualDevice["type"] = virtualDevice.Type_
- mappedVirtualDevice["uuid"] = virtualDevice.Uuid
- mappedVirtualDevices = append(mappedVirtualDevices, mappedVirtualDevice)
- }
+ mappedVirtualDevice := make(map[string]interface{})
+ mappedVirtualDevice["name"] = virtualDevice.GetName()
+ mappedVirtualDevice["href"] = virtualDevice.GetHref()
+ mappedVirtualDevice["type"] = string(virtualDevice.GetType())
+ mappedVirtualDevice["uuid"] = virtualDevice.GetUuid()
+
virtualDeviceSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: accessPointVirtualDeviceSch()}),
- mappedVirtualDevices)
+ []interface{}{mappedVirtualDevice})
return virtualDeviceSet
}
-func interfaceToTerra(mInterface *v4.ModelInterface) *schema.Set {
+func interfaceGoToTerraform(mInterface *fabricv4.Interface) *schema.Set {
if mInterface == nil {
return nil
}
- mInterfaces := []*v4.ModelInterface{mInterface}
- mappedMInterfaces := make([]interface{}, len(mInterfaces))
- for _, mInterface := range mInterfaces {
- mappedMInterface := make(map[string]interface{})
- mappedMInterface["id"] = int(mInterface.Id)
- mappedMInterface["type"] = mInterface.Type_
- mappedMInterface["uuid"] = mInterface.Uuid
- mappedMInterfaces = append(mappedMInterfaces, mappedMInterface)
- }
+ mappedMInterface := make(map[string]interface{})
+ mappedMInterface["id"] = int(mInterface.GetId())
+ mappedMInterface["type"] = string(mInterface.GetType())
+ mappedMInterface["uuid"] = mInterface.GetUuid()
+
mInterfaceSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: accessPointInterface()}),
- mappedMInterfaces)
+ []interface{}{mappedMInterface})
return mInterfaceSet
}
-func accessPointToTerra(accessPoint *v4.AccessPoint) *schema.Set {
- accessPoints := []*v4.AccessPoint{accessPoint}
- mappedAccessPoints := make([]interface{}, len(accessPoints))
- for _, accessPoint := range accessPoints {
- mappedAccessPoint := make(map[string]interface{})
- if accessPoint.Type_ != nil {
- mappedAccessPoint["type"] = string(*accessPoint.Type_)
- }
- if accessPoint.Account != nil {
- mappedAccessPoint["account"] = equinix_fabric_schema.AccountToTerra(accessPoint.Account)
- }
- if accessPoint.Location != nil {
- mappedAccessPoint["location"] = equinix_fabric_schema.LocationToTerra(accessPoint.Location)
- }
- if accessPoint.Port != nil {
- mappedAccessPoint["port"] = portToTerra(accessPoint.Port)
- }
- if accessPoint.Profile != nil {
- mappedAccessPoint["profile"] = simplifiedServiceProfileToTerra(accessPoint.Profile)
- }
- if accessPoint.Router != nil {
- mappedAccessPoint["router"] = cloudRouterToTerra(accessPoint.Router)
- mappedAccessPoint["gateway"] = cloudRouterToTerra(accessPoint.Router)
- }
- if accessPoint.LinkProtocol != nil {
- mappedAccessPoint["link_protocol"] = linkedProtocolToTerra(*accessPoint.LinkProtocol)
- }
- if accessPoint.VirtualDevice != nil {
- mappedAccessPoint["virtual_device"] = virtualDeviceToTerra(accessPoint.VirtualDevice)
- }
- if accessPoint.Interface_ != nil {
- mappedAccessPoint["interface"] = interfaceToTerra(accessPoint.Interface_)
- }
- mappedAccessPoint["seller_region"] = accessPoint.SellerRegion
- if accessPoint.PeeringType != nil {
- mappedAccessPoint["peering_type"] = string(*accessPoint.PeeringType)
- }
- mappedAccessPoint["authentication_key"] = accessPoint.AuthenticationKey
- mappedAccessPoint["provider_connection_id"] = accessPoint.ProviderConnectionId
- mappedAccessPoints = append(mappedAccessPoints, mappedAccessPoint)
+func networkGoToTerraform(network *fabricv4.SimplifiedNetwork) *schema.Set {
+ if network == nil {
+ return nil
+ }
+
+ mappedNetwork := make(map[string]interface{})
+ mappedNetwork["uuid"] = network.GetUuid()
+
+ return schema.NewSet(
+ schema.HashResource(&schema.Resource{Schema: networkSch()}),
+ []interface{}{mappedNetwork})
+}
+
+func accessPointGoToTerraform(accessPoint *fabricv4.AccessPoint) *schema.Set {
+ mappedAccessPoint := make(map[string]interface{})
+ if accessPoint.Type != nil {
+ mappedAccessPoint["type"] = string(accessPoint.GetType())
+ }
+ if accessPoint.Account != nil {
+ account := accessPoint.GetAccount()
+ mappedAccessPoint["account"] = equinix_fabric_schema.AccountGoToTerraform(&account)
+ }
+ if accessPoint.Location != nil {
+ location := accessPoint.GetLocation()
+ mappedAccessPoint["location"] = equinix_fabric_schema.LocationGoToTerraform(&location)
+ }
+ if accessPoint.Port != nil {
+ port := accessPoint.GetPort()
+ mappedAccessPoint["port"] = portGoToTerraform(&port)
+ }
+ if accessPoint.Profile != nil {
+ profile := accessPoint.GetProfile()
+ mappedAccessPoint["profile"] = simplifiedServiceProfileGoToTerraform(&profile)
+ }
+ if accessPoint.Router != nil {
+ router := accessPoint.GetRouter()
+ mappedAccessPoint["router"] = cloudRouterGoToTerraform(&router)
+ mappedAccessPoint["gateway"] = cloudRouterGoToTerraform(&router)
+ }
+ if accessPoint.LinkProtocol != nil {
+ linkProtocol := accessPoint.GetLinkProtocol()
+ mappedAccessPoint["link_protocol"] = linkedProtocolGoToTerraform(&linkProtocol)
+ }
+ if accessPoint.VirtualDevice != nil {
+ virtualDevice := accessPoint.GetVirtualDevice()
+ mappedAccessPoint["virtual_device"] = virtualDeviceGoToTerraform(&virtualDevice)
+ }
+ if accessPoint.Interface != nil {
+ interface_ := accessPoint.GetInterface()
+ mappedAccessPoint["interface"] = interfaceGoToTerraform(&interface_)
+ }
+ if accessPoint.Network != nil {
+ network := accessPoint.GetNetwork()
+ mappedAccessPoint["network"] = networkGoToTerraform(&network)
}
+ mappedAccessPoint["seller_region"] = accessPoint.GetSellerRegion()
+ if accessPoint.PeeringType != nil {
+ mappedAccessPoint["peering_type"] = string(accessPoint.GetPeeringType())
+ }
+ mappedAccessPoint["authentication_key"] = accessPoint.GetAuthenticationKey()
+ mappedAccessPoint["provider_connection_id"] = accessPoint.GetProviderConnectionId()
+
accessPointSet := schema.NewSet(
schema.HashResource(accessPointSch()),
- mappedAccessPoints,
+ []interface{}{mappedAccessPoint},
)
return accessPointSet
}
-func linkedProtocolToTerra(linkedProtocol v4.SimplifiedLinkProtocol) *schema.Set {
- linkedProtocols := []v4.SimplifiedLinkProtocol{linkedProtocol}
- mappedLinkedProtocols := make([]interface{}, len(linkedProtocols))
- for _, linkedProtocol := range linkedProtocols {
- mappedLinkedProtocol := make(map[string]interface{})
- mappedLinkedProtocol["type"] = string(*linkedProtocol.Type_)
- mappedLinkedProtocol["vlan_tag"] = int(linkedProtocol.VlanTag)
- mappedLinkedProtocol["vlan_s_tag"] = int(linkedProtocol.VlanSTag)
- mappedLinkedProtocol["vlan_c_tag"] = int(linkedProtocol.VlanCTag)
- mappedLinkedProtocols = append(mappedLinkedProtocols, mappedLinkedProtocol)
- }
+func linkedProtocolGoToTerraform(linkedProtocol *fabricv4.SimplifiedLinkProtocol) *schema.Set {
+
+ mappedLinkedProtocol := make(map[string]interface{})
+ mappedLinkedProtocol["type"] = string(linkedProtocol.GetType())
+ mappedLinkedProtocol["vlan_tag"] = int(linkedProtocol.GetVlanTag())
+ mappedLinkedProtocol["vlan_s_tag"] = int(linkedProtocol.GetVlanSTag())
+ mappedLinkedProtocol["vlan_c_tag"] = int(linkedProtocol.GetVlanCTag())
+
linkedProtocolSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: accessPointLinkProtocolSch()}),
- mappedLinkedProtocols)
+ []interface{}{mappedLinkedProtocol})
return linkedProtocolSet
}
-func simplifiedServiceProfileToTerra(profile *v4.SimplifiedServiceProfile) *schema.Set {
- profiles := []*v4.SimplifiedServiceProfile{profile}
- mappedProfiles := make([]interface{}, len(profiles))
- for _, profile := range profiles {
- mappedProfile := make(map[string]interface{})
- mappedProfile["href"] = profile.Href
- mappedProfile["type"] = string(*profile.Type_)
- mappedProfile["name"] = profile.Name
- mappedProfile["uuid"] = profile.Uuid
- mappedProfile["access_point_type_configs"] = accessPointTypeConfigToTerra(profile.AccessPointTypeConfigs)
- mappedProfiles = append(mappedProfiles, mappedProfile)
- }
+func simplifiedServiceProfileGoToTerraform(profile *fabricv4.SimplifiedServiceProfile) *schema.Set {
+
+ mappedProfile := make(map[string]interface{})
+ mappedProfile["href"] = profile.GetHref()
+ mappedProfile["type"] = string(profile.GetType())
+ mappedProfile["name"] = profile.GetName()
+ mappedProfile["uuid"] = profile.GetName()
+ mappedProfile["access_point_type_configs"] = accessPointTypeConfigGoToTerraform(profile.AccessPointTypeConfigs)
profileSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: serviceProfileSch()}),
- mappedProfiles,
+ []interface{}{mappedProfile},
)
return profileSet
}
-func apiConfigToTerra(apiConfig *v4.ApiConfig) *schema.Set {
- apiConfigs := []*v4.ApiConfig{apiConfig}
- mappedApiConfigs := make([]interface{}, len(apiConfigs))
- for _, apiConfig := range apiConfigs {
- mappedApiConfig := make(map[string]interface{})
- mappedApiConfig["api_available"] = apiConfig.ApiAvailable
- mappedApiConfig["equinix_managed_vlan"] = apiConfig.EquinixManagedVlan
- mappedApiConfig["bandwidth_from_api"] = apiConfig.BandwidthFromApi
- mappedApiConfig["integration_id"] = apiConfig.IntegrationId
- mappedApiConfig["equinix_managed_port"] = apiConfig.EquinixManagedPort
- mappedApiConfigs = append(mappedApiConfigs, mappedApiConfig)
- }
- apiConfigSet := schema.NewSet(
- schema.HashResource(&schema.Resource{Schema: createApiConfigSch()}),
- mappedApiConfigs)
- return apiConfigSet
-}
-
-func authenticationKeyToTerra(authenticationKey *v4.AuthenticationKey) *schema.Set {
- authenticationKeys := []*v4.AuthenticationKey{authenticationKey}
- mappedAuthenticationKeys := make([]interface{}, len(authenticationKeys))
- for _, authenticationKey := range authenticationKeys {
- mappedAuthenticationKey := make(map[string]interface{})
- mappedAuthenticationKey["required"] = authenticationKey.Required
- mappedAuthenticationKey["label"] = authenticationKey.Label
- mappedAuthenticationKey["description"] = authenticationKey.Description
- mappedAuthenticationKeys = append(mappedAuthenticationKeys, mappedAuthenticationKey)
- }
- apiConfigSet := schema.NewSet(
- schema.HashResource(&schema.Resource{Schema: createAuthenticationKeySch()}),
- mappedAuthenticationKeys)
- return apiConfigSet
-}
-
-func supportedBandwidthsToTerra(supportedBandwidths *[]int32) []interface{} {
- if supportedBandwidths == nil {
- return nil
- }
- mappedSupportedBandwidths := make([]interface{}, len(*supportedBandwidths))
- for _, bandwidth := range *supportedBandwidths {
- mappedSupportedBandwidths = append(mappedSupportedBandwidths, int(bandwidth))
- }
- return mappedSupportedBandwidths
-}
-
-func getUpdateRequests(conn v4.Connection, d *schema.ResourceData) ([][]v4.ConnectionChangeOperation, error) {
- var changeOps [][]v4.ConnectionChangeOperation
- existingName := conn.Name
- existingBandwidth := int(conn.Bandwidth)
+func getUpdateRequests(conn *fabricv4.Connection, d *schema.ResourceData) ([][]fabricv4.ConnectionChangeOperation, error) {
+ var changeOps [][]fabricv4.ConnectionChangeOperation
+ existingName := conn.GetName()
+ existingBandwidth := int(conn.GetBandwidth())
updateNameVal := d.Get("name").(string)
updateBandwidthVal := d.Get("bandwidth").(int)
additionalInfo := d.Get("additional_info").([]interface{})
@@ -1531,7 +1509,7 @@ func getUpdateRequests(conn v4.Connection, d *schema.ResourceData) ([][]v4.Conne
awsSecrets, hasAWSSecrets := additionalInfoContainsAWSSecrets(additionalInfo)
if existingName != updateNameVal {
- changeOps = append(changeOps, []v4.ConnectionChangeOperation{
+ changeOps = append(changeOps, []fabricv4.ConnectionChangeOperation{
{
Op: "replace",
Path: "/name",
@@ -1541,7 +1519,7 @@ func getUpdateRequests(conn v4.Connection, d *schema.ResourceData) ([][]v4.Conne
}
if existingBandwidth != updateBandwidthVal {
- changeOps = append(changeOps, []v4.ConnectionChangeOperation{
+ changeOps = append(changeOps, []fabricv4.ConnectionChangeOperation{
{
Op: "replace",
Path: "/bandwidth",
@@ -1550,8 +1528,8 @@ func getUpdateRequests(conn v4.Connection, d *schema.ResourceData) ([][]v4.Conne
})
}
- if *conn.Operation.ProviderStatus == v4.PENDING_APPROVAL_ProviderStatus && hasAWSSecrets {
- changeOps = append(changeOps, []v4.ConnectionChangeOperation{
+ if *conn.Operation.ProviderStatus == fabricv4.PROVIDERSTATUS_PENDING_APPROVAL && hasAWSSecrets {
+ changeOps = append(changeOps, []fabricv4.ConnectionChangeOperation{
{
Op: "add",
Path: "",
diff --git a/equinix/resource_fabric_connection_acc_test.go b/equinix/resource_fabric_connection_acc_test.go
index fd052fb08..6a03a42a1 100644
--- a/equinix/resource_fabric_connection_acc_test.go
+++ b/equinix/resource_fabric_connection_acc_test.go
@@ -6,13 +6,11 @@ import (
"fmt"
"github.com/equinix/terraform-provider-equinix/equinix"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"os"
"testing"
"time"
- "github.com/equinix/terraform-provider-equinix/internal/config"
-
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)
@@ -47,10 +45,10 @@ func TestAccFabricCreatePort2SPConnection_PFCR(t *testing.T) {
var publicSPName, portUuid string
if len(ports) > 0 && len(connectionsTestData) > 0 {
publicSPName = connectionsTestData["pfcr"]["publicSPName"]
- portUuid = ports["pfcr"]["dot1q"][0].Uuid
+ portUuid = ports["pfcr"]["dot1q"][0].GetUuid()
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: CheckConnectionDelete,
Steps: []resource.TestStep{
@@ -145,11 +143,11 @@ func TestAccFabricCreatePort2PortConnection_PFCR(t *testing.T) {
ports := GetFabricEnvPorts(t)
var aSidePortUuid, zSidePortUuid string
if len(ports) > 0 {
- aSidePortUuid = ports["pfcr"]["dot1q"][0].Uuid
- zSidePortUuid = ports["pfcr"]["dot1q"][1].Uuid
+ aSidePortUuid = ports["pfcr"]["dot1q"][0].GetUuid()
+ zSidePortUuid = ports["pfcr"]["dot1q"][1].GetUuid()
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: CheckConnectionDelete,
Steps: []resource.TestStep{
@@ -260,10 +258,10 @@ func TestAccFabricCreateCloudRouter2PortConnection_PFCR(t *testing.T) {
ports := GetFabricEnvPorts(t)
var portUuid string
if len(ports) > 0 {
- portUuid = ports["pfcr"]["dot1q"][1].Uuid
+ portUuid = ports["pfcr"]["dot1q"][1].GetUuid()
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: CheckConnectionDelete,
Steps: []resource.TestStep{
@@ -378,7 +376,7 @@ func TestAccFabricCreateVirtualDevice2NetworkConnection_PNFV(t *testing.T) {
virtualDevice = connectionTestData["pnfv"]["virtualDevice"]
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: CheckConnectionDelete,
Steps: []resource.TestStep{
@@ -412,7 +410,6 @@ func TestAccFabricCreateVirtualDevice2NetworkConnection_PNFV(t *testing.T) {
resource.TestCheckResourceAttrSet(
"equinix_fabric_connection.test", "z_side.0.access_point.0.network.0.uuid"),
),
- ExpectNonEmptyPlan: true,
},
},
})
@@ -478,12 +475,12 @@ func testAccFabricCreateVirtualDevice2NetworkConnectionConfig(name, virtualDevic
func CheckConnectionDelete(s *terraform.State) error {
ctx := context.Background()
- ctx = context.WithValue(ctx, v4.ContextAccessToken, acceptance.TestAccProvider.Meta().(*config.Config).FabricAuthToken)
for _, rs := range s.RootModule().Resources {
if rs.Type != "equinix_fabric_connection" {
continue
}
- err := equinix.WaitUntilConnectionDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), ctx, 10*time.Minute)
+
+ err := equinix.WaitUntilConnectionDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), &schema.ResourceData{}, ctx, 10*time.Minute)
if err != nil {
return fmt.Errorf("API call failed while waiting for resource deletion")
}
diff --git a/equinix/resource_fabric_network.go b/equinix/resource_fabric_network.go
index bd46ab48e..60c0a1fc2 100755
--- a/equinix/resource_fabric_network.go
+++ b/equinix/resource_fabric_network.go
@@ -3,7 +3,7 @@ package equinix
import (
"context"
"fmt"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/equinix/terraform-provider-equinix/internal/config"
equinix_errors "github.com/equinix/terraform-provider-equinix/internal/errors"
equinix_fabric_schema "github.com/equinix/terraform-provider-equinix/internal/fabric/schema"
@@ -167,35 +167,38 @@ func resourceFabricNetwork() *schema.Resource {
}
func resourceFabricNetworkCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ createRequest := fabricv4.NetworkPostRequest{}
+ createRequest.SetName(d.Get("name").(string))
+
schemaNotifications := d.Get("notifications").([]interface{})
- notifications := equinix_fabric_schema.NotificationsToFabric(schemaNotifications)
- schemaLocation := d.Get("location").(*schema.Set).List()
- location := equinix_fabric_schema.LocationToFabric(schemaLocation)
- schemaProject := d.Get("project").(*schema.Set).List()
- project := equinix_fabric_schema.ProjectToFabric(schemaProject)
- netType := v4.NetworkType(d.Get("type").(string))
- netScope := v4.NetworkScope(d.Get("scope").(string))
-
- createRequest := v4.NetworkPostRequest{
- Name: d.Get("name").(string),
- Type_: &netType,
- Scope: &netScope,
- Location: &location,
- Notifications: notifications,
- Project: project,
+ notifications := equinix_fabric_schema.NotificationsTerraformToGo(schemaNotifications)
+ createRequest.SetNotifications(notifications)
+
+ if schemaLocation, ok := d.GetOk("location"); ok {
+ location := equinix_fabric_schema.LocationTerraformToGo(schemaLocation.(*schema.Set).List())
+ createRequest.SetLocation(location)
}
+ schemaProject := d.Get("project").(*schema.Set).List()
+ project := equinix_fabric_schema.ProjectTerraformToGo(schemaProject)
+ createRequest.SetProject(project)
+
+ netType := fabricv4.NetworkType(d.Get("type").(string))
+ createRequest.SetType(netType)
+
+ netScope := fabricv4.NetworkScope(d.Get("scope").(string))
+ createRequest.SetScope(netScope)
+
start := time.Now()
- fabricNetwork, _, err := client.NetworksApi.CreateNetwork(ctx, createRequest)
+ fabricNetwork, _, err := client.NetworksApi.CreateNetwork(ctx).NetworkPostRequest(createRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
d.SetId(fabricNetwork.Uuid)
createTimeout := d.Timeout(schema.TimeoutCreate) - 30*time.Second - time.Since(start)
- if _, err = waitUntilFabricNetworkIsProvisioned(d.Id(), meta, ctx, createTimeout); err != nil {
+ if _, err = waitUntilFabricNetworkIsProvisioned(d.Id(), meta, d, ctx, createTimeout); err != nil {
return diag.Errorf("error waiting for Network (%s) to be created: %s", d.Id(), err)
}
@@ -203,125 +206,121 @@ func resourceFabricNetworkCreate(ctx context.Context, d *schema.ResourceData, me
}
func resourceFabricNetworkRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- fabricNetwork, _, err := client.NetworksApi.GetNetworkByUuid(ctx, d.Id())
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ fabricNetwork, _, err := client.NetworksApi.GetNetworkByUuid(ctx, d.Id()).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
d.SetId(fabricNetwork.Uuid)
return setFabricNetworkMap(d, fabricNetwork)
}
-func fabricNetworkOperationToTerra(operation *v4.NetworkOperation) *schema.Set {
+
+func fabricNetworkOperationGoToTerraform(operation *fabricv4.NetworkOperation) *schema.Set {
if operation == nil {
return nil
}
- operations := []*v4.NetworkOperation{operation}
- mappedOperations := make([]interface{}, len(operations))
- for _, operation := range operations {
- mappedOperation := make(map[string]interface{})
- mappedOperation["equinix_status"] = string(*operation.EquinixStatus)
- mappedOperations = append(mappedOperations, mappedOperation)
- }
+ mappedOperation := make(map[string]interface{})
+ mappedOperation["equinix_status"] = string(*operation.EquinixStatus)
operationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: fabricNetworkOperationSch()}),
- mappedOperations,
+ []interface{}{mappedOperation},
)
return operationSet
}
-func simplifiedFabricNetworkChangeToTerra(networkChange *v4.SimplifiedNetworkChange) *schema.Set {
- changes := []*v4.SimplifiedNetworkChange{networkChange}
- mappedChanges := make([]interface{}, len(changes))
- for _, change := range changes {
- mappedChange := make(map[string]interface{})
- mappedChange["href"] = change.Href
- mappedChange["type"] = string(*change.Type_)
- mappedChange["uuid"] = change.Uuid
- mappedChanges = append(mappedChanges, mappedChange)
- }
+func simplifiedFabricNetworkChangeGoToTerraform(networkChange *fabricv4.SimplifiedNetworkChange) *schema.Set {
+
+ mappedChange := make(map[string]interface{})
+ mappedChange["href"] = networkChange.GetHref()
+ mappedChange["type"] = string(networkChange.GetType())
+ mappedChange["uuid"] = networkChange.GetUuid()
changeSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: fabricNetworkChangeSch()}),
- mappedChanges,
+ []interface{}{mappedChange},
)
return changeSet
}
-func setFabricNetworkMap(d *schema.ResourceData, nt v4.Network) diag.Diagnostics {
+func setFabricNetworkMap(d *schema.ResourceData, nt *fabricv4.Network) diag.Diagnostics {
diags := diag.Diagnostics{}
+ operation := nt.GetOperation()
+ change := nt.GetChange()
+ location := nt.GetLocation()
+ notifications := nt.GetNotifications()
+ project := nt.GetProject()
+ changeLog := nt.GetChangeLog()
err := equinix_schema.SetMap(d, map[string]interface{}{
- "name": nt.Name,
- "href": nt.Href,
- "uuid": nt.Uuid,
- "type": nt.Type_,
- "scope": nt.Scope,
- "state": nt.State,
- "operation": fabricNetworkOperationToTerra(nt.Operation),
- "change": simplifiedFabricNetworkChangeToTerra(nt.Change),
- "location": equinix_fabric_schema.LocationToTerra(nt.Location),
- "notifications": equinix_fabric_schema.NotificationsToTerra(nt.Notifications),
- "project": equinix_fabric_schema.ProjectToTerra(nt.Project),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(nt.ChangeLog),
- "connections_count": nt.ConnectionsCount,
+ "name": nt.GetName(),
+ "href": nt.GetHref(),
+ "uuid": nt.GetUuid(),
+ "type": string(nt.GetType()),
+ "scope": string(nt.GetScope()),
+ "state": string(nt.GetState()),
+ "operation": fabricNetworkOperationGoToTerraform(&operation),
+ "change": simplifiedFabricNetworkChangeGoToTerraform(&change),
+ "location": equinix_fabric_schema.LocationGoToTerraform(&location),
+ "notifications": equinix_fabric_schema.NotificationsGoToTerraform(notifications),
+ "project": equinix_fabric_schema.ProjectGoToTerraform(&project),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog),
+ "connections_count": nt.GetConnectionsCount(),
})
if err != nil {
return diag.FromErr(err)
}
return diags
}
-func getFabricNetworkUpdateRequest(network v4.Network, d *schema.ResourceData) (v4.NetworkChangeOperation, error) {
- changeOps := v4.NetworkChangeOperation{}
- existingName := network.Name
- updateNameVal := d.Get("name")
+func getFabricNetworkUpdateRequest(network *fabricv4.Network, d *schema.ResourceData) (fabricv4.NetworkChangeOperation, error) {
+ changeOps := fabricv4.NetworkChangeOperation{}
+ existingName := network.GetName()
+ updateNameVal := d.Get("name").(string)
log.Printf("existing name %s, Update Name Request %s ", existingName, updateNameVal)
if existingName != updateNameVal {
- changeOps = v4.NetworkChangeOperation{Op: "replace", Path: "/name", Value: &updateNameVal}
+ changeOps = fabricv4.NetworkChangeOperation{Op: "replace", Path: "/name", Value: updateNameVal}
} else {
return changeOps, fmt.Errorf("nothing to update for the Fabric Network: %s", existingName)
}
return changeOps, nil
}
+
func resourceFabricNetworkUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- dbConn, err := waitUntilFabricNetworkIsProvisioned(d.Id(), meta, ctx, updateTimeout)
- if err != nil {
- return diag.Errorf("either timed out or errored out while fetching Fabric Network for uuid %s and error %v", d.Id(), err)
+ dbConn, waitUntilNetworkProvisionedErr := waitUntilFabricNetworkIsProvisioned(d.Id(), meta, d, ctx, updateTimeout)
+ if waitUntilNetworkProvisionedErr != nil {
+ return diag.Errorf("either timed out or errored out while fetching Fabric Network for uuid %s and error %v", d.Id(), waitUntilNetworkProvisionedErr)
}
- update, err := getFabricNetworkUpdateRequest(dbConn, d)
- if err != nil {
- return diag.Errorf("error retrieving intended updates from network config: %v", err)
+ update, getUpdateRequestErr := getFabricNetworkUpdateRequest(dbConn, d)
+ if getUpdateRequestErr != nil {
+ return diag.Errorf("error retrieving intended updates from network config: %v", getUpdateRequestErr)
}
- updates := []v4.NetworkChangeOperation{update}
- _, res, err := client.NetworksApi.UpdateNetworkByUuid(ctx, updates, d.Id())
+ updates := []fabricv4.NetworkChangeOperation{update}
+ _, _, err := client.NetworksApi.UpdateNetworkByUuid(ctx, d.Id()).NetworkChangeOperation(updates).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- updateFg := v4.Network{}
updateTimeout = d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- updateFg, err = waitForFabricNetworkUpdateCompletion(d.Id(), meta, ctx, updateTimeout)
+ updateNetwork, waitForNetworkUpdateCompletionErr := waitForFabricNetworkUpdateCompletion(d.Id(), meta, d, ctx, updateTimeout)
- if err != nil {
- return diag.Errorf("errored while waiting for successful Fabric Network update, response %v, error %v", res, err)
+ if waitForNetworkUpdateCompletionErr != nil {
+ return diag.Errorf("errored while waiting for successful Fabric Network update error %v", waitForNetworkUpdateCompletionErr)
}
- d.SetId(updateFg.Uuid)
- return setFabricNetworkMap(d, updateFg)
+ d.SetId(updateNetwork.Uuid)
+ return setFabricNetworkMap(d, updateNetwork)
}
-func waitForFabricNetworkUpdateCompletion(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Network, error) {
+func waitForFabricNetworkUpdateCompletion(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Network, error) {
log.Printf("Waiting for Network update to complete, uuid %s", uuid)
stateConf := &resource.StateChangeConf{
- Target: []string{string(v4.PROVISIONED_NetworkEquinixStatus)},
+ Target: []string{string(fabricv4.NETWORKEQUINIXSTATUS_PROVISIONED)},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
@@ -333,26 +332,26 @@ func waitForFabricNetworkUpdateCompletion(uuid string, meta interface{}, ctx con
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.Network{}
+ var dbConn *fabricv4.Network
if err == nil {
- dbConn = inter.(v4.Network)
+ dbConn = inter.(*fabricv4.Network)
}
return dbConn, err
}
-func waitUntilFabricNetworkIsProvisioned(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.Network, error) {
+func waitUntilFabricNetworkIsProvisioned(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.Network, error) {
log.Printf("Waiting for Fabric Network to be provisioned, uuid %s", uuid)
stateConf := &resource.StateChangeConf{
Pending: []string{
- string(v4.PROVISIONING_NetworkEquinixStatus),
+ string(fabricv4.NETWORKEQUINIXSTATUS_PROVISIONING),
},
Target: []string{
- string(v4.PROVISIONED_NetworkEquinixStatus),
+ string(fabricv4.NETWORKEQUINIXSTATUS_PROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
@@ -364,51 +363,51 @@ func waitUntilFabricNetworkIsProvisioned(uuid string, meta interface{}, ctx cont
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.Network{}
+ var dbConn *fabricv4.Network
if err == nil {
- dbConn = inter.(v4.Network)
+ dbConn = inter.(*fabricv4.Network)
}
return dbConn, err
}
func resourceFabricNetworkDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
diags := diag.Diagnostics{}
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
- _, _, err := client.NetworksApi.DeleteNetworkByUuid(ctx, d.Id())
+ _, _, err := client.NetworksApi.DeleteNetworkByUuid(ctx, d.Id()).Execute()
if err != nil {
- errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError)
- if ok {
- // EQ-3040055 = There is an existing update in REQUESTED state
- if equinix_errors.HasModelErrorCode(errors, "EQ-3040055") {
- return diags
+ if genericError, ok := err.(*fabricv4.GenericOpenAPIError); ok {
+ if fabricErrs, ok := genericError.Model().([]fabricv4.Error); ok {
+ // EQ-3040055 = There is an existing update in REQUESTED state
+ if equinix_errors.HasErrorCode(fabricErrs, "EQ-3040055") {
+ return diags
+ }
}
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
deleteTimeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start)
- err = WaitUntilFabricNetworkDeprovisioned(d.Id(), meta, ctx, deleteTimeout)
+ err = WaitUntilFabricNetworkDeprovisioned(d.Id(), meta, d, ctx, deleteTimeout)
if err != nil {
return diag.Errorf("API call failed while waiting for resource deletion. Error %v", err)
}
return diags
}
-func WaitUntilFabricNetworkDeprovisioned(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) error {
+func WaitUntilFabricNetworkDeprovisioned(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for Fabric Network to be deprovisioned, uuid %s", uuid)
stateConf := &resource.StateChangeConf{
Pending: []string{
- string(v4.DEPROVISIONING_NetworkEquinixStatus),
+ string(fabricv4.NETWORKEQUINIXSTATUS_DEPROVISIONING),
},
Target: []string{
- string(v4.DEPROVISIONED_NetworkEquinixStatus),
+ string(fabricv4.NETWORKEQUINIXSTATUS_DEPROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.NetworksApi.GetNetworkByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
diff --git a/equinix/resource_fabric_network_acc_test.go b/equinix/resource_fabric_network_acc_test.go
index dc444e0c5..8d0e76984 100644
--- a/equinix/resource_fabric_network_acc_test.go
+++ b/equinix/resource_fabric_network_acc_test.go
@@ -3,14 +3,12 @@ package equinix_test
import (
"context"
"fmt"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"testing"
"time"
"github.com/equinix/terraform-provider-equinix/equinix"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
- "github.com/equinix/terraform-provider-equinix/internal/config"
-
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)
@@ -28,7 +26,7 @@ func testSweepNetworks(region string) error {
func TestAccFabricNetworkCreateOnlyRequiredParameters_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkNetworkDelete,
Steps: []resource.TestStep{
@@ -83,12 +81,11 @@ func testAccNetworkCreateOnlyRequiredParameterConfig_PFCR(name string) string {
}
func checkNetworkDelete(s *terraform.State) error {
ctx := context.Background()
- ctx = context.WithValue(ctx, v4.ContextAccessToken, acceptance.TestAccProvider.Meta().(*config.Config).FabricAuthToken)
for _, rs := range s.RootModule().Resources {
if rs.Type != "equinix_fabric_network" {
continue
}
- err := equinix.WaitUntilFabricNetworkDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), ctx, 10*time.Minute)
+ err := equinix.WaitUntilFabricNetworkDeprovisioned(rs.Primary.ID, acceptance.TestAccProvider.Meta(), &schema.ResourceData{}, ctx, 10*time.Minute)
if err != nil {
return fmt.Errorf("API call failed while waiting for resource deletion")
}
@@ -98,7 +95,7 @@ func checkNetworkDelete(s *terraform.State) error {
func TestAccFabricNetworkCreateMixedParameters_PFCR(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkNetworkDelete,
Steps: []resource.TestStep{
diff --git a/equinix/resource_fabric_port.go b/equinix/resource_fabric_port.go
index ca24f9ee8..5130f363e 100644
--- a/equinix/resource_fabric_port.go
+++ b/equinix/resource_fabric_port.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"log"
"runtime/debug"
"strings"
@@ -14,8 +15,6 @@ import (
"github.com/equinix/terraform-provider-equinix/internal/config"
- "github.com/antihax/optional"
- 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/schema"
)
@@ -249,170 +248,120 @@ func readGetPortsByNameQueryParamSch() map[string]*schema.Schema {
}
}
-func portToFabric(portList []interface{}) v4.SimplifiedPort {
- p := v4.SimplifiedPort{}
- for _, pl := range portList {
- plMap := pl.(map[string]interface{})
- uuid := plMap["uuid"].(string)
- p = v4.SimplifiedPort{Uuid: uuid}
+func portTerraformToGo(portList []interface{}) fabricv4.SimplifiedPort {
+ if portList == nil || len(portList) == 0 {
+ return fabricv4.SimplifiedPort{}
}
- return p
+ var port fabricv4.SimplifiedPort
+ portListMap := portList[0].(map[string]interface{})
+ uuid := portListMap["uuid"].(string)
+ port.SetUuid(uuid)
+
+ return port
}
-func portToTerra(port *v4.SimplifiedPort) *schema.Set {
- ports := []*v4.SimplifiedPort{port}
- mappedPorts := make([]interface{}, len(ports))
- for _, port := range ports {
- mappedPort := make(map[string]interface{})
- mappedPort["href"] = port.Href
- mappedPort["name"] = port.Name
- mappedPort["uuid"] = port.Uuid
- if port.Redundancy != nil {
- mappedPort["redundancy"] = PortRedundancyToTerra(port.Redundancy)
- }
- mappedPorts = append(mappedPorts, mappedPort)
+func portGoToTerraform(port *fabricv4.SimplifiedPort) *schema.Set {
+ mappedPort := make(map[string]interface{})
+ mappedPort["href"] = port.GetHref()
+ mappedPort["name"] = port.GetName()
+ mappedPort["uuid"] = port.GetUuid()
+ if port.Redundancy != nil {
+ mappedPort["redundancy"] = portRedundancyGoToTerraform(port.Redundancy)
}
portSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: portSch()}),
- mappedPorts,
+ []interface{}{mappedPort},
)
return portSet
}
-func PortRedundancyToTerra(redundancy *v4.PortRedundancy) *schema.Set {
+func portRedundancyGoToTerraform(redundancy *fabricv4.PortRedundancy) *schema.Set {
if redundancy == nil {
return nil
}
- redundancies := []*v4.PortRedundancy{redundancy}
- mappedRedundancies := make([]interface{}, 0)
- for _, redundancy := range redundancies {
- mappedRedundancy := make(map[string]interface{})
- mappedRedundancy["enabled"] = redundancy.Enabled
- mappedRedundancy["group"] = redundancy.Group
- mappedRedundancy["priority"] = string(*redundancy.Priority)
- mappedRedundancies = append(mappedRedundancies, mappedRedundancy)
- }
+ mappedRedundancy := make(map[string]interface{})
+ mappedRedundancy["enabled"] = redundancy.GetEnabled()
+ mappedRedundancy["group"] = redundancy.GetGroup()
+ mappedRedundancy["priority"] = string(redundancy.GetPriority())
+
redundancySet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: PortRedundancySch()}),
- mappedRedundancies,
+ []interface{}{mappedRedundancy},
)
return redundancySet
}
-func portOperationToTerra(operation *v4.PortOperation) *schema.Set {
+func portOperationGoToTerraform(operation *fabricv4.PortOperation) *schema.Set {
if operation == nil {
return nil
}
- operations := []*v4.PortOperation{operation}
- mappedOperations := make([]interface{}, 0)
- for _, operation := range operations {
- mappedOperation := make(map[string]interface{})
- mappedOperation["operational_status"] = operation.OperationalStatus
- mappedOperation["connection_count"] = operation.ConnectionCount
- mappedOperation["op_status_changed_at"] = operation.OpStatusChangedAt.String()
- mappedOperations = append(mappedOperations, mappedOperation)
- }
+
+ mappedOperation := make(map[string]interface{})
+ mappedOperation["operational_status"] = operation.GetOperationalStatus()
+ mappedOperation["connection_count"] = operation.GetConnectionCount()
+ mappedOperation["op_status_changed_at"] = operation.GetOpStatusChangedAt().String()
+
operationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: operationSch()}),
- mappedOperations,
+ []interface{}{mappedOperation},
)
return operationSet
}
-func portDeviceRedundancyToTerra(redundancy *v4.PortDeviceRedundancy) *schema.Set {
+func portDeviceRedundancyGoToTerraform(redundancy *fabricv4.PortDeviceRedundancy) *schema.Set {
if redundancy == nil {
return nil
}
- redundancies := []*v4.PortDeviceRedundancy{redundancy}
- mappedRedundancies := make([]interface{}, 0)
- for _, redundancy := range redundancies {
- mappedRedundancy := make(map[string]interface{})
- mappedRedundancy["group"] = redundancy.Group
- mappedRedundancy["priority"] = redundancy.Priority
- mappedRedundancies = append(mappedRedundancies, mappedRedundancy)
- }
+
+ mappedRedundancy := make(map[string]interface{})
+ mappedRedundancy["group"] = redundancy.GetGroup()
+ mappedRedundancy["priority"] = string(redundancy.GetPriority())
+
redundancySet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: PortRedundancySch()}),
- mappedRedundancies,
+ []interface{}{mappedRedundancy},
)
return redundancySet
}
-func portDeviceToTerra(device *v4.PortDevice) *schema.Set {
+func portDeviceGoToTerraform(device *fabricv4.PortDevice) *schema.Set {
if device == nil {
return nil
}
- devices := []*v4.PortDevice{device}
- mappedDevices := make([]interface{}, 0)
- for _, device := range devices {
- mappedDevice := make(map[string]interface{})
- mappedDevice["name"] = device.Name
- if device.Redundancy != nil {
- mappedDevice["redundancy"] = portDeviceRedundancyToTerra(device.Redundancy)
- }
- mappedDevices = append(mappedDevices, mappedDevice)
+
+ mappedDevice := make(map[string]interface{})
+ mappedDevice["name"] = device.GetName()
+ redundancy := device.GetRedundancy()
+ if &redundancy != nil {
+ mappedDevice["redundancy"] = portDeviceRedundancyGoToTerraform(&redundancy)
}
+
deviceSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: portDeviceSch()}),
- mappedDevices,
+ []interface{}{mappedDevice},
)
return deviceSet
}
-func portEncapsulationToTerra(portEncapsulation *v4.PortEncapsulation) *schema.Set {
+func portEncapsulationGoToTerraform(portEncapsulation *fabricv4.PortEncapsulation) *schema.Set {
if portEncapsulation == nil {
return nil
}
- portEncapsulations := []*v4.PortEncapsulation{portEncapsulation}
- mappedPortEncapsulations := make([]interface{}, 0)
- for _, portEncapsulation := range portEncapsulations {
- mappedPortEncapsulation := make(map[string]interface{})
- mappedPortEncapsulation["type"] = portEncapsulation.Type_
- mappedPortEncapsulation["tag_protocol_id"] = portEncapsulation.TagProtocolId
- mappedPortEncapsulations = append(mappedPortEncapsulations, mappedPortEncapsulation)
- }
+
+ mappedPortEncapsulation := make(map[string]interface{})
+ mappedPortEncapsulation["type"] = string(portEncapsulation.GetType())
+ mappedPortEncapsulation["tag_protocol_id"] = portEncapsulation.GetTagProtocolId()
+
portEncapsulationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: portEncapsulationSch()}),
- mappedPortEncapsulations,
+ []interface{}{mappedPortEncapsulation},
)
return portEncapsulationSet
}
-func fabricPortsListToTerra(ports v4.AllPortsResponse) []map[string]interface{} {
- portsl := ports.Data
- if portsl == nil {
- return nil
- }
- mappedPortsl := make([]map[string]interface{}, len(portsl))
- for index, port := range portsl {
- mappedPortsl[index] = map[string]interface{}{
- "uuid": port.Uuid,
- "name": port.Name,
- "bandwidth": port.Bandwidth,
- "available_bandwidth": port.AvailableBandwidth,
- "used_bandwidth": port.UsedBandwidth,
- "href": port.Href,
- "description": port.Description,
- "type": port.Type_,
- "state": port.State,
- "service_type": port.ServiceType,
- "operation": portOperationToTerra(port.Operation),
- "redundancy": PortRedundancyToTerra(port.Redundancy),
- "account": equinix_fabric_schema.AccountToTerra(port.Account),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(port.Changelog),
- "location": equinix_fabric_schema.LocationToTerra(port.Location),
- "device": portDeviceToTerra(port.Device),
- "encapsulation": portEncapsulationToTerra(port.Encapsulation),
- "lag_enabled": port.LagEnabled,
- }
- }
- return mappedPortsl
-}
-
func resourceFabricPortRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- port, _, err := client.PortsApi.GetPortByUuid(ctx, d.Id())
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ port, _, err := client.PortsApi.GetPortByUuid(ctx, d.Id()).Execute()
if err != nil {
log.Printf("[WARN] Port %s not found , error %s", d.Id(), err)
if !strings.Contains(err.Error(), "500") {
@@ -420,41 +369,62 @@ func resourceFabricPortRead(ctx context.Context, d *schema.ResourceData, meta in
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(port.Uuid)
+ d.SetId(port.GetUuid())
return setFabricPortMap(d, port)
}
-func setFabricPortMap(d *schema.ResourceData, port v4.Port) diag.Diagnostics {
+func fabricPortMap(port *fabricv4.PortResponse) map[string]interface{} {
+ operation := port.GetOperation()
+ redundancy := port.GetRedundancy()
+ account := port.GetAccount()
+ changelog := port.GetChangelog()
+ location := port.GetLocation()
+ device := port.GetDevice()
+ encapsulation := port.GetEncapsulation()
+ return map[string]interface{}{
+ "uuid": port.GetUuid(),
+ "name": port.GetName(),
+ "bandwidth": port.GetBandwidth(),
+ "available_bandwidth": port.GetAvailableBandwidth(),
+ "used_bandwidth": port.GetUsedBandwidth(),
+ "href": port.GetHref(),
+ "description": port.GetDescription(),
+ "type": string(port.GetType()),
+ "state": string(port.GetState()),
+ "service_type": string(port.GetServiceType()),
+ "operation": portOperationGoToTerraform(&operation),
+ "redundancy": portRedundancyGoToTerraform(&redundancy),
+ "account": equinix_fabric_schema.AccountGoToTerraform(&account),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changelog),
+ "location": equinix_fabric_schema.LocationGoToTerraform(&location),
+ "device": portDeviceGoToTerraform(&device),
+ "encapsulation": portEncapsulationGoToTerraform(&encapsulation),
+ "lag_enabled": port.GetLagEnabled(),
+ }
+}
+
+func setFabricPortMap(d *schema.ResourceData, port *fabricv4.PortResponse) diag.Diagnostics {
diags := diag.Diagnostics{}
- err := equinix_schema.SetMap(d, map[string]interface{}{
- "name": port.Name,
- "bandwidth": port.Bandwidth,
- "available_bandwidth": port.AvailableBandwidth,
- "used_bandwidth": port.UsedBandwidth,
- "href": port.Href,
- "description": port.Description,
- "type": port.Type_,
- "state": port.State,
- "service_type": port.ServiceType,
- "operation": portOperationToTerra(port.Operation),
- "redundancy": PortRedundancyToTerra(port.Redundancy),
- "account": equinix_fabric_schema.AccountToTerra(port.Account),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(port.Changelog),
- "location": equinix_fabric_schema.LocationToTerra(port.Location),
- "device": portDeviceToTerra(port.Device),
- "encapsulation": portEncapsulationToTerra(port.Encapsulation),
- "lag_enabled": port.LagEnabled,
- })
+ err := equinix_schema.SetMap(d, fabricPortMap(port))
if err != nil {
return diag.FromErr(err)
}
return diags
}
-func setPortsListMap(d *schema.ResourceData, spl v4.AllPortsResponse) diag.Diagnostics {
+func setPortsListMap(d *schema.ResourceData, portResponse *fabricv4.AllPortsResponse) diag.Diagnostics {
diags := diag.Diagnostics{}
+ ports := portResponse.Data
+ if ports == nil {
+ return nil
+ }
+ mappedPorts := make([]map[string]interface{}, len(ports))
+ for index, port := range ports {
+ mappedPorts[index] = fabricPortMap(&port)
+ }
+
err := equinix_schema.SetMap(d, map[string]interface{}{
- "data": fabricPortsListToTerra(spl),
+ "data": mappedPorts,
})
if err != nil {
return diag.FromErr(err)
@@ -478,11 +448,10 @@ func resourceFabricPortGetByPortName(ctx context.Context, d *schema.ResourceData
}
}()
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
portNameParam := d.Get("filters").(*schema.Set).List()
- portName := portNameQueryParamToFabric(portNameParam)
- ports, _, err := client.PortsApi.GetPorts(ctx, &portName)
+ portName := portName(portNameParam)
+ ports, _, err := client.PortsApi.GetPorts(ctx).Name(portName).Execute()
if err != nil {
log.Printf("[WARN] Ports not found , error %s", err)
if !strings.Contains(err.Error(), "500") {
@@ -496,20 +465,16 @@ func resourceFabricPortGetByPortName(ctx context.Context, d *schema.ResourceData
return diag.FromErr(error)
}
- d.SetId(ports.Data[0].Uuid)
+ d.SetId(ports.Data[0].GetUuid())
return setPortsListMap(d, ports)
}
-func portNameQueryParamToFabric(portNameParam []interface{}) v4.PortsApiGetPortsOpts {
+func portName(portNameParam []interface{}) string {
if len(portNameParam) == 0 {
- return v4.PortsApiGetPortsOpts{}
+ return ""
}
- mappedPn := v4.PortsApiGetPortsOpts{}
- for _, pn := range portNameParam {
- pnMap := pn.(map[string]interface{})
- portName := pnMap["name"].(string)
- pName := optional.NewString(portName)
- mappedPn = v4.PortsApiGetPortsOpts{Name: pName}
- }
- return mappedPn
+
+ pnMap := portNameParam[0].(map[string]interface{})
+ portName := pnMap["name"].(string)
+ return portName
}
diff --git a/equinix/resource_fabric_routing_protocol.go b/equinix/resource_fabric_routing_protocol.go
index aa5af4bf2..e2591759b 100644
--- a/equinix/resource_fabric_routing_protocol.go
+++ b/equinix/resource_fabric_routing_protocol.go
@@ -3,6 +3,7 @@ package equinix
import (
"context"
"fmt"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"log"
"strconv"
@@ -16,7 +17,6 @@ import (
"github.com/equinix/terraform-provider-equinix/internal/config"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
- 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/schema"
)
@@ -286,10 +286,9 @@ func resourceFabricRoutingProtocol() *schema.Resource {
}
func resourceFabricRoutingProtocolRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
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))
+ fabricRoutingProtocolData, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string)).Execute()
if err != nil {
log.Printf("[WARN] Routing Protocol %s not found , error %s", d.Id(), err)
if !strings.Contains(err.Error(), "500") {
@@ -297,96 +296,30 @@ func resourceFabricRoutingProtocolRead(ctx context.Context, d *schema.ResourceDa
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- switch fabricRoutingProtocol.Type_ {
- case "BGP":
- d.SetId(fabricRoutingProtocol.RoutingProtocolBgpData.Uuid)
- case "DIRECT":
- d.SetId(fabricRoutingProtocol.RoutingProtocolDirectData.Uuid)
- }
- return setFabricRoutingProtocolMap(d, fabricRoutingProtocol)
+ _ = setIdFromAPIResponse(fabricRoutingProtocolData, false, d)
+
+ return setFabricRoutingProtocolMap(d, fabricRoutingProtocolData)
}
func resourceFabricRoutingProtocolCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- schemaBgpIpv4 := d.Get("bgp_ipv4").(*schema.Set).List()
- bgpIpv4 := routingProtocolBgpIpv4ToFabric(schemaBgpIpv4)
- schemaBgpIpv6 := d.Get("bgp_ipv6").(*schema.Set).List()
- bgpIpv6 := routingProtocolBgpIpv6ToFabric(schemaBgpIpv6)
- schemaDirectIpv4 := d.Get("direct_ipv4").(*schema.Set).List()
- directIpv4 := routingProtocolDirectIpv4ToFabric(schemaDirectIpv4)
- schemaDirectIpv6 := d.Get("direct_ipv6").(*schema.Set).List()
- directIpv6 := routingProtocolDirectIpv6ToFabric(schemaDirectIpv6)
- schemaBfd := d.Get("bfd").(*schema.Set).List()
- bfd := routingProtocolBfdToFabric(schemaBfd)
- bgpAuthKey := d.Get("bgp_auth_key")
- if bgpAuthKey == nil {
- bgpAuthKey = ""
- }
-
- createRequest := v4.RoutingProtocolBase{}
- if d.Get("type").(string) == "BGP" {
- createRequest = v4.RoutingProtocolBase{
- Type_: d.Get("type").(string),
- OneOfRoutingProtocolBase: v4.OneOfRoutingProtocolBase{
- RoutingProtocolBgpType: v4.RoutingProtocolBgpType{
- Type_: d.Get("type").(string),
- Name: d.Get("name").(string),
- BgpIpv4: &bgpIpv4,
- BgpIpv6: &bgpIpv6,
- CustomerAsn: int64(d.Get("customer_asn").(int)),
- EquinixAsn: int64(d.Get("equinix_asn").(int)),
- BgpAuthKey: bgpAuthKey.(string),
- Bfd: &bfd,
- },
- },
- }
- if bgpIpv4.CustomerPeerIp == "" {
- createRequest.BgpIpv4 = nil
- }
- if bgpIpv6.CustomerPeerIp == "" {
- createRequest.BgpIpv6 = nil
- }
- if bfd.Enabled == false {
- createRequest.Bfd = nil
- }
- }
- if d.Get("type").(string) == "DIRECT" {
- createRequest = v4.RoutingProtocolBase{
- Type_: d.Get("type").(string),
- OneOfRoutingProtocolBase: v4.OneOfRoutingProtocolBase{
- RoutingProtocolDirectType: v4.RoutingProtocolDirectType{
- Type_: d.Get("type").(string),
- Name: d.Get("name").(string),
- DirectIpv4: &directIpv4,
- DirectIpv6: &directIpv6,
- },
- },
- }
- if directIpv4.EquinixIfaceIp == "" {
- createRequest.DirectIpv4 = nil
- }
- if directIpv6.EquinixIfaceIp == "" {
- createRequest.DirectIpv6 = nil
- }
- }
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
start := time.Now()
- fabricRoutingProtocol, _, err := client.RoutingProtocolsApi.CreateConnectionRoutingProtocol(ctx, createRequest, d.Get("connection_uuid").(string))
+ type_ := d.Get("type").(string)
+
+ createRequest := routingProtocolPayloadFromType(type_, d)
+
+ fabricRoutingProtocolData, _, err := client.RoutingProtocolsApi.CreateConnectionRoutingProtocol(ctx, d.Get("connection_uuid").(string)).RoutingProtocolBase(createRequest).Execute()
+
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- switch fabricRoutingProtocol.Type_ {
- case "BGP":
- d.SetId(fabricRoutingProtocol.RoutingProtocolBgpData.Uuid)
- case "DIRECT":
- d.SetId(fabricRoutingProtocol.RoutingProtocolDirectData.Uuid)
- }
+ _ = setIdFromAPIResponse(fabricRoutingProtocolData, false, d)
createTimeout := d.Timeout(schema.TimeoutCreate) - 30*time.Second - time.Since(start)
- if _, err = waitUntilRoutingProtocolIsProvisioned(d.Id(), d.Get("connection_uuid").(string), meta, ctx, createTimeout); err != nil {
+ if _, err = waitUntilRoutingProtocolIsProvisioned(d.Id(), d.Get("connection_uuid").(string), meta, d, ctx, createTimeout); err != nil {
return diag.Errorf("error waiting for RP (%s) to be created: %s", d.Id(), err)
}
@@ -394,93 +327,31 @@ func resourceFabricRoutingProtocolCreate(ctx context.Context, d *schema.Resource
}
func resourceFabricRoutingProtocolUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
-
- schemaBgpIpv4 := d.Get("bgp_ipv4").(*schema.Set).List()
- bgpIpv4 := routingProtocolBgpIpv4ToFabric(schemaBgpIpv4)
- schemaBgpIpv6 := d.Get("bgp_ipv6").(*schema.Set).List()
- bgpIpv6 := routingProtocolBgpIpv6ToFabric(schemaBgpIpv6)
- schemaDirectIpv4 := d.Get("direct_ipv4").(*schema.Set).List()
- directIpv4 := routingProtocolDirectIpv4ToFabric(schemaDirectIpv4)
- schemaDirectIpv6 := d.Get("direct_ipv6").(*schema.Set).List()
- directIpv6 := routingProtocolDirectIpv6ToFabric(schemaDirectIpv6)
- schemaBfd := d.Get("bfd").(*schema.Set).List()
- bfd := routingProtocolBfdToFabric(schemaBfd)
- bgpAuthKey := d.Get("bgp_auth_key")
- if bgpAuthKey == nil {
- bgpAuthKey = ""
- }
-
- updateRequest := v4.RoutingProtocolBase{}
- if d.Get("type").(string) == "BGP" {
- updateRequest = v4.RoutingProtocolBase{
- Type_: d.Get("type").(string),
- OneOfRoutingProtocolBase: v4.OneOfRoutingProtocolBase{
- RoutingProtocolBgpType: v4.RoutingProtocolBgpType{
- Type_: d.Get("type").(string),
- Name: d.Get("name").(string),
- BgpIpv4: &bgpIpv4,
- BgpIpv6: &bgpIpv6,
- CustomerAsn: int64(d.Get("customer_asn").(int)),
- EquinixAsn: int64(d.Get("equinix_asn").(int)),
- BgpAuthKey: bgpAuthKey.(string),
- Bfd: &bfd,
- },
- },
- }
- if bgpIpv4.CustomerPeerIp == "" {
- updateRequest.BgpIpv4 = nil
- }
- if bgpIpv6.CustomerPeerIp == "" {
- updateRequest.BgpIpv6 = nil
- }
- }
- if d.Get("type").(string) == "DIRECT" {
- updateRequest = v4.RoutingProtocolBase{
- Type_: d.Get("type").(string),
- OneOfRoutingProtocolBase: v4.OneOfRoutingProtocolBase{
- RoutingProtocolDirectType: v4.RoutingProtocolDirectType{
- Type_: d.Get("type").(string),
- Name: d.Get("name").(string),
- DirectIpv4: &directIpv4,
- DirectIpv6: &directIpv6,
- },
- },
- }
- if directIpv4.EquinixIfaceIp == "" {
- updateRequest.DirectIpv4 = nil
- }
- if directIpv6.EquinixIfaceIp == "" {
- updateRequest.DirectIpv6 = nil
- }
- }
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+
+ type_ := d.Get("type").(string)
+
+ updateRequest := routingProtocolPayloadFromType(type_, d)
start := time.Now()
- updatedRpResp, _, err := client.RoutingProtocolsApi.ReplaceConnectionRoutingProtocolByUuid(ctx, updateRequest, d.Id(), d.Get("connection_uuid").(string))
+ updatedRpResp, _, err := client.RoutingProtocolsApi.ReplaceConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string)).RoutingProtocolBase(updateRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- var changeUuid string
- switch updatedRpResp.Type_ {
- case "BGP":
- changeUuid = updatedRpResp.RoutingProtocolBgpData.Change.Uuid
- d.SetId(updatedRpResp.RoutingProtocolBgpData.Uuid)
- case "DIRECT":
- changeUuid = updatedRpResp.RoutingProtocolDirectData.Change.Uuid
- d.SetId(updatedRpResp.RoutingProtocolDirectData.Uuid)
- }
+ changeUuid := setIdFromAPIResponse(updatedRpResp, true, d)
+
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- _, err = waitForRoutingProtocolUpdateCompletion(changeUuid, d.Id(), d.Get("connection_uuid").(string), meta, ctx, updateTimeout)
+ _, err = waitForRoutingProtocolUpdateCompletion(changeUuid, d.Id(), d.Get("connection_uuid").(string), meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
}
return diag.FromErr(fmt.Errorf("timeout updating routing protocol: %v", err))
}
+
updateTimeout = d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- updatedProvisionedRpResp, err := waitUntilRoutingProtocolIsProvisioned(d.Id(), d.Get("connection_uuid").(string), meta, ctx, updateTimeout)
+ updatedProvisionedRpResp, err := waitUntilRoutingProtocolIsProvisioned(d.Id(), d.Get("connection_uuid").(string), meta, d, ctx, updateTimeout)
if err != nil {
return diag.Errorf("error waiting for RP (%s) to be replace updated: %s", d.Id(), err)
}
@@ -490,23 +361,23 @@ 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.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
start := time.Now()
- _, _, err := client.RoutingProtocolsApi.DeleteConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string))
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ _, _, err := client.RoutingProtocolsApi.DeleteConnectionRoutingProtocolByUuid(ctx, d.Id(), d.Get("connection_uuid").(string)).Execute()
if err != nil {
- errors, ok := err.(v4.GenericSwaggerError).Model().([]v4.ModelError)
- if ok {
- // EQ-3142509 = Connection already deleted
- if equinix_errors.HasModelErrorCode(errors, "EQ-3142509") {
- return diags
+ if genericError, ok := err.(*fabricv4.GenericOpenAPIError); ok {
+ if fabricErrs, ok := genericError.Model().([]fabricv4.Error); ok {
+ // EQ-3041121 = Routing Protocol already deleted
+ if equinix_errors.HasErrorCode(fabricErrs, "EQ-3041121") {
+ return diags
+ }
}
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
deleteTimeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start)
- err = WaitUntilRoutingProtocolIsDeprovisioned(d.Id(), d.Get("connection_uuid").(string), meta, ctx, deleteTimeout)
+ err = WaitUntilRoutingProtocolIsDeprovisioned(d.Id(), d.Get("connection_uuid").(string), meta, d, ctx, deleteTimeout)
if err != nil {
return diag.FromErr(fmt.Errorf("API call failed while waiting for resource deletion. Error %v", err))
}
@@ -514,67 +385,168 @@ func resourceFabricRoutingProtocolDelete(ctx context.Context, d *schema.Resource
return diags
}
-func setFabricRoutingProtocolMap(d *schema.ResourceData, rp v4.RoutingProtocolData) diag.Diagnostics {
+func setIdFromAPIResponse(resp *fabricv4.RoutingProtocolData, isChange bool, d *schema.ResourceData) string {
+ var changeUuid string
+
+ switch rpData := resp.GetActualInstance().(type) {
+ case *fabricv4.RoutingProtocolBGPData:
+ if isChange {
+ change := rpData.GetChange()
+ changeUuid = change.GetUuid()
+ }
+ d.SetId(rpData.GetUuid())
+ case *fabricv4.RoutingProtocolDirectData:
+ if isChange {
+ change := rpData.GetChange()
+ changeUuid = change.GetUuid()
+ }
+ d.SetId(rpData.GetUuid())
+ }
+
+ return changeUuid
+}
+
+func routingProtocolPayloadFromType(type_ string, d *schema.ResourceData) fabricv4.RoutingProtocolBase {
+ payload := fabricv4.RoutingProtocolBase{}
+ if type_ == "BGP" {
+ bgpRP := fabricv4.RoutingProtocolBGPType{}
+ bgpType := fabricv4.RoutingProtocolBGPTypeType(type_)
+ bgpRP.SetType(bgpType)
+
+ name := d.Get("name").(string)
+ if name != "" {
+ bgpRP.SetName(name)
+ }
+
+ if customerASNSchema, ok := d.GetOk("customer_asn"); ok {
+ customerASN := int64(customerASNSchema.(int))
+ bgpRP.SetCustomerAsn(customerASN)
+ }
+
+ if equinixASNSchema, ok := d.GetOk("equinix_asn"); ok {
+ equinixASN := int64(equinixASNSchema.(int))
+ bgpRP.SetEquinixAsn(equinixASN)
+ }
+
+ bgpAuthKey := d.Get("bgp_auth_key").(string)
+ if bgpAuthKey != "" {
+ bgpRP.SetBgpAuthKey(bgpAuthKey)
+ }
+
+ if schemaBgpIpv4, ok := d.GetOk("bgp_ipv4"); ok {
+ bgpIpv4 := routingProtocolBgpIpv4TerraformToGo(schemaBgpIpv4.(*schema.Set).List())
+ bgpRP.SetBgpIpv4(bgpIpv4)
+ }
+
+ if schemaBgpIpv6, ok := d.GetOk("bgp_ipv6"); ok {
+ bgpIpv6 := routingProtocolBgpIpv6TerraformToGo(schemaBgpIpv6.(*schema.Set).List())
+ bgpRP.SetBgpIpv6(bgpIpv6)
+ }
+
+ if bfdSchema, ok := d.GetOk("bfd"); ok {
+ bfd := routingProtocolBfdTerraformToGo(bfdSchema.(*schema.Set).List())
+ bgpRP.SetBfd(bfd)
+ }
+ payload = fabricv4.RoutingProtocolBGPTypeAsRoutingProtocolBase(&bgpRP)
+ }
+ if type_ == "DIRECT" {
+ directRP := fabricv4.RoutingProtocolDirectType{}
+ directType := fabricv4.RoutingProtocolDirectTypeType(type_)
+ directRP.SetType(directType)
+
+ name := d.Get("name").(string)
+ if name != "" {
+ directRP.SetName(name)
+ }
+ if schemaDirectIpv4, ok := d.GetOk("direct_ipv4"); ok {
+ directIpv4 := routingProtocolDirectIpv4TerraformToGo(schemaDirectIpv4.(*schema.Set).List())
+ directRP.SetDirectIpv4(directIpv4)
+ }
+
+ if schemaDirectIpv6, ok := d.GetOk("direct_ipv6"); ok {
+ directIpv6 := routingProtocolDirectIpv6TerraformToGo(schemaDirectIpv6.(*schema.Set).List())
+ directRP.SetDirectIpv6(directIpv6)
+ }
+ payload = fabricv4.RoutingProtocolDirectTypeAsRoutingProtocolBase(&directRP)
+ }
+ return payload
+}
+
+func setFabricRoutingProtocolMap(d *schema.ResourceData, routingProtocolData *fabricv4.RoutingProtocolData) diag.Diagnostics {
diags := diag.Diagnostics{}
- err := error(nil)
- if rp.Type_ == "BGP" {
- err = equinix_schema.SetMap(d, map[string]interface{}{
- "name": rp.RoutingProtocolBgpData.Name,
- "href": rp.RoutingProtocolBgpData.Href,
- "type": rp.RoutingProtocolBgpData.Type_,
- "state": rp.RoutingProtocolBgpData.State,
- "operation": routingProtocolOperationToTerra(rp.RoutingProtocolBgpData.Operation),
- "bgp_ipv4": routingProtocolBgpConnectionIpv4ToTerra(rp.BgpIpv4),
- "bgp_ipv6": routingProtocolBgpConnectionIpv6ToTerra(rp.BgpIpv6),
- "customer_asn": rp.CustomerAsn,
- "equinix_asn": rp.EquinixAsn,
- "bfd": routingProtocolBfdToTerra(rp.Bfd),
- "bgp_auth_key": rp.BgpAuthKey,
- "change": routingProtocolChangeToTerra(rp.RoutingProtocolBgpData.Change),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(rp.RoutingProtocolBgpData.Changelog),
+ switch rp := routingProtocolData.GetActualInstance().(type) {
+ case *fabricv4.RoutingProtocolBGPData:
+ operation := rp.GetOperation()
+ bgpIpv4 := rp.GetBgpIpv4()
+ bgpIpv6 := rp.GetBgpIpv6()
+ bfd := rp.GetBfd()
+ change := rp.GetChange()
+ changeLog := rp.GetChangelog()
+ err := equinix_schema.SetMap(d, map[string]interface{}{
+ "name": rp.GetName(),
+ "href": rp.GetHref(),
+ "type": string(rp.GetType()),
+ "state": string(rp.GetState()),
+ "operation": routingProtocolOperationGoToTerraform(&operation),
+ "bgp_ipv4": routingProtocolBgpConnectionIpv4GoToTerraform(&bgpIpv4),
+ "bgp_ipv6": routingProtocolBgpConnectionIpv6GoToTerraform(&bgpIpv6),
+ "customer_asn": rp.GetCustomerAsn(),
+ "equinix_asn": rp.GetEquinixAsn(),
+ "bfd": routingProtocolBfdGoToTerraform(&bfd),
+ "bgp_auth_key": rp.GetBgpAuthKey(),
+ "change": routingProtocolChangeGoToTerraform(&change),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog),
})
- } else if rp.Type_ == "DIRECT" {
- err = equinix_schema.SetMap(d, map[string]interface{}{
- "name": rp.RoutingProtocolDirectData.Name,
- "href": rp.RoutingProtocolDirectData.Href,
- "type": rp.RoutingProtocolDirectData.Type_,
- "state": rp.RoutingProtocolDirectData.State,
- "operation": routingProtocolOperationToTerra(rp.RoutingProtocolDirectData.Operation),
- "direct_ipv4": routingProtocolDirectConnectionIpv4ToTerra(rp.DirectIpv4),
- "direct_ipv6": routingProtocolDirectConnectionIpv6ToTerra(rp.DirectIpv6),
- "change": routingProtocolChangeToTerra(rp.RoutingProtocolDirectData.Change),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(rp.RoutingProtocolDirectData.Changelog),
+ if err != nil {
+ return diag.FromErr(err)
+ }
+ case *fabricv4.RoutingProtocolDirectData:
+ operation := rp.GetOperation()
+ directIpv4 := rp.GetDirectIpv4()
+ directIpv6 := rp.GetDirectIpv6()
+ change := rp.GetChange()
+ changeLog := rp.GetChangelog()
+ err := equinix_schema.SetMap(d, map[string]interface{}{
+ "name": rp.GetName(),
+ "href": rp.GetHref(),
+ "type": string(rp.GetType()),
+ "state": string(rp.GetState()),
+ "operation": routingProtocolOperationGoToTerraform(&operation),
+ "direct_ipv4": routingProtocolDirectConnectionIpv4GoToTerraform(&directIpv4),
+ "direct_ipv6": routingProtocolDirectConnectionIpv6GoToTerraform(&directIpv6),
+ "change": routingProtocolChangeGoToTerraform(&change),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog),
})
- }
- if err != nil {
- return diag.FromErr(err)
+ if err != nil {
+ return diag.FromErr(err)
+ }
}
return diags
}
-
-func waitUntilRoutingProtocolIsProvisioned(uuid string, connUuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.RoutingProtocolData, error) {
+func waitUntilRoutingProtocolIsProvisioned(uuid string, connUuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.RoutingProtocolData, error) {
log.Printf("Waiting for routing protocol to be provisioned, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Pending: []string{
- string(v4.PROVISIONING_ConnectionState),
- string(v4.REPROVISIONING_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_PROVISIONING),
+ string(fabricv4.CONNECTIONSTATE_REPROVISIONING),
},
Target: []string{
- string(v4.PROVISIONED_ConnectionState),
+ string(fabricv4.CONNECTIONSTATE_PROVISIONED),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
var state string
- if dbConn.Type_ == "BGP" {
- state = dbConn.RoutingProtocolBgpData.State
- } else if dbConn.Type_ == "DIRECT" {
- state = dbConn.RoutingProtocolDirectData.State
+ switch rpData := dbConn.GetActualInstance().(type) {
+ case *fabricv4.RoutingProtocolBGPData:
+ state = string(rpData.GetState())
+ case *fabricv4.RoutingProtocolDirectData:
+ state = string(rpData.GetState())
}
return dbConn, state, nil
},
@@ -584,16 +556,16 @@ func waitUntilRoutingProtocolIsProvisioned(uuid string, connUuid string, meta in
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.RoutingProtocolData{}
+ var dbConn *fabricv4.RoutingProtocolData
if err == nil {
- dbConn = inter.(v4.RoutingProtocolData)
+ dbConn = inter.(*fabricv4.RoutingProtocolData)
}
return dbConn, err
}
-func WaitUntilRoutingProtocolIsDeprovisioned(uuid string, connUuid string, meta interface{}, ctx context.Context, timeout time.Duration) error {
+func WaitUntilRoutingProtocolIsDeprovisioned(uuid string, connUuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for routing protocol to be deprovisioned, uuid %s", uuid)
/* check if resource is not found */
@@ -602,8 +574,8 @@ func WaitUntilRoutingProtocolIsDeprovisioned(uuid string, connUuid string, meta
strconv.Itoa(404),
},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, resp, _ := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, resp, _ := client.RoutingProtocolsApi.GetConnectionRoutingProtocolByUuid(ctx, uuid, connUuid).Execute()
// fixme: check for error code instead?
// ignore error for Target
return dbConn, strconv.Itoa(resp.StatusCode), nil
@@ -618,19 +590,19 @@ func WaitUntilRoutingProtocolIsDeprovisioned(uuid string, connUuid string, meta
return err
}
-func waitForRoutingProtocolUpdateCompletion(rpChangeUuid string, uuid string, connUuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.RoutingProtocolChangeData, error) {
+func waitForRoutingProtocolUpdateCompletion(rpChangeUuid string, uuid string, connUuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.RoutingProtocolChangeData, error) {
log.Printf("Waiting for routing protocol update to complete, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Target: []string{"COMPLETED"},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolsChangeByUuid(ctx, connUuid, uuid, rpChangeUuid)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.RoutingProtocolsApi.GetConnectionRoutingProtocolsChangeByUuid(ctx, connUuid, uuid, rpChangeUuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
updatableState := ""
- if dbConn.Status == "COMPLETED" {
- updatableState = dbConn.Status
+ if dbConn.GetStatus() == "COMPLETED" {
+ updatableState = dbConn.GetStatus()
}
return dbConn, updatableState, nil
},
@@ -640,203 +612,210 @@ func waitForRoutingProtocolUpdateCompletion(rpChangeUuid string, uuid string, co
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbConn := v4.RoutingProtocolChangeData{}
+ var dbConn *fabricv4.RoutingProtocolChangeData
if err == nil {
- dbConn = inter.(v4.RoutingProtocolChangeData)
+ dbConn = inter.(*fabricv4.RoutingProtocolChangeData)
}
return dbConn, err
}
-func routingProtocolDirectIpv4ToFabric(routingProtocolDirectIpv4Request []interface{}) v4.DirectConnectionIpv4 {
- mappedRpDirectIpv4 := v4.DirectConnectionIpv4{}
- for _, str := range routingProtocolDirectIpv4Request {
- directIpv4Map := str.(map[string]interface{})
- equinixIfaceIp := directIpv4Map["equinix_iface_ip"].(string)
+func routingProtocolDirectIpv4TerraformToGo(routingProtocolDirectIpv4Request []interface{}) fabricv4.DirectConnectionIpv4 {
+ if routingProtocolDirectIpv4Request == nil || len(routingProtocolDirectIpv4Request) == 0 {
+ return fabricv4.DirectConnectionIpv4{}
+ }
+
+ rpDirectIpv4 := fabricv4.DirectConnectionIpv4{}
- mappedRpDirectIpv4 = v4.DirectConnectionIpv4{EquinixIfaceIp: equinixIfaceIp}
+ directIpv4Map := routingProtocolDirectIpv4Request[0].(map[string]interface{})
+ equinixIfaceIp := directIpv4Map["equinix_iface_ip"].(string)
+ if equinixIfaceIp != "" {
+ rpDirectIpv4.SetEquinixIfaceIp(equinixIfaceIp)
}
- return mappedRpDirectIpv4
-}
-func routingProtocolDirectIpv6ToFabric(routingProtocolDirectIpv6Request []interface{}) v4.DirectConnectionIpv6 {
- mappedRpDirectIpv6 := v4.DirectConnectionIpv6{}
- for _, str := range routingProtocolDirectIpv6Request {
- directIpv6Map := str.(map[string]interface{})
- equinixIfaceIp := directIpv6Map["equinix_iface_ip"].(string)
+ return rpDirectIpv4
+}
- mappedRpDirectIpv6 = v4.DirectConnectionIpv6{EquinixIfaceIp: equinixIfaceIp}
+func routingProtocolDirectIpv6TerraformToGo(routingProtocolDirectIpv6Request []interface{}) fabricv4.DirectConnectionIpv6 {
+ if routingProtocolDirectIpv6Request == nil || len(routingProtocolDirectIpv6Request) == 0 {
+ return fabricv4.DirectConnectionIpv6{}
+ }
+ rpDirectIpv6 := fabricv4.DirectConnectionIpv6{}
+ directIpv6Map := routingProtocolDirectIpv6Request[0].(map[string]interface{})
+ equinixIfaceIp := directIpv6Map["equinix_iface_ip"].(string)
+ if equinixIfaceIp != "" {
+ rpDirectIpv6.SetEquinixIfaceIp(equinixIfaceIp)
}
- return mappedRpDirectIpv6
+
+ return rpDirectIpv6
}
-func routingProtocolBgpIpv4ToFabric(routingProtocolBgpIpv4Request []interface{}) v4.BgpConnectionIpv4 {
- mappedRpBgpIpv4 := v4.BgpConnectionIpv4{}
- for _, str := range routingProtocolBgpIpv4Request {
- bgpIpv4Map := str.(map[string]interface{})
- customerPeerIp := bgpIpv4Map["customer_peer_ip"].(string)
- enabled := bgpIpv4Map["enabled"].(bool)
+func routingProtocolBgpIpv4TerraformToGo(routingProtocolBgpIpv4Request []interface{}) fabricv4.BGPConnectionIpv4 {
+ if routingProtocolBgpIpv4Request == nil || len(routingProtocolBgpIpv4Request) == 0 {
+ return fabricv4.BGPConnectionIpv4{}
+ }
- mappedRpBgpIpv4 = v4.BgpConnectionIpv4{CustomerPeerIp: customerPeerIp, Enabled: enabled}
+ rpBgpIpv4 := fabricv4.BGPConnectionIpv4{}
+ bgpIpv4Map := routingProtocolBgpIpv4Request[0].(map[string]interface{})
+ customerPeerIp := bgpIpv4Map["customer_peer_ip"].(string)
+ if customerPeerIp != "" {
+ rpBgpIpv4.SetCustomerPeerIp(customerPeerIp)
}
- return mappedRpBgpIpv4
+ enabled := bgpIpv4Map["enabled"].(bool)
+ rpBgpIpv4.SetEnabled(enabled)
+
+ return rpBgpIpv4
}
-func routingProtocolBgpIpv6ToFabric(routingProtocolBgpIpv6Request []interface{}) v4.BgpConnectionIpv6 {
- mappedRpBgpIpv6 := v4.BgpConnectionIpv6{}
- for _, str := range routingProtocolBgpIpv6Request {
- bgpIpv6Map := str.(map[string]interface{})
- customerPeerIp := bgpIpv6Map["customer_peer_ip"].(string)
- enabled := bgpIpv6Map["enabled"].(bool)
+func routingProtocolBgpIpv6TerraformToGo(routingProtocolBgpIpv6Request []interface{}) fabricv4.BGPConnectionIpv6 {
+ if routingProtocolBgpIpv6Request == nil || len(routingProtocolBgpIpv6Request) == 0 {
+ return fabricv4.BGPConnectionIpv6{}
+ }
- mappedRpBgpIpv6 = v4.BgpConnectionIpv6{CustomerPeerIp: customerPeerIp, Enabled: enabled}
+ rpBgpIpv6 := fabricv4.BGPConnectionIpv6{}
+ bgpIpv6Map := routingProtocolBgpIpv6Request[0].(map[string]interface{})
+ customerPeerIp := bgpIpv6Map["customer_peer_ip"].(string)
+ if customerPeerIp != "" {
+ rpBgpIpv6.SetCustomerPeerIp(customerPeerIp)
}
- return mappedRpBgpIpv6
+ enabled := bgpIpv6Map["enabled"].(bool)
+ rpBgpIpv6.SetEnabled(enabled)
+
+ return rpBgpIpv6
}
-func routingProtocolBfdToFabric(routingProtocolBfdRequest []interface{}) v4.RoutingProtocolBfd {
- mappedRpBfd := v4.RoutingProtocolBfd{}
- for _, str := range routingProtocolBfdRequest {
- rpBfdMap := str.(map[string]interface{})
- bfdEnabled := rpBfdMap["enabled"].(bool)
- bfdInterval := rpBfdMap["interval"].(string)
+func routingProtocolBfdTerraformToGo(routingProtocolBfdRequest []interface{}) fabricv4.RoutingProtocolBFD {
+ if routingProtocolBfdRequest == nil || len(routingProtocolBfdRequest) == 0 {
+ return fabricv4.RoutingProtocolBFD{}
+ }
- mappedRpBfd = v4.RoutingProtocolBfd{Enabled: bfdEnabled, Interval: bfdInterval}
+ rpBfd := fabricv4.RoutingProtocolBFD{}
+ rpBfdMap := routingProtocolBfdRequest[0].(map[string]interface{})
+ bfdEnabled := rpBfdMap["enabled"].(bool)
+ rpBfd.SetEnabled(bfdEnabled)
+ bfdInterval := rpBfdMap["interval"].(string)
+ if bfdInterval != "" {
+ rpBfd.SetInterval(bfdInterval)
}
- return mappedRpBfd
+
+ return rpBfd
}
-func routingProtocolDirectConnectionIpv4ToTerra(routingProtocolDirectIpv4 *v4.DirectConnectionIpv4) *schema.Set {
+func routingProtocolDirectConnectionIpv4GoToTerraform(routingProtocolDirectIpv4 *fabricv4.DirectConnectionIpv4) *schema.Set {
if routingProtocolDirectIpv4 == nil {
return nil
}
- routingProtocolDirectIpv4s := []*v4.DirectConnectionIpv4{routingProtocolDirectIpv4}
- mappedDirectIpv4s := make([]interface{}, len(routingProtocolDirectIpv4s))
- for i, routingProtocolDirectIpv4 := range routingProtocolDirectIpv4s {
- mappedDirectIpv4s[i] = map[string]interface{}{
- "equinix_iface_ip": routingProtocolDirectIpv4.EquinixIfaceIp,
- }
+
+ mappedDirectIpv4 := map[string]interface{}{
+ "equinix_iface_ip": routingProtocolDirectIpv4.GetEquinixIfaceIp(),
}
+
rpDirectIpv4Set := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createDirectConnectionIpv4Sch()}),
- mappedDirectIpv4s,
+ []interface{}{mappedDirectIpv4},
)
return rpDirectIpv4Set
}
-func routingProtocolDirectConnectionIpv6ToTerra(routingProtocolDirectIpv6 *v4.DirectConnectionIpv6) *schema.Set {
+func routingProtocolDirectConnectionIpv6GoToTerraform(routingProtocolDirectIpv6 *fabricv4.DirectConnectionIpv6) *schema.Set {
if routingProtocolDirectIpv6 == nil {
return nil
}
- routingProtocolDirectIpv6s := []*v4.DirectConnectionIpv6{routingProtocolDirectIpv6}
- mappedDirectIpv6s := make([]interface{}, len(routingProtocolDirectIpv6s))
- for i, routingProtocolDirectIpv6 := range routingProtocolDirectIpv6s {
- mappedDirectIpv6s[i] = map[string]interface{}{
- "equinix_iface_ip": routingProtocolDirectIpv6.EquinixIfaceIp,
- }
+
+ mappedDirectIpv6 := map[string]interface{}{
+ "equinix_iface_ip": routingProtocolDirectIpv6.GetEquinixIfaceIp(),
}
+
rpDirectIpv6Set := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createDirectConnectionIpv6Sch()}),
- mappedDirectIpv6s,
+ []interface{}{mappedDirectIpv6},
)
return rpDirectIpv6Set
}
-func routingProtocolBgpConnectionIpv4ToTerra(routingProtocolBgpIpv4 *v4.BgpConnectionIpv4) *schema.Set {
+func routingProtocolBgpConnectionIpv4GoToTerraform(routingProtocolBgpIpv4 *fabricv4.BGPConnectionIpv4) *schema.Set {
if routingProtocolBgpIpv4 == nil {
return nil
}
- routingProtocolBgpIpv4s := []*v4.BgpConnectionIpv4{routingProtocolBgpIpv4}
- mappedBgpIpv4s := make([]interface{}, len(routingProtocolBgpIpv4s))
- for i, routingProtocolBgpIpv4 := range routingProtocolBgpIpv4s {
- mappedBgpIpv4s[i] = map[string]interface{}{
- "customer_peer_ip": routingProtocolBgpIpv4.CustomerPeerIp,
- "equinix_peer_ip": routingProtocolBgpIpv4.EquinixPeerIp,
- "enabled": routingProtocolBgpIpv4.Enabled,
- }
+
+ mappedBgpIpv4 := map[string]interface{}{
+ "customer_peer_ip": routingProtocolBgpIpv4.GetCustomerPeerIp(),
+ "equinix_peer_ip": routingProtocolBgpIpv4.GetEquinixPeerIp(),
+ "enabled": routingProtocolBgpIpv4.GetEnabled(),
}
rpBgpIpv4Set := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createBgpConnectionIpv4Sch()}),
- mappedBgpIpv4s,
+ []interface{}{mappedBgpIpv4},
)
return rpBgpIpv4Set
}
-func routingProtocolBgpConnectionIpv6ToTerra(routingProtocolBgpIpv6 *v4.BgpConnectionIpv6) *schema.Set {
+func routingProtocolBgpConnectionIpv6GoToTerraform(routingProtocolBgpIpv6 *fabricv4.BGPConnectionIpv6) *schema.Set {
if routingProtocolBgpIpv6 == nil {
return nil
}
- routingProtocolBgpIpv6s := []*v4.BgpConnectionIpv6{routingProtocolBgpIpv6}
- mappedBgpIpv6s := make([]interface{}, len(routingProtocolBgpIpv6s))
- for i, routingProtocolBgpIpv6 := range routingProtocolBgpIpv6s {
- mappedBgpIpv6s[i] = map[string]interface{}{
- "customer_peer_ip": routingProtocolBgpIpv6.CustomerPeerIp,
- "equinix_peer_ip": routingProtocolBgpIpv6.EquinixPeerIp,
- "enabled": routingProtocolBgpIpv6.Enabled,
- }
+
+ mappedBgpIpv6 := map[string]interface{}{
+ "customer_peer_ip": routingProtocolBgpIpv6.GetCustomerPeerIp(),
+ "equinix_peer_ip": routingProtocolBgpIpv6.GetEquinixPeerIp(),
+ "enabled": routingProtocolBgpIpv6.GetEnabled(),
}
+
rpBgpIpv6Set := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createBgpConnectionIpv6Sch()}),
- mappedBgpIpv6s,
+ []interface{}{mappedBgpIpv6},
)
return rpBgpIpv6Set
}
-func routingProtocolBfdToTerra(routingProtocolBfd *v4.RoutingProtocolBfd) *schema.Set {
+func routingProtocolBfdGoToTerraform(routingProtocolBfd *fabricv4.RoutingProtocolBFD) *schema.Set {
if routingProtocolBfd == nil {
return nil
}
- routingProtocolBfds := []*v4.RoutingProtocolBfd{routingProtocolBfd}
- mappedRpBfds := make([]interface{}, len(routingProtocolBfds))
- for i, routingProtocolBfd := range routingProtocolBfds {
- mappedRpBfds[i] = map[string]interface{}{
- "enabled": routingProtocolBfd.Enabled,
- "interval": routingProtocolBfd.Interval,
- }
+
+ mappedRpBfd := map[string]interface{}{
+ "enabled": routingProtocolBfd.GetEnabled(),
+ "interval": routingProtocolBfd.GetInterval(),
}
+
rpBfdSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createRoutingProtocolBfdSch()}),
- mappedRpBfds,
+ []interface{}{mappedRpBfd},
)
return rpBfdSet
}
-func routingProtocolOperationToTerra(routingProtocolOperation *v4.RoutingProtocolOperation) *schema.Set {
+func routingProtocolOperationGoToTerraform(routingProtocolOperation *fabricv4.RoutingProtocolOperation) *schema.Set {
if routingProtocolOperation == nil {
return nil
}
- routingProtocolOperations := []*v4.RoutingProtocolOperation{routingProtocolOperation}
- mappedRpOperations := make([]interface{}, len(routingProtocolOperations))
- for _, routingProtocolOperation := range routingProtocolOperations {
- mappedRpOperation := make(map[string]interface{})
- if routingProtocolOperation.Errors != nil {
- mappedRpOperation["errors"] = equinix_fabric_schema.ErrorToTerra(routingProtocolOperation.Errors)
- }
- mappedRpOperations = append(mappedRpOperations, mappedRpOperation)
+ mappedRpOperation := make(map[string]interface{})
+ errors := routingProtocolOperation.GetErrors()
+ if errors != nil {
+ mappedRpOperation["errors"] = equinix_fabric_schema.ErrorGoToTerraform(errors)
}
+
rpOperationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createRoutingProtocolOperationSch()}),
- mappedRpOperations,
+ []interface{}{mappedRpOperation},
)
return rpOperationSet
}
-func routingProtocolChangeToTerra(routingProtocolChange *v4.RoutingProtocolChange) *schema.Set {
+func routingProtocolChangeGoToTerraform(routingProtocolChange *fabricv4.RoutingProtocolChange) *schema.Set {
if routingProtocolChange == nil {
return nil
}
- routingProtocolChanges := []*v4.RoutingProtocolChange{routingProtocolChange}
- mappedRpChanges := make([]interface{}, len(routingProtocolChanges))
- for i, rpChanges := range routingProtocolChanges {
- mappedRpChanges[i] = map[string]interface{}{
- "uuid": rpChanges.Uuid,
- "type": rpChanges.Type_,
- "href": rpChanges.Href,
- }
+
+ mappedRpChange := map[string]interface{}{
+ "uuid": routingProtocolChange.GetUuid(),
+ "type": string(routingProtocolChange.GetType()),
+ "href": routingProtocolChange.GetHref(),
}
+
rpChangeSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: createRoutingProtocolChangeSch()}),
- mappedRpChanges,
+ []interface{}{mappedRpChange},
)
return rpChangeSet
}
diff --git a/equinix/resource_fabric_routing_protocol_acc_test.go b/equinix/resource_fabric_routing_protocol_acc_test.go
index 94dcab672..5c0fb4e9e 100644
--- a/equinix/resource_fabric_routing_protocol_acc_test.go
+++ b/equinix/resource_fabric_routing_protocol_acc_test.go
@@ -3,14 +3,12 @@ package equinix_test
import (
"context"
"fmt"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"testing"
"time"
"github.com/equinix/terraform-provider-equinix/equinix"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
- "github.com/equinix/terraform-provider-equinix/internal/config"
-
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)
@@ -27,11 +25,11 @@ func TestAccFabricCreateRoutingProtocols_PFCR(t *testing.T) {
var portUuid string
if len(ports) > 0 {
- portUuid = ports["pfcr"]["dot1q"][1].Uuid
+ portUuid = ports["pfcr"]["dot1q"][1].GetUuid()
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkRoutingProtocolDelete,
Steps: []resource.TestStep{
@@ -198,12 +196,11 @@ data "equinix_fabric_routing_protocol" "bgp" {
func checkRoutingProtocolDelete(s *terraform.State) error {
ctx := context.Background()
- ctx = context.WithValue(ctx, v4.ContextAccessToken, acceptance.TestAccProvider.Meta().(*config.Config).FabricAuthToken)
for _, rs := range s.RootModule().Resources {
if rs.Type != "equinix_fabric_routing_protocol" {
continue
}
- err := equinix.WaitUntilRoutingProtocolIsDeprovisioned(rs.Primary.ID, rs.Primary.Attributes["connection_uuid"], acceptance.TestAccProvider.Meta(), ctx, 10*time.Minute)
+ err := equinix.WaitUntilRoutingProtocolIsDeprovisioned(rs.Primary.ID, rs.Primary.Attributes["connection_uuid"], acceptance.TestAccProvider.Meta(), &schema.ResourceData{}, ctx, 10*time.Minute)
if err != nil {
return fmt.Errorf("API call failed while waiting for resource deletion")
}
diff --git a/equinix/resource_fabric_service_profile.go b/equinix/resource_fabric_service_profile.go
index ed5791283..9e3eb3cec 100644
--- a/equinix/resource_fabric_service_profile.go
+++ b/equinix/resource_fabric_service_profile.go
@@ -2,8 +2,9 @@ package equinix
import (
"context"
- "errors"
"fmt"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"log"
"strconv"
"strings"
@@ -14,10 +15,8 @@ import (
equinix_fabric_schema "github.com/equinix/terraform-provider-equinix/internal/fabric/schema"
equinix_schema "github.com/equinix/terraform-provider-equinix/internal/schema"
- "github.com/antihax/optional"
"github.com/equinix/terraform-provider-equinix/internal/config"
- 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"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
@@ -31,9 +30,10 @@ func fabricServiceProfileSchema() map[string]*schema.Schema {
Description: "Service Profile URI response attribute",
},
"type": {
- Type: schema.TypeString,
- Required: true,
- Description: "Service profile type - L2_PROFILE, L3_PROFILE, ECIA_PROFILE, ECMC_PROFILE",
+ Type: schema.TypeString,
+ Required: true,
+ ValidateFunc: validation.StringInSlice([]string{"L2_PROFILE", "L3_PROFILE", "ECIA_PROFILE", "ECMC_PROFILE", "IA_PROFILE"}, true),
+ Description: "Service profile type - L2_PROFILE, L3_PROFILE, ECIA_PROFILE, ECMC_PROFILE, IA_PROFILE",
},
"visibility": {
Type: schema.TypeString,
@@ -161,6 +161,12 @@ func fabricServiceProfileSchema() map[string]*schema.Schema {
Schema: equinix_fabric_schema.ChangeLogSch(),
},
},
+ "view_point": {
+ Type: schema.TypeString,
+ Optional: true,
+ Description: "Flips view between buyer and seller representation. Available values : aSide, zSide. Default value : aSide",
+ ValidateFunc: validation.StringInSlice([]string{"aSide", "zSide"}, false),
+ },
}
}
@@ -543,92 +549,100 @@ func resourceFabricServiceProfile() *schema.Resource {
}
func resourceFabricServiceProfileRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- serviceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, d.Id(), nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ serviceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, d.Id()).Execute()
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
}
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(serviceProfile.Uuid)
+ d.SetId(serviceProfile.GetUuid())
return setFabricServiceProfileMap(d, serviceProfile)
}
func resourceFabricServiceProfileCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
createRequest := getServiceProfileRequestPayload(d)
- sp, _, err := client.ServiceProfilesApi.CreateServiceProfile(ctx, createRequest)
+ sp, _, err := client.ServiceProfilesApi.CreateServiceProfile(ctx).ServiceProfileRequest(createRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
- d.SetId(sp.Uuid)
+ d.SetId(sp.GetUuid())
return resourceFabricServiceProfileRead(ctx, d, meta)
}
-func getServiceProfileRequestPayload(d *schema.ResourceData) v4.ServiceProfileRequest {
- spType := v4.ServiceProfileTypeEnum(d.Get("type").(string))
+func getServiceProfileRequestPayload(d *schema.ResourceData) fabricv4.ServiceProfileRequest {
+ createRequest := fabricv4.ServiceProfileRequest{}
- schemaNotifications := d.Get("notifications").([]interface{})
- notifications := equinix_fabric_schema.NotificationsToFabric(schemaNotifications)
+ createRequest.SetName(d.Get("name").(string))
- var tags []string
- if d.Get("tags") != nil {
- schemaTags := d.Get("tags").([]interface{})
- tags = converters.IfArrToStringArr(schemaTags)
+ if description, ok := d.GetOk("description"); ok {
+ createRequest.SetDescription(description.(string))
}
- spVisibility := v4.ServiceProfileVisibilityEnum(d.Get("visibility").(string))
+ spType := fabricv4.ServiceProfileTypeEnum(d.Get("type").(string))
+ createRequest.SetType(spType)
- var spAllowedEmails []string
- if d.Get("allowed_emails") != nil {
- schemaAllowedEmails := d.Get("allowed_emails").([]interface{})
- spAllowedEmails = converters.IfArrToStringArr(schemaAllowedEmails)
+ if schemaNotifications, ok := d.GetOk("notifications"); ok {
+ notifications := equinix_fabric_schema.NotificationsTerraformToGo(schemaNotifications.([]interface{}))
+ createRequest.SetNotifications(notifications)
+ }
+
+ if tagsSchema, ok := d.GetOk("tags"); ok {
+ tags := converters.IfArrToStringArr(tagsSchema.([]interface{}))
+ createRequest.SetTags(tags)
+ }
+
+ if visibility, ok := d.GetOk("visibility"); ok {
+ spVisibility := fabricv4.ServiceProfileVisibilityEnum(visibility.(string))
+ createRequest.SetVisibility(spVisibility)
+ }
+
+ if allowedEmailsSchema, ok := d.GetOk("allowed_emails"); ok {
+ spAllowedEmails := converters.IfArrToStringArr(allowedEmailsSchema.([]interface{}))
+ createRequest.SetAllowedEmails(spAllowedEmails)
}
schemaAccessPointTypeConfigs := d.Get("access_point_type_configs").([]interface{})
- spAccessPointTypeConfigs := accessPointTypeConfigsToFabric(schemaAccessPointTypeConfigs)
-
- schemaCustomFields := d.Get("custom_fields").([]interface{})
- spCustomFields := customFieldsToFabric(schemaCustomFields)
-
- schemaMarketingInfo := d.Get("marketing_info").(*schema.Set).List()
- spMarketingInfo := marketingInfoToFabric(schemaMarketingInfo)
-
- schemaPorts := d.Get("ports").([]interface{})
- spPorts := portsToFabric(schemaPorts)
-
- schemaVirtualDevices := d.Get("virtual_devices").([]interface{})
- spVirtualDevices := virtualDevicesToFabric(schemaVirtualDevices)
-
- schemaMetros := d.Get("metros").([]interface{})
- spMetros := metrosToFabric(schemaMetros)
-
- createRequest := v4.ServiceProfileRequest{
- Name: d.Get("name").(string),
- Type_: &spType,
- Description: d.Get("description").(string),
- Notifications: notifications,
- Tags: &tags,
- Visibility: &spVisibility,
- AllowedEmails: spAllowedEmails,
- AccessPointTypeConfigs: spAccessPointTypeConfigs,
- CustomFields: spCustomFields,
- MarketingInfo: spMarketingInfo,
- Ports: spPorts,
- VirtualDevices: spVirtualDevices,
- Metros: spMetros,
- SelfProfile: d.Get("self_profile").(bool),
+ spAccessPointTypeConfigs := accessPointTypeConfigsTerraformToGo(schemaAccessPointTypeConfigs)
+ createRequest.SetAccessPointTypeConfigs(spAccessPointTypeConfigs)
+
+ if schemaCustomFields, ok := d.GetOk("custom_fields"); ok {
+ spCustomFields := customFieldsTerraformToGo(schemaCustomFields.([]interface{}))
+ createRequest.SetCustomFields(spCustomFields)
+ }
+
+ if schemaMarketingInfo, ok := d.GetOk("marketing_info"); ok {
+ spMarketingInfo := marketingInfoTerraformToGo(schemaMarketingInfo.(*schema.Set).List())
+ createRequest.SetMarketingInfo(spMarketingInfo)
+ }
+
+ if schemaPorts, ok := d.GetOk("ports"); ok {
+ spPorts := portsTerraformToGo(schemaPorts.([]interface{}))
+ createRequest.SetPorts(spPorts)
}
+
+ if schemaVirtualDevices, ok := d.GetOk("virtual_devices"); ok {
+ spVirtualDevices := virtualDevicesTerraformToGo(schemaVirtualDevices.([]interface{}))
+ createRequest.SetVirtualDevices(spVirtualDevices)
+ }
+
+ if schemaMetros, ok := d.GetOk("metros"); ok {
+ spMetros := metrosTerraformToGo(schemaMetros.([]interface{}))
+ createRequest.SetMetros(spMetros)
+ }
+
+ if selfProfile, ok := d.GetOk("self_profile"); ok {
+ createRequest.SetSelfProfile(selfProfile.(bool))
+ }
+
return createRequest
}
func resourceFabricServiceProfileUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
uuid := d.Id()
updateRequest := getServiceProfileRequestPayload(d)
@@ -636,39 +650,38 @@ func resourceFabricServiceProfileUpdate(ctx context.Context, d *schema.ResourceD
updateTimeout := d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
var err error
var eTag int64 = 0
- _, err, eTag = waitForActiveServiceProfileAndPopulateETag(uuid, meta, ctx, updateTimeout)
+ _, err, eTag = waitForActiveServiceProfileAndPopulateETag(uuid, meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
}
return diag.Errorf("Either timed out or errored out while fetching service profile for uuid %s and error %v", uuid, err)
}
-
- _, _, err = client.ServiceProfilesApi.PutServiceProfileByUuid(ctx, updateRequest, strconv.FormatInt(eTag, 10), uuid)
+ _, _, err = client.ServiceProfilesApi.PutServiceProfileByUuid(ctx, uuid).IfMatch(strconv.FormatInt(eTag, 10)).ServiceProfileRequest(updateRequest).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
updateTimeout = d.Timeout(schema.TimeoutUpdate) - 30*time.Second - time.Since(start)
- updatedServiceProfile := v4.ServiceProfile{}
- updatedServiceProfile, err = waitForServiceProfileUpdateCompletion(uuid, meta, ctx, updateTimeout)
+ var updatedServiceProfile *fabricv4.ServiceProfile
+ updatedServiceProfile, err = waitForServiceProfileUpdateCompletion(uuid, meta, d, ctx, updateTimeout)
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
}
return diag.FromErr(fmt.Errorf("errored while waiting for successful service profile update, error %v", err))
}
- d.SetId(updatedServiceProfile.Uuid)
+ d.SetId(updatedServiceProfile.GetUuid())
return setFabricServiceProfileMap(d, updatedServiceProfile)
}
-func waitForServiceProfileUpdateCompletion(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.ServiceProfile, error) {
+func waitForServiceProfileUpdateCompletion(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.ServiceProfile, error) {
log.Printf("Waiting for service profile update to complete, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
Target: []string{"COMPLETED"},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbServiceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbServiceProfile, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
@@ -681,22 +694,22 @@ func waitForServiceProfileUpdateCompletion(uuid string, meta interface{}, ctx co
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbSp := v4.ServiceProfile{}
+ var dbSp *fabricv4.ServiceProfile
if err == nil {
- dbSp = inter.(v4.ServiceProfile)
+ dbSp = inter.(*fabricv4.ServiceProfile)
}
return dbSp, err
}
-func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, ctx context.Context, timeout time.Duration) (v4.ServiceProfile, error, int64) {
+func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) (*fabricv4.ServiceProfile, error, int64) {
log.Printf("Waiting for service profile to be in active state, uuid %s", uuid)
var eTag int64 = 0
stateConf := &retry.StateChangeConf{
- Target: []string{string(v4.ACTIVE_ServiceProfileStateEnum)},
+ Target: []string{string(fabricv4.SERVICEPROFILESTATEENUM_ACTIVE)},
Refresh: func() (interface{}, string, error) {
- client := meta.(*config.Config).FabricClient
- dbServiceProfile, res, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbServiceProfile, res, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid).Execute()
if err != nil {
return nil, "", equinix_errors.FormatFabricError(err)
}
@@ -708,8 +721,8 @@ func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, c
}
updatableState := ""
- if *dbServiceProfile.State == v4.ACTIVE_ServiceProfileStateEnum {
- updatableState = string(*dbServiceProfile.State)
+ if dbServiceProfile.GetState() == fabricv4.SERVICEPROFILESTATEENUM_ACTIVE {
+ updatableState = string(dbServiceProfile.GetState())
}
return dbServiceProfile, updatableState, nil
},
@@ -718,29 +731,29 @@ func waitForActiveServiceProfileAndPopulateETag(uuid string, meta interface{}, c
MinTimeout: 10 * time.Second,
}
inter, err := stateConf.WaitForStateContext(ctx)
- dbServiceProfile := v4.ServiceProfile{}
+ var dbServiceProfile *fabricv4.ServiceProfile
if err == nil {
- dbServiceProfile = inter.(v4.ServiceProfile)
+ dbServiceProfile = inter.(*fabricv4.ServiceProfile)
}
return dbServiceProfile, err, eTag
}
func resourceFabricServiceProfileDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
diags := diag.Diagnostics{}
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
uuid := d.Id()
if uuid == "" {
return diag.Errorf("No uuid found for Service Profile Deletion %v ", uuid)
}
+
start := time.Now()
- _, _, err := client.ServiceProfilesApi.DeleteServiceProfileByUuid(ctx, uuid)
+ _, _, err := client.ServiceProfilesApi.DeleteServiceProfileByUuid(ctx, uuid).Execute()
if err != nil {
return diag.FromErr(equinix_errors.FormatFabricError(err))
}
deleteTimeout := d.Timeout(schema.TimeoutDelete) - 30*time.Second - time.Since(start)
- waitErr := WaitAndCheckServiceProfileDeleted(uuid, client, ctx, deleteTimeout)
+ waitErr := WaitAndCheckServiceProfileDeleted(uuid, meta, d, ctx, deleteTimeout)
if waitErr != nil {
return diag.Errorf("Error while waiting for Service Profile deletion: %v", waitErr)
}
@@ -748,18 +761,19 @@ func resourceFabricServiceProfileDelete(ctx context.Context, d *schema.ResourceD
return diags
}
-func WaitAndCheckServiceProfileDeleted(uuid string, client *v4.APIClient, ctx context.Context, timeout time.Duration) error {
+func WaitAndCheckServiceProfileDeleted(uuid string, meta interface{}, d *schema.ResourceData, ctx context.Context, timeout time.Duration) error {
log.Printf("Waiting for service profile to be in deleted, uuid %s", uuid)
stateConf := &retry.StateChangeConf{
- Target: []string{string(v4.DELETED_ServiceProfileStateEnum)},
+ Target: []string{string(fabricv4.SERVICEPROFILESTATEENUM_DELETED)},
Refresh: func() (interface{}, string, error) {
- dbConn, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid, nil)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ dbConn, _, err := client.ServiceProfilesApi.GetServiceProfileByUuid(ctx, uuid).Execute()
if err != nil {
return "", "", equinix_errors.FormatFabricError(err)
}
updatableState := ""
- if *dbConn.State == v4.DELETED_ServiceProfileStateEnum {
- updatableState = string(*dbConn.State)
+ if dbConn.GetState() == fabricv4.SERVICEPROFILESTATEENUM_DELETED {
+ updatableState = string(dbConn.GetState())
}
return dbConn, updatableState, nil
},
@@ -771,7 +785,7 @@ func WaitAndCheckServiceProfileDeleted(uuid string, client *v4.APIClient, ctx co
return err
}
-func setFabricServiceProfilesListMap(d *schema.ResourceData, spl v4.ServiceProfiles) diag.Diagnostics {
+func setFabricServiceProfilesListMap(d *schema.ResourceData, spl *fabricv4.ServiceProfiles) diag.Diagnostics {
diags := diag.Diagnostics{}
mappedServiceProfiles := make([]map[string]interface{}, len(spl.Data))
if spl.Data != nil {
@@ -790,70 +804,66 @@ func setFabricServiceProfilesListMap(d *schema.ResourceData, spl v4.ServiceProfi
return diags
}
-func setFabricServiceProfileMap(d *schema.ResourceData, sp v4.ServiceProfile) diag.Diagnostics {
+func setFabricServiceProfileMap(d *schema.ResourceData, sp *fabricv4.ServiceProfile) diag.Diagnostics {
diags := diag.Diagnostics{}
- err := equinix_schema.SetMap(d, fabricServiceProfileMap(&sp))
+ err := equinix_schema.SetMap(d, fabricServiceProfileMap(sp))
if err != nil {
return diag.FromErr(err)
}
return diags
}
-func fabricServiceProfileMap(serviceProfile *v4.ServiceProfile) map[string]interface{} {
+func fabricServiceProfileMap(serviceProfile *fabricv4.ServiceProfile) map[string]interface{} {
if serviceProfile == nil {
return nil
}
+
+ marketingInfo := serviceProfile.GetMarketingInfo()
+ account := serviceProfile.GetAccount()
+ project := serviceProfile.GetProject()
+ changeLog := serviceProfile.GetChangeLog()
return map[string]interface{}{
- "href": serviceProfile.Href,
- "type": serviceProfile.Type_,
- "name": serviceProfile.Name,
- "uuid": serviceProfile.Uuid,
- "description": serviceProfile.Description,
- "notifications": equinix_fabric_schema.NotificationsToTerra(serviceProfile.Notifications),
- "tags": tagsFabricSpToTerra(serviceProfile.Tags),
- "visibility": serviceProfile.Visibility,
- "access_point_type_configs": accessPointTypeConfigToTerra(serviceProfile.AccessPointTypeConfigs),
- "custom_fields": customFieldFabricSpToTerra(serviceProfile.CustomFields),
- "marketing_info": marketingInfoMappingToTerra(serviceProfile.MarketingInfo),
- "ports": accessPointColoFabricSpToTerra(serviceProfile.Ports),
- "allowed_emails": allowedEmailsFabricSpToTerra(serviceProfile.AllowedEmails),
- "metros": serviceMetroFabricSpToTerra(serviceProfile.Metros),
- "self_profile": serviceProfile.SelfProfile,
- "state": serviceProfile.State,
- "account": equinix_fabric_schema.AccountToTerra(serviceProfile.Account),
- "project": equinix_fabric_schema.ProjectToTerra(serviceProfile.Project),
- "change_log": equinix_fabric_schema.ChangeLogToTerra(serviceProfile.ChangeLog),
+ "href": serviceProfile.GetHref(),
+ "type": string(serviceProfile.GetType()),
+ "name": serviceProfile.GetName(),
+ "uuid": serviceProfile.GetUuid(),
+ "description": serviceProfile.GetDescription(),
+ "notifications": equinix_fabric_schema.NotificationsGoToTerraform(serviceProfile.GetNotifications()),
+ "tags": tagsGoToTerraform(serviceProfile.GetTags()),
+ "visibility": string(serviceProfile.GetVisibility()),
+ "access_point_type_configs": accessPointTypeConfigGoToTerraform(serviceProfile.GetAccessPointTypeConfigs()),
+ "custom_fields": customFieldGoToTerraform(serviceProfile.GetCustomFields()),
+ "marketing_info": marketingInfoGoToTerraform(&marketingInfo),
+ "ports": serviceProfileAccessPointColoGoToTerraform(serviceProfile.GetPorts()),
+ "allowed_emails": allowedEmailsGoToTerraform(serviceProfile.GetAllowedEmails()),
+ "metros": serviceMetroGoToTerraform(serviceProfile.GetMetros()),
+ "self_profile": serviceProfile.GetSelfProfile(),
+ "state": string(serviceProfile.GetState()),
+ "account": equinix_fabric_schema.AccountGoToTerraform(&account),
+ "project": equinix_fabric_schema.ProjectGoToTerraform(&project),
+ "change_log": equinix_fabric_schema.ChangeLogGoToTerraform(&changeLog),
}
}
func resourceServiceProfilesSearchRequest(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
- client := meta.(*config.Config).FabricClient
- ctx = context.WithValue(ctx, v4.ContextAccessToken, meta.(*config.Config).FabricAuthToken)
- schemaFilter := d.Get("filter").(*schema.Set).List()
- filter := serviceProfilesSearchFilterRequestToFabric(schemaFilter)
- var serviceProfileFlt v4.ServiceProfileFilter // Cast ServiceProfile search expression struct type to interface
- serviceProfileFlt = filter
- schemaSort := d.Get("sort").([]interface{})
- sort := serviceProfilesSearchSortRequestToFabric(schemaSort)
- schemaViewPoint := d.Get("view_point").(string)
+ client := meta.(*config.Config).NewFabricClientForSDK(d)
+ serviceProfilesSearchRequest := fabricv4.ServiceProfileSearchRequest{}
- if schemaViewPoint != "" && schemaViewPoint != string(v4.A_SIDE_ViewPoint) && schemaViewPoint != string(v4.Z_SIDE_ViewPoint) {
- return diag.FromErr(errors.New("view_point can only be set to aSide or zSide. Omitting it will default to aSide"))
- }
+ schemaFilter := d.Get("filter").(*schema.Set).List()
+ filter := serviceProfilesSearchFilterRequestTerraformToGo(schemaFilter)
+ serviceProfilesSearchRequest.SetFilter(filter)
- viewPoint := &v4.ServiceProfilesApiSearchServiceProfilesOpts{
- ViewPoint: optional.NewString(schemaViewPoint),
+ if schemaSort, ok := d.GetOk("sort"); ok {
+ sort := serviceProfilesSearchSortRequestTerraformToGo(schemaSort.([]interface{}))
+ serviceProfilesSearchRequest.SetSort(sort)
}
- if schemaViewPoint == "" {
- viewPoint = nil
+ viewPoint := fabricv4.GetServiceProfilesViewPointParameter("aSide")
+ if viewPointSchema, ok := d.GetOk("view_point"); ok {
+ viewPoint = fabricv4.GetServiceProfilesViewPointParameter(viewPointSchema.(string))
}
- createServiceProfilesSearchRequest := v4.ServiceProfileSearchRequest{
- Filter: &serviceProfileFlt,
- Sort: sort,
- }
- serviceProfiles, _, err := client.ServiceProfilesApi.SearchServiceProfiles(ctx, createServiceProfilesSearchRequest, viewPoint)
+ serviceProfiles, _, err := client.ServiceProfilesApi.SearchServiceProfiles(ctx).ViewPoint(viewPoint).ServiceProfileSearchRequest(serviceProfilesSearchRequest).Execute()
if err != nil {
if !strings.Contains(err.Error(), "500") {
d.SetId("")
@@ -865,50 +875,50 @@ func resourceServiceProfilesSearchRequest(ctx context.Context, d *schema.Resourc
error := fmt.Errorf("incorrect # of records are found for the service profile search criteria - %d , please change the criteria", len(serviceProfiles.Data))
return diag.FromErr(error)
}
- d.SetId(serviceProfiles.Data[0].Uuid)
+ d.SetId(serviceProfiles.Data[0].GetUuid())
return setFabricServiceProfilesListMap(d, serviceProfiles)
}
-func customFieldFabricSpToTerra(customFields []v4.CustomField) []interface{} {
+func customFieldGoToTerraform(customFields []fabricv4.CustomField) []interface{} {
if customFields == nil {
return nil
}
mappedCustomFields := make([]interface{}, len(customFields))
for index, customField := range customFields {
mappedCustomFields[index] = map[string]interface{}{
- "label": customField.Label,
- "description": customField.Description,
- "required": customField.Required,
- "data_type": customField.DataType,
- "options": customField.Options,
+ "label": customField.GetLabel(),
+ "description": customField.GetDescription(),
+ "required": customField.GetRequired(),
+ "data_type": customField.GetDataType(),
+ "options": customField.GetOptions(),
}
}
return mappedCustomFields
}
-func processStepFabricSpToTerra(processSteps []v4.ProcessStep) []interface{} {
+func processStepsGoToTerraform(processSteps []fabricv4.ProcessStep) []interface{} {
if processSteps == nil {
return nil
}
mappedProcessSteps := make([]interface{}, len(processSteps))
for index, processStep := range processSteps {
mappedProcessSteps[index] = map[string]interface{}{
- "title": processStep.Title,
- "sub_title": processStep.SubTitle,
- "description": processStep.Description,
+ "title": processStep.GetTitle(),
+ "sub_title": processStep.GetSubTitle(),
+ "description": processStep.GetDescription(),
}
}
return mappedProcessSteps
}
-func marketingInfoMappingToTerra(mkinfo *v4.MarketingInfo) *schema.Set {
+func marketingInfoGoToTerraform(mkinfo *fabricv4.MarketingInfo) *schema.Set {
if mkinfo == nil {
return nil
}
mappedMkInfo := make(map[string]interface{})
- mappedMkInfo["logo"] = mkinfo.Logo
- mappedMkInfo["promotion"] = mkinfo.Promotion
- processSteps := processStepFabricSpToTerra(mkinfo.ProcessSteps)
+ mappedMkInfo["logo"] = mkinfo.GetLogo()
+ mappedMkInfo["promotion"] = mkinfo.GetPromotion()
+ processSteps := processStepsGoToTerraform(mkinfo.GetProcessSteps())
if processSteps != nil {
mappedMkInfo["process_step"] = processSteps
}
@@ -919,347 +929,424 @@ func marketingInfoMappingToTerra(mkinfo *v4.MarketingInfo) *schema.Set {
return marketingInfoSet
}
-func accessPointColoFabricSpToTerra(accessPointColos []v4.ServiceProfileAccessPointColo) []interface{} {
+func serviceProfileAccessPointColoGoToTerraform(accessPointColos []fabricv4.ServiceProfileAccessPointCOLO) []interface{} {
if accessPointColos == nil {
return nil
}
mappedAccessPointColos := make([]interface{}, len(accessPointColos))
for index, accessPointColo := range accessPointColos {
+ location := accessPointColo.GetLocation()
mappedAccessPointColos[index] = map[string]interface{}{
- "type": accessPointColo.Type_,
- "uuid": accessPointColo.Uuid,
- "location": equinix_fabric_schema.LocationToTerra(accessPointColo.Location),
- "seller_region": accessPointColo.SellerRegion,
- "seller_region_description": accessPointColo.SellerRegionDescription,
- "cross_connect_id": accessPointColo.CrossConnectId,
+ "type": string(accessPointColo.GetType()),
+ "uuid": accessPointColo.GetUuid(),
+ "location": equinix_fabric_schema.LocationGoToTerraform(&location),
+ "seller_region": accessPointColo.GetSellerRegion(),
+ "seller_region_description": accessPointColo.GetSellerRegionDescription(),
+ "cross_connect_id": accessPointColo.GetCrossConnectId(),
}
}
return mappedAccessPointColos
}
-func serviceMetroFabricSpToTerra(serviceMetros []v4.ServiceMetro) []interface{} {
+func serviceMetroGoToTerraform(serviceMetros []fabricv4.ServiceMetro) []interface{} {
if serviceMetros == nil {
return nil
}
mappedServiceMetros := make([]interface{}, len(serviceMetros))
for index, serviceMetro := range serviceMetros {
mappedServiceMetros[index] = map[string]interface{}{
- "code": serviceMetro.Code,
- "name": serviceMetro.Name,
- "ibxs": serviceMetro.Ibxs,
- "in_trail": serviceMetro.InTrail,
- "display_name": serviceMetro.DisplayName,
- "seller_regions": serviceMetro.SellerRegions,
+ "code": serviceMetro.GetCode(),
+ "name": serviceMetro.GetName(),
+ "ibxs": serviceMetro.GetIbxs(),
+ "in_trail": serviceMetro.GetInTrail(),
+ "display_name": serviceMetro.GetDisplayName(),
+ "seller_regions": serviceMetro.GetSellerRegions(),
}
}
return mappedServiceMetros
}
-func tagsFabricSpToTerra(tags *[]string) []interface{} {
+func tagsGoToTerraform(tags []string) []interface{} {
if tags == nil {
return nil
}
- mappedTags := make([]interface{}, len(*tags))
- for index, tag := range *tags {
+ mappedTags := make([]interface{}, len(tags))
+ for index, tag := range tags {
mappedTags[index] = tag
}
return mappedTags
}
-func allowedEmailsFabricSpToTerra(allowedemails []string) []interface{} {
- if allowedemails == nil {
+func allowedEmailsGoToTerraform(allowedEmails []string) []interface{} {
+ if allowedEmails == nil {
return nil
}
- mappedEmails := make([]interface{}, len(allowedemails))
- for index, email := range allowedemails {
+ mappedEmails := make([]interface{}, len(allowedEmails))
+ for index, email := range allowedEmails {
mappedEmails[index] = email
}
return mappedEmails
}
-func accessPointTypeConfigsToFabric(schemaAccessPointTypeConfigs []interface{}) []v4.ServiceProfileAccessPointType {
+func accessPointTypeConfigsTerraformToGo(schemaAccessPointTypeConfigs []interface{}) []fabricv4.ServiceProfileAccessPointType {
if schemaAccessPointTypeConfigs == nil {
- return []v4.ServiceProfileAccessPointType{}
- }
- var accessPointTypeConfigs []v4.ServiceProfileAccessPointType
- for _, accessPoint := range schemaAccessPointTypeConfigs {
- spType := v4.ServiceProfileAccessPointTypeEnum(accessPoint.(map[string]interface{})["type"].(string))
- spConnectionRedundancyRequired := accessPoint.(map[string]interface{})["connection_redundancy_required"].(bool)
- spAllowBandwidthAutoApproval := accessPoint.(map[string]interface{})["allow_bandwidth_auto_approval"].(bool)
- spAllowRemoteConnections := accessPoint.(map[string]interface{})["allow_remote_connections"].(bool)
- spConnectionLabel := accessPoint.(map[string]interface{})["connection_label"].(string)
- spEnableAutoGenerateServiceKey := accessPoint.(map[string]interface{})["enable_auto_generate_service_key"].(bool)
- spBandwidthAlertThreshold := accessPoint.(map[string]interface{})["bandwidth_alert_threshold"].(float64)
- spAllowCustomBandwidth := accessPoint.(map[string]interface{})["allow_custom_bandwidth"].(bool)
-
- var spApiConfig *v4.ApiConfig
- if accessPoint.(map[string]interface{})["api_config"] != nil {
- apiConfig := accessPoint.(map[string]interface{})["api_config"].(interface{}).(*schema.Set).List()
- spApiConfig = apiConfigToFabric(apiConfig)
+ return nil
+ }
+ accessPointTypeConfigs := make([]fabricv4.ServiceProfileAccessPointType, len(schemaAccessPointTypeConfigs))
+ for index, accessPoint := range schemaAccessPointTypeConfigs {
+ apMap := accessPoint.(map[string]interface{})
+ accessPointTypeCOLO := fabricv4.ServiceProfileAccessPointTypeCOLO{}
+
+ spType := fabricv4.ServiceProfileAccessPointTypeEnum(apMap["type"].(string))
+ accessPointTypeCOLO.SetType(spType)
+
+ spConnectionRedundancyRequired := apMap["connection_redundancy_required"].(bool)
+ accessPointTypeCOLO.SetConnectionRedundancyRequired(spConnectionRedundancyRequired)
+
+ spAllowBandwidthAutoApproval := apMap["allow_bandwidth_auto_approval"].(bool)
+ accessPointTypeCOLO.SetAllowBandwidthAutoApproval(spAllowBandwidthAutoApproval)
+
+ spAllowRemoteConnections := apMap["allow_remote_connections"].(bool)
+ accessPointTypeCOLO.SetAllowRemoteConnections(spAllowRemoteConnections)
+
+ spConnectionLabel := apMap["connection_label"].(string)
+ accessPointTypeCOLO.SetConnectionLabel(spConnectionLabel)
+
+ spEnableAutoGenerateServiceKey := apMap["enable_auto_generate_service_key"].(bool)
+ accessPointTypeCOLO.SetEnableAutoGenerateServiceKey(spEnableAutoGenerateServiceKey)
+
+ spBandwidthAlertThreshold := float32(apMap["bandwidth_alert_threshold"].(float64))
+ accessPointTypeCOLO.SetBandwidthAlertThreshold(spBandwidthAlertThreshold)
+
+ spAllowCustomBandwidth := apMap["allow_custom_bandwidth"].(bool)
+ accessPointTypeCOLO.SetAllowCustomBandwidth(spAllowCustomBandwidth)
+
+ if apMap["api_config"] != nil {
+ apiConfig := apMap["api_config"].(*schema.Set).List()
+ spApiConfig := apiConfigTerraformToGo(apiConfig)
+ accessPointTypeCOLO.SetApiConfig(spApiConfig)
}
- var spAuthenticationKey *v4.AuthenticationKey
- if accessPoint.(map[string]interface{})["authentication_key"] != nil {
- authenticationKey := accessPoint.(map[string]interface{})["authentication_key"].(interface{}).(*schema.Set).List()
- spAuthenticationKey = authenticationKeyToFabric(authenticationKey)
+ if apMap["authentication_key"] != nil {
+ authenticationKey := apMap["authentication_key"].(*schema.Set).List()
+ spAuthenticationKey := authenticationKeyTerraformToGo(authenticationKey)
+ accessPointTypeCOLO.SetAuthenticationKey(spAuthenticationKey)
}
- supportedBandwidthsRaw := accessPoint.(map[string]interface{})["supported_bandwidths"].([]interface{})
+ supportedBandwidthsRaw := apMap["supported_bandwidths"].([]interface{})
spSupportedBandwidths := converters.ListToInt32List(supportedBandwidthsRaw)
+ accessPointTypeCOLO.SetSupportedBandwidths(spSupportedBandwidths)
+
+ accessPointType := fabricv4.ServiceProfileAccessPointTypeCOLOAsServiceProfileAccessPointType(&accessPointTypeCOLO)
- accessPointTypeConfigs = append(accessPointTypeConfigs, v4.ServiceProfileAccessPointType{
- Type_: &spType,
- ConnectionRedundancyRequired: spConnectionRedundancyRequired,
- AllowBandwidthAutoApproval: spAllowBandwidthAutoApproval,
- AllowRemoteConnections: spAllowRemoteConnections,
- ConnectionLabel: spConnectionLabel,
- EnableAutoGenerateServiceKey: spEnableAutoGenerateServiceKey,
- BandwidthAlertThreshold: spBandwidthAlertThreshold,
- AllowCustomBandwidth: spAllowCustomBandwidth,
- ApiConfig: spApiConfig,
- AuthenticationKey: spAuthenticationKey,
- SupportedBandwidths: &spSupportedBandwidths,
- })
+ accessPointTypeConfigs[index] = accessPointType
}
return accessPointTypeConfigs
}
-func accessPointTypeConfigToTerra(spAccessPointTypes []v4.ServiceProfileAccessPointType) []interface{} {
+func accessPointTypeConfigGoToTerraform(spAccessPointTypes []fabricv4.ServiceProfileAccessPointType) []interface{} {
mappedSpAccessPointTypes := make([]interface{}, len(spAccessPointTypes))
for index, spAccessPointType := range spAccessPointTypes {
+ spAccessPointType := spAccessPointType.GetActualInstance().(*fabricv4.ServiceProfileAccessPointTypeCOLO)
+ apiConfig := spAccessPointType.GetApiConfig()
+ authKey := spAccessPointType.GetAuthenticationKey()
mappedSpAccessPointTypes[index] = map[string]interface{}{
- "type": string(*spAccessPointType.Type_),
- "uuid": spAccessPointType.Uuid,
- "allow_remote_connections": spAccessPointType.AllowRemoteConnections,
- "allow_custom_bandwidth": spAccessPointType.AllowCustomBandwidth,
- "allow_bandwidth_auto_approval": spAccessPointType.AllowBandwidthAutoApproval,
- "enable_auto_generate_service_key": spAccessPointType.EnableAutoGenerateServiceKey,
- "connection_redundancy_required": spAccessPointType.ConnectionRedundancyRequired,
- "connection_label": spAccessPointType.ConnectionLabel,
- "api_config": apiConfigToTerra(spAccessPointType.ApiConfig),
- "authentication_key": authenticationKeyToTerra(spAccessPointType.AuthenticationKey),
- "supported_bandwidths": supportedBandwidthsToTerra(spAccessPointType.SupportedBandwidths),
+ "type": string(spAccessPointType.Type),
+ "uuid": spAccessPointType.GetUuid(),
+ "allow_remote_connections": spAccessPointType.GetAllowRemoteConnections(),
+ "allow_custom_bandwidth": spAccessPointType.GetAllowCustomBandwidth(),
+ "allow_bandwidth_auto_approval": spAccessPointType.GetAllowBandwidthAutoApproval(),
+ "enable_auto_generate_service_key": spAccessPointType.GetEnableAutoGenerateServiceKey(),
+ "connection_redundancy_required": spAccessPointType.GetConnectionRedundancyRequired(),
+ "connection_label": spAccessPointType.GetConnectionLabel(),
+ "api_config": apiConfigGoToTerraform(&apiConfig),
+ "authentication_key": authenticationKeyGoToTerraform(&authKey),
+ "supported_bandwidths": supportedBandwidthsGoToTerraform(spAccessPointType.GetSupportedBandwidths()),
}
}
return mappedSpAccessPointTypes
}
-func apiConfigToFabric(apiConfigs []interface{}) *v4.ApiConfig {
- if apiConfigs == nil {
+func apiConfigGoToTerraform(apiConfig *fabricv4.ApiConfig) *schema.Set {
+
+ mappedApiConfig := make(map[string]interface{})
+ mappedApiConfig["api_available"] = apiConfig.GetApiAvailable()
+ mappedApiConfig["equinix_managed_vlan"] = apiConfig.GetEquinixManagedVlan()
+ mappedApiConfig["bandwidth_from_api"] = apiConfig.GetBandwidthFromApi()
+ mappedApiConfig["integration_id"] = apiConfig.GetIntegrationId()
+ mappedApiConfig["equinix_managed_port"] = apiConfig.GetEquinixManagedPort()
+
+ apiConfigSet := schema.NewSet(
+ schema.HashResource(&schema.Resource{Schema: createApiConfigSch()}),
+ []interface{}{mappedApiConfig})
+ return apiConfigSet
+}
+
+func authenticationKeyGoToTerraform(authenticationKey *fabricv4.AuthenticationKey) *schema.Set {
+ mappedAuthenticationKey := make(map[string]interface{})
+ mappedAuthenticationKey["required"] = authenticationKey.GetRequired()
+ mappedAuthenticationKey["label"] = authenticationKey.GetLabel()
+ mappedAuthenticationKey["description"] = authenticationKey.GetDescription()
+
+ apiConfigSet := schema.NewSet(
+ schema.HashResource(&schema.Resource{Schema: createAuthenticationKeySch()}),
+ []interface{}{mappedAuthenticationKey})
+ return apiConfigSet
+}
+
+func supportedBandwidthsGoToTerraform(supportedBandwidths []int32) []interface{} {
+ if supportedBandwidths == nil {
return nil
}
- var apiConfigRes *v4.ApiConfig
- for _, apiConfig := range apiConfigs {
- psApiAvailable := apiConfig.(map[string]interface{})["api_available"].(interface{}).(bool)
- psEquinixManagedVlan := apiConfig.(map[string]interface{})["equinix_managed_vlan"].(interface{}).(bool)
- psBandwidthFromApi := apiConfig.(map[string]interface{})["bandwidth_from_api"].(interface{}).(bool)
- psIntegrationId := apiConfig.(map[string]interface{})["integration_id"].(interface{}).(string)
- psEquinixManagedPort := apiConfig.(map[string]interface{})["equinix_managed_port"].(interface{}).(bool)
- apiConfigRes = &v4.ApiConfig{
- ApiAvailable: psApiAvailable,
- EquinixManagedVlan: psEquinixManagedVlan,
- BandwidthFromApi: psBandwidthFromApi,
- IntegrationId: psIntegrationId,
- EquinixManagedPort: psEquinixManagedPort,
- }
+ mappedSupportedBandwidths := make([]interface{}, len(supportedBandwidths))
+ for index, bandwidth := range supportedBandwidths {
+ mappedSupportedBandwidths[index] = int(bandwidth)
}
- return apiConfigRes
+ return mappedSupportedBandwidths
}
-func authenticationKeyToFabric(authenticationKeys []interface{}) *v4.AuthenticationKey {
+func apiConfigTerraformToGo(apiConfigs []interface{}) fabricv4.ApiConfig {
+ if apiConfigs == nil {
+ return fabricv4.ApiConfig{}
+ }
+ apiConfig := fabricv4.ApiConfig{}
+ apiConfigMap := apiConfigs[0].(map[string]interface{})
+ apiAvailable := apiConfigMap["api_available"].(bool)
+ equinixManagedVlan := apiConfigMap["equinix_managed_vlan"].(bool)
+ bandwidthFromApi := apiConfigMap["bandwidth_from_api"].(bool)
+ integrationId := apiConfigMap["integration_id"].(string)
+ equinixManagedPort := apiConfigMap["equinix_managed_port"].(bool)
+ apiConfig.SetApiAvailable(apiAvailable)
+ apiConfig.SetEquinixManagedVlan(equinixManagedVlan)
+ apiConfig.SetBandwidthFromApi(bandwidthFromApi)
+ apiConfig.SetIntegrationId(integrationId)
+ apiConfig.SetEquinixManagedPort(equinixManagedPort)
+
+ return apiConfig
+}
+
+func authenticationKeyTerraformToGo(authenticationKeys []interface{}) fabricv4.AuthenticationKey {
if authenticationKeys == nil {
- return nil
- }
- var authenticationKeyRes *v4.AuthenticationKey
- for _, authenticationKey := range authenticationKeys {
- psRequired := authenticationKey.(map[string]interface{})["required"].(interface{}).(bool)
- psLabel := authenticationKey.(map[string]interface{})["label"].(interface{}).(string)
- psDescription := authenticationKey.(map[string]interface{})["description"].(interface{}).(string)
- authenticationKeyRes = &v4.AuthenticationKey{
- Required: psRequired,
- Label: psLabel,
- Description: psDescription,
- }
+ return fabricv4.AuthenticationKey{}
}
+ authenticationKeyRes := fabricv4.AuthenticationKey{}
+ authKeyMap := authenticationKeys[0].(map[string]interface{})
+ required := authKeyMap["required"].(bool)
+ label := authKeyMap["label"].(string)
+ description := authKeyMap["description"].(string)
+
+ authenticationKeyRes.SetRequired(required)
+ authenticationKeyRes.SetLabel(label)
+ authenticationKeyRes.SetDescription(description)
+
return authenticationKeyRes
}
-func customFieldsToFabric(schemaCustomField []interface{}) []v4.CustomField {
+func customFieldsTerraformToGo(schemaCustomField []interface{}) []fabricv4.CustomField {
if schemaCustomField == nil {
- return []v4.CustomField{}
- }
- var customFields []v4.CustomField
- for _, customField := range schemaCustomField {
- cfLabel := customField.(map[string]interface{})["label"].(string)
- cfDescription := customField.(map[string]interface{})["description"].(string)
- cfRequired := customField.(map[string]interface{})["required"].(bool)
- cfDataType := customField.(map[string]interface{})["data_type"].(string)
- optionsRaw := customField.(map[string]interface{})["options"].([]interface{})
+ return nil
+ }
+ customFields := make([]fabricv4.CustomField, len(schemaCustomField))
+ for index, customField := range schemaCustomField {
+ cfMap := customField.(map[string]interface{})
+ cfLabel := cfMap["label"].(string)
+ cfDescription := cfMap["description"].(string)
+ cfRequired := cfMap["required"].(bool)
+ cfDataType := fabricv4.CustomFieldDataType(cfMap["data_type"].(string))
+ optionsRaw := cfMap["options"].([]interface{})
cfOptions := converters.IfArrToStringArr(optionsRaw)
- cfCaptureInEmail := customField.(map[string]interface{})["capture_in_email"].(bool)
- customFields = append(customFields, v4.CustomField{
- Label: cfLabel,
- Description: cfDescription,
- Required: cfRequired,
- DataType: cfDataType,
- Options: cfOptions,
- CaptureInEmail: cfCaptureInEmail,
- })
+ cfCaptureInEmail := cfMap["capture_in_email"].(bool)
+ mappedCustomField := fabricv4.CustomField{}
+ mappedCustomField.SetLabel(cfLabel)
+ mappedCustomField.SetDescription(cfDescription)
+ mappedCustomField.SetRequired(cfRequired)
+ mappedCustomField.SetDataType(cfDataType)
+ mappedCustomField.SetOptions(cfOptions)
+ mappedCustomField.SetCaptureInEmail(cfCaptureInEmail)
+
+ customFields[index] = mappedCustomField
}
return customFields
}
-func marketingInfoToFabric(schemaMarketingInfos []interface{}) *v4.MarketingInfo {
+func marketingInfoTerraformToGo(schemaMarketingInfos []interface{}) fabricv4.MarketingInfo {
if schemaMarketingInfos == nil {
- return nil
+ return fabricv4.MarketingInfo{}
+ }
+ marketingInfo := fabricv4.MarketingInfo{}
+ marketingInfoMap := schemaMarketingInfos[0].(map[string]interface{})
+ miLogo := marketingInfoMap["logo"].(string)
+ if miLogo != "" {
+ marketingInfo.SetLogo(miLogo)
}
- marketingInfoRes := v4.MarketingInfo{}
- for _, marketingInfo := range schemaMarketingInfos {
- miLogo := marketingInfo.(map[string]interface{})["logo"].(string)
- miPromotion := marketingInfo.(map[string]interface{})["promotion"].(bool)
- var miProcessSteps []v4.ProcessStep
- if marketingInfo.(map[string]interface{})["process_steps"] != nil {
- processStepsList := marketingInfo.(map[string]interface{})["process_steps"].([]interface{})
- miProcessSteps = processStepToFabric(processStepsList)
- }
+ miPromotion := marketingInfoMap["promotion"].(bool)
+ marketingInfo.SetPromotion(miPromotion)
- marketingInfoRes = v4.MarketingInfo{
- Logo: miLogo,
- Promotion: miPromotion,
- ProcessSteps: miProcessSteps,
- }
+ var miProcessSteps []fabricv4.ProcessStep
+ if marketingInfoMap["process_steps"] != nil {
+ processStepsList := marketingInfoMap["process_steps"].([]interface{})
+ miProcessSteps = processStepTerraformToGo(processStepsList)
+ marketingInfo.SetProcessSteps(miProcessSteps)
}
- return &marketingInfoRes
+
+ return marketingInfo
}
-func processStepToFabric(processSteps []interface{}) []v4.ProcessStep {
+func processStepTerraformToGo(processSteps []interface{}) []fabricv4.ProcessStep {
if processSteps == nil {
return nil
}
- processStepRes := make([]v4.ProcessStep, len(processSteps))
+ processStepRes := make([]fabricv4.ProcessStep, len(processSteps))
for index, processStep := range processSteps {
- psTitle := processStep.(map[string]interface{})["title"].(interface{}).(string)
- psSubTitle := processStep.(map[string]interface{})["sub_title"].(interface{}).(string)
- psDescription := processStep.(map[string]interface{})["description"].(interface{}).(string)
- processStepRes[index] = v4.ProcessStep{
- Title: psTitle,
- SubTitle: psSubTitle,
- Description: psDescription,
- }
+ processStepMap := processStep.(map[string]interface{})
+ psTitle := processStepMap["title"].(string)
+ psSubTitle := processStepMap["sub_title"].(string)
+ psDescription := processStepMap["description"].(string)
+ mappedProcessStep := fabricv4.ProcessStep{}
+ mappedProcessStep.SetTitle(psTitle)
+ mappedProcessStep.SetSubTitle(psSubTitle)
+ mappedProcessStep.SetDescription(psDescription)
+ processStepRes[index] = mappedProcessStep
}
return processStepRes
}
-func portsToFabric(schemaPorts []interface{}) []v4.ServiceProfileAccessPointColo {
+func portsTerraformToGo(schemaPorts []interface{}) []fabricv4.ServiceProfileAccessPointCOLO {
if schemaPorts == nil {
return nil
}
- serviceProfileAccessPointColos := make([]v4.ServiceProfileAccessPointColo, len(schemaPorts))
+ serviceProfileAccessPointColos := make([]fabricv4.ServiceProfileAccessPointCOLO, len(schemaPorts))
for index, schemaPort := range schemaPorts {
- pType := schemaPort.(map[string]interface{})["type"].(string)
- pUuid := schemaPort.(map[string]interface{})["uuid"].(string)
- locationList := schemaPort.(map[string]interface{})["location"].(interface{}).(*schema.Set).List()
- pLocation := v4.SimplifiedLocation{}
- if len(locationList) != 0 {
- pLocation = equinix_fabric_schema.LocationToFabric(locationList)
+ portMap := schemaPort.(map[string]interface{})
+ coloPort := fabricv4.ServiceProfileAccessPointCOLO{}
+
+ type_ := portMap["type"].(string)
+ if type_ != "" {
+ pType := fabricv4.ServiceProfileAccessPointCOLOType(type_)
+ coloPort.SetType(pType)
}
- pSellerRegion := schemaPort.(map[string]interface{})["seller_region"].(string)
- pSellerRegionDescription := schemaPort.(map[string]interface{})["seller_region_description"].(string)
- pCrossConnectId := schemaPort.(map[string]interface{})["cross_connect_id"].(string)
- serviceProfileAccessPointColos[index] = v4.ServiceProfileAccessPointColo{
- Type_: pType,
- Uuid: pUuid,
- Location: &pLocation,
- SellerRegion: pSellerRegion,
- SellerRegionDescription: pSellerRegionDescription,
- CrossConnectId: pCrossConnectId,
+
+ pUuid := portMap["uuid"].(string)
+ if pUuid != "" {
+ coloPort.SetUuid(pUuid)
+ }
+
+ locationList := portMap["location"].(*schema.Set).List()
+ if locationList != nil && len(locationList) != 0 {
+ pLocation := equinix_fabric_schema.LocationTerraformToGo(locationList)
+ coloPort.SetLocation(pLocation)
}
+
+ pSellerRegion := portMap["seller_region"].(string)
+ if pSellerRegion != "" {
+ coloPort.SetSellerRegion(pSellerRegion)
+ }
+
+ pSellerRegionDescription := portMap["seller_region_description"].(string)
+ if pSellerRegionDescription != "" {
+ coloPort.SetSellerRegionDescription(pSellerRegionDescription)
+ }
+
+ pCrossConnectId := portMap["cross_connect_id"].(string)
+ if pCrossConnectId != "" {
+ coloPort.SetCrossConnectId(pCrossConnectId)
+ }
+
+ serviceProfileAccessPointColos[index] = coloPort
}
return serviceProfileAccessPointColos
}
-func virtualDevicesToFabric(schemaVirtualDevices []interface{}) []v4.ServiceProfileAccessPointVd {
+func virtualDevicesTerraformToGo(schemaVirtualDevices []interface{}) []fabricv4.ServiceProfileAccessPointVD {
if schemaVirtualDevices == nil {
- return []v4.ServiceProfileAccessPointVd{}
- }
- var virtualDevices []v4.ServiceProfileAccessPointVd
- for _, virtualDevice := range schemaVirtualDevices {
- vType := virtualDevice.(map[string]interface{})["type"].(string)
- vUuid := virtualDevice.(map[string]interface{})["uuid"].(string)
- locationList := virtualDevice.(map[string]interface{})["location"].(interface{}).(*schema.Set).List()
- vLocation := v4.SimplifiedLocation{}
+ return nil
+ }
+ virtualDevices := make([]fabricv4.ServiceProfileAccessPointVD, len(schemaVirtualDevices))
+ for index, virtualDevice := range schemaVirtualDevices {
+ vdMap := virtualDevice.(map[string]interface{})
+ vType := fabricv4.ServiceProfileAccessPointVDType(vdMap["type"].(string))
+ vUuid := vdMap["uuid"].(string)
+ locationList := vdMap["location"].(interface{}).(*schema.Set).List()
+ var vLocation fabricv4.SimplifiedLocation
if len(locationList) != 0 {
- vLocation = equinix_fabric_schema.LocationToFabric(locationList)
+ vLocation = equinix_fabric_schema.LocationTerraformToGo(locationList)
}
- pInterfaceUuid := virtualDevice.(map[string]interface{})["interface_uuid"].(string)
- virtualDevices = append(virtualDevices, v4.ServiceProfileAccessPointVd{
- Type_: vType,
- Uuid: vUuid,
- Location: &vLocation,
- InterfaceUuid: pInterfaceUuid,
- })
+ vInterfaceUuid := vdMap["interface_uuid"].(string)
+ accessPointVD := fabricv4.ServiceProfileAccessPointVD{}
+ accessPointVD.SetType(vType)
+ accessPointVD.SetUuid(vUuid)
+ accessPointVD.SetLocation(vLocation)
+ accessPointVD.SetInterfaceUuid(vInterfaceUuid)
+ virtualDevices[index] = accessPointVD
}
return virtualDevices
}
-func metrosToFabric(schemaMetros []interface{}) []v4.ServiceMetro {
+func metrosTerraformToGo(schemaMetros []interface{}) []fabricv4.ServiceMetro {
if schemaMetros == nil {
- return []v4.ServiceMetro{}
+ return nil
}
- var metros []v4.ServiceMetro
- for _, metro := range schemaMetros {
- mCode := metro.(map[string]interface{})["code"].(string)
- mName := metro.(map[string]interface{})["name"].(string)
- ibxsRaw := metro.(map[string]interface{})["ibxs"].([]interface{})
+ var metros []fabricv4.ServiceMetro
+ for index, metro := range schemaMetros {
+ metroMap := metro.(map[string]interface{})
+ mCode := metroMap["code"].(string)
+ mName := metroMap["name"].(string)
+ ibxsRaw := metroMap["ibxs"].([]interface{})
mIbxs := converters.IfArrToStringArr(ibxsRaw)
- mInTrail := metro.(map[string]interface{})["in_trail"].(bool)
- mDisplayName := metro.(map[string]interface{})["display_name"].(string)
- mSellerRegions := metro.(map[string]interface{})["seller_regions"].(map[string]string)
- metros = append(metros, v4.ServiceMetro{
- Code: mCode,
- Name: mName,
- Ibxs: mIbxs,
- InTrail: mInTrail,
- DisplayName: mDisplayName,
- SellerRegions: mSellerRegions,
- })
+ mInTrail := metroMap["in_trail"].(bool)
+ mDisplayName := metroMap["display_name"].(string)
+ mSellerRegions := metroMap["seller_regions"].(map[string]string)
+ mappedMetro := fabricv4.ServiceMetro{}
+ mappedMetro.SetCode(mCode)
+ mappedMetro.SetName(mName)
+ mappedMetro.SetIbxs(mIbxs)
+ mappedMetro.SetInTrail(mInTrail)
+ mappedMetro.SetDisplayName(mDisplayName)
+ mappedMetro.SetSellerRegions(mSellerRegions)
+ metros[index] = mappedMetro
}
return metros
}
-func serviceProfilesSearchFilterRequestToFabric(schemaServiceProfileFilterRequest []interface{}) v4.ServiceProfileSimpleExpression {
+func serviceProfilesSearchFilterRequestTerraformToGo(schemaServiceProfileFilterRequest []interface{}) fabricv4.ServiceProfileFilter {
if schemaServiceProfileFilterRequest == nil {
- return v4.ServiceProfileSimpleExpression{}
+ return fabricv4.ServiceProfileFilter{}
}
- mappedFilter := v4.ServiceProfileSimpleExpression{}
- for _, s := range schemaServiceProfileFilterRequest {
- sProperty := s.(map[string]interface{})["property"].(string)
- operator := s.(map[string]interface{})["operator"].(string)
- valuesRaw := s.(map[string]interface{})["values"].([]interface{})
- values := converters.IfArrToStringArr(valuesRaw)
- mappedFilter = v4.ServiceProfileSimpleExpression{Property: sProperty, Operator: operator, Values: values}
+ var mappedServiceProfileExpression fabricv4.ServiceProfileSimpleExpression
+ simpleExpressionMap := schemaServiceProfileFilterRequest[0].(map[string]interface{})
+ sProperty := simpleExpressionMap["property"].(string)
+ operator := simpleExpressionMap["operator"].(string)
+ valuesRaw := simpleExpressionMap["values"].([]interface{})
+ values := converters.IfArrToStringArr(valuesRaw)
+
+ mappedServiceProfileExpression.SetProperty(sProperty)
+ mappedServiceProfileExpression.SetOperator(operator)
+ mappedServiceProfileExpression.SetValues(values)
+
+ filter := fabricv4.ServiceProfileFilter{
+ ServiceProfileSimpleExpression: &mappedServiceProfileExpression,
}
- return mappedFilter
+
+ return filter
}
-func serviceProfilesSearchSortRequestToFabric(schemaServiceProfilesSearchSortRequest []interface{}) []v4.ServiceProfileSortCriteria {
+func serviceProfilesSearchSortRequestTerraformToGo(schemaServiceProfilesSearchSortRequest []interface{}) []fabricv4.ServiceProfileSortCriteria {
if schemaServiceProfilesSearchSortRequest == nil {
- return []v4.ServiceProfileSortCriteria{}
+ return nil
}
- var spSortCriteria []v4.ServiceProfileSortCriteria
- for _, sp := range schemaServiceProfilesSearchSortRequest {
+ spSortCriteria := make([]fabricv4.ServiceProfileSortCriteria, len(schemaServiceProfilesSearchSortRequest))
+ for index, sp := range schemaServiceProfilesSearchSortRequest {
serviceProfileSortCriteriaMap := sp.(map[string]interface{})
- direction := serviceProfileSortCriteriaMap["direction"]
- directionCont := v4.ServiceProfileSortDirection(direction.(string))
- property := serviceProfileSortCriteriaMap["property"]
- propertyCont := v4.ServiceProfileSortBy(property.(string))
- spSortCriteria = append(spSortCriteria, v4.ServiceProfileSortCriteria{
- Direction: &directionCont,
- Property: &propertyCont,
- })
-
+ direction := serviceProfileSortCriteriaMap["direction"].(string)
+ directionCont := fabricv4.ServiceProfileSortDirection(direction)
+ property := serviceProfileSortCriteriaMap["property"].(string)
+ propertyCont := fabricv4.ServiceProfileSortBy(property)
+ sortCriteria := fabricv4.ServiceProfileSortCriteria{}
+ sortCriteria.SetDirection(directionCont)
+ sortCriteria.SetProperty(propertyCont)
+ spSortCriteria[index] = sortCriteria
}
return spSortCriteria
}
diff --git a/equinix/resource_fabric_service_profile_acc_test.go b/equinix/resource_fabric_service_profile_acc_test.go
index f5def517c..7c43e63cb 100644
--- a/equinix/resource_fabric_service_profile_acc_test.go
+++ b/equinix/resource_fabric_service_profile_acc_test.go
@@ -5,14 +5,12 @@ import (
"fmt"
"github.com/equinix/terraform-provider-equinix/equinix"
"github.com/equinix/terraform-provider-equinix/internal/acceptance"
- "github.com/equinix/terraform-provider-equinix/internal/config"
+ "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"testing"
"time"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
-
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
)
func TestAccFabricCreateServiceProfile_PFCR(t *testing.T) {
@@ -23,16 +21,18 @@ func TestAccFabricCreateServiceProfile_PFCR(t *testing.T) {
if len(ports) > 0 {
portDot1Q := ports["pfcr"]["dot1q"][0]
portQinq := ports["pfcr"]["qinq"][0]
- portUuidDot1Q = portDot1Q.Uuid
- portMetroCodeDot1Q = portDot1Q.Location.MetroCode
- portTypeDot1Q = string(*portDot1Q.Type_)
- portUuidQinq = portQinq.Uuid
- portMetroCodeQinq = portQinq.Location.MetroCode
- portTypeQinq = string(*portQinq.Type_)
+ portUuidDot1Q = portDot1Q.GetUuid()
+ portMetroCodeDot1QLocation := portDot1Q.GetLocation()
+ portMetroCodeDot1Q = portMetroCodeDot1QLocation.GetMetroCode()
+ portTypeDot1Q = string(portDot1Q.GetType())
+ portUuidQinq = portQinq.GetUuid()
+ portMetroCodeQinqLocation := portQinq.GetLocation()
+ portMetroCodeQinq = portMetroCodeQinqLocation.GetMetroCode()
+ portTypeQinq = string(portQinq.GetType())
}
resource.ParallelTest(t, resource.TestCase{
- PreCheck: func() { acceptance.TestAccPreCheck(t) },
+ PreCheck: func() { acceptance.TestAccPreCheck(t); acceptance.TestAccPreCheckProviderConfigured(t) },
Providers: acceptance.TestAccProviders,
CheckDestroy: checkServiceProfileDelete,
Steps: []resource.TestStep{
@@ -154,14 +154,12 @@ func testAccFabricCreateServiceProfileConfig(portUUID string, portType string, p
}
func checkServiceProfileDelete(s *terraform.State) error {
- client := acceptance.TestAccProvider.Meta().(*config.Config).FabricClient
ctx := context.Background()
- ctx = context.WithValue(ctx, v4.ContextAccessToken, acceptance.TestAccProvider.Meta().(*config.Config).FabricAuthToken)
for _, rs := range s.RootModule().Resources {
if rs.Type != "equinix_fabric_service_profile" {
continue
}
- err := equinix.WaitAndCheckServiceProfileDeleted(rs.Primary.ID, client, ctx, 10*time.Minute)
+ err := equinix.WaitAndCheckServiceProfileDeleted(rs.Primary.ID, acceptance.TestAccProvider.Meta(), &schema.ResourceData{}, ctx, 10*time.Minute)
if err != nil {
return fmt.Errorf("API call failed while waiting for resource deletion: %v", err)
}
diff --git a/internal/config/config.go b/internal/config/config.go
index 50d17c176..a7ce96ce9 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -15,8 +15,8 @@ import (
"strings"
"time"
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/equinix/ecx-go/v2"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/equinix/equinix-sdk-go/services/metalv1"
"github.com/equinix/ne-go"
"github.com/equinix/oauth2-go"
@@ -95,6 +95,8 @@ type Config struct {
PageSize int
Token string
+ authClient *http.Client
+
Ecx ecx.Client
Ne ne.Client
Metal *packngo.Client
@@ -104,8 +106,6 @@ type Config struct {
metalUserAgent string
TerraformVersion string
- FabricClient *v4.APIClient
- FabricAuthToken string
}
// Load function validates configuration structure fields and configures
@@ -135,25 +135,11 @@ func (c *Config) Load(ctx context.Context) error {
BaseURL: c.BaseURL,
}
authClient = authConfig.New(ctx)
-
- if c.ClientID != "" && c.ClientSecret != "" {
- tke, err := authConfig.TokenSource(ctx, authClient).Token()
- if err != nil {
- if err != nil {
- return err
- }
- }
- if tke != nil {
- c.FabricAuthToken = tke.AccessToken
- }
- }
}
- if c.FabricAuthToken == "" {
- c.FabricAuthToken = c.Token
- }
authClient.Timeout = c.requestTimeout()
authClient.Transport = logging.NewTransport("Equinix", authClient.Transport)
+ c.authClient = authClient
ecxClient := ecx.NewClient(ctx, c.BaseURL, authClient)
neClient := ne.NewClient(ctx, c.BaseURL, authClient)
@@ -173,30 +159,47 @@ func (c *Config) Load(ctx context.Context) error {
c.Ecx = ecxClient
c.Ne = neClient
c.Metal = c.NewMetalClient()
- 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{
- Transport: transport,
- }
- authClient.Timeout = c.requestTimeout()
- fabricHeaderMap := map[string]string{
- "X-SOURCE": "API",
- "X-CORRELATION-ID": correlationId(25),
- }
- v4Configuration := v4.Configuration{
- BasePath: c.BaseURL,
- DefaultHeader: fabricHeaderMap,
- UserAgent: "equinix/fabric-go",
- HTTPClient: authClient,
+// NewFabricClientForSDK returns a terraform sdkv2 plugin compatible
+// equinix-sdk-go/fabricv4 client to be used to access Fabric's V4 APIs
+func (c *Config) NewFabricClientForSDK(d *schema.ResourceData) *fabricv4.APIClient {
+ client := c.newFabricClient()
+
+ baseUserAgent := c.tfSdkUserAgent(client.GetConfig().UserAgent)
+ client.GetConfig().UserAgent = generateModuleUserAgentString(d, baseUserAgent)
+
+ return client
+}
+
+// newFabricClient returns the base fabricv4 client that is then used for either the sdkv2 or framework
+// implementations of the Terraform Provider with exported Methods
+func (c *Config) newFabricClient() *fabricv4.APIClient {
+ transport := logging.NewTransport("Equinix Fabric (fabricv4)", c.authClient.Transport)
+
+ retryClient := retryablehttp.NewClient()
+ retryClient.HTTPClient.Transport = transport
+ retryClient.HTTPClient.Timeout = c.requestTimeout()
+ retryClient.RetryMax = c.MaxRetries
+ retryClient.RetryWaitMin = time.Second
+ retryClient.RetryWaitMax = c.MaxRetryWait
+ retryClient.CheckRetry = RetryPolicy
+ standardClient := retryClient.StandardClient()
+
+ baseURL, _ := url.Parse(c.BaseURL)
+
+ configuration := fabricv4.NewConfiguration()
+ configuration.Servers = fabricv4.ServerConfigurations{
+ fabricv4.ServerConfiguration{
+ URL: baseURL.String(),
+ },
}
- client := v4.NewAPIClient(&v4Configuration)
+ configuration.HTTPClient = standardClient
+ configuration.AddDefaultHeader("X-SOURCE", "API")
+ configuration.AddDefaultHeader("X-CORRELATION-ID", correlationId(25))
+ client := fabricv4.NewAPIClient(configuration)
+
return client
}
@@ -211,7 +214,7 @@ func (c *Config) NewMetalClient() *packngo.Client {
retryClient.RetryMax = c.MaxRetries
retryClient.RetryWaitMin = time.Second
retryClient.RetryWaitMax = c.MaxRetryWait
- retryClient.CheckRetry = MetalRetryPolicy
+ retryClient.CheckRetry = RetryPolicy
standardClient := retryClient.StandardClient()
baseURL, _ := url.Parse(c.BaseURL)
baseURL.Path = path.Join(baseURL.Path, metalBasePath) + "/"
@@ -258,7 +261,7 @@ func (c *Config) newMetalClient() *metalv1.APIClient {
retryClient.RetryMax = c.MaxRetries
retryClient.RetryWaitMin = time.Second
retryClient.RetryWaitMax = c.MaxRetryWait
- retryClient.CheckRetry = MetalRetryPolicy
+ retryClient.CheckRetry = RetryPolicy
standardClient := retryClient.StandardClient()
baseURL, _ := url.Parse(c.BaseURL)
@@ -283,7 +286,7 @@ func (c *Config) requestTimeout() time.Duration {
return c.RequestTimeout
}
-func MetalRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
+func RetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
if ctx.Err() != nil {
return false, ctx.Err()
}
diff --git a/internal/errors/errors.go b/internal/errors/errors.go
index 4d8d0078c..9a2f43cb5 100644
--- a/internal/errors/errors.go
+++ b/internal/errors/errors.go
@@ -2,10 +2,10 @@ package errors
import (
"fmt"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"net/http"
"strings"
- fabric "github.com/equinix-labs/fabric-go/fabric/v4"
"github.com/equinix/rest-go"
"github.com/packethost/packngo"
)
@@ -49,39 +49,9 @@ func convertToFriendlyError(errors Errors, resp *http.Response) error {
return er
}
-func FormatFabricAdditionalInfo(additionalInfo []fabric.PriceErrorAdditionalInfo) string {
- var str []string
- for _, addInfo := range additionalInfo {
- property, reason := addInfo.Property, addInfo.Reason
- if property != "" {
- property = fmt.Sprintf("Property: %s, ", addInfo.Property)
- }
- if reason != "" {
- reason = fmt.Sprintf("%s", addInfo.Reason)
- } else {
- reason = fmt.Sprintf("Reason: Not Provided")
- }
- str = append(str, fmt.Sprintf("{%s%s}", property, reason))
- }
- return strings.Join(str, ", ")
-}
-
func FormatFabricError(err error) error {
- // If in future one would like to do something with the response body of the API request
- // The line below is how to access it with the SwaggerCodegen Fabric Go 12/7/2023 - thogarty
- // errors = append(errors, string(err.(fabric.GenericSwaggerError).Body()))
var errors Errors
errors = append(errors, err.Error())
- if fabricErrs, ok := err.(fabric.GenericSwaggerError).Model().([]fabric.ModelError); ok {
- for _, e := range fabricErrs {
- errors = append(errors, fmt.Sprintf("Code: %s", e.ErrorCode))
- errors = append(errors, fmt.Sprintf("Message: %s", e.ErrorMessage))
- errors = append(errors, fmt.Sprintf("Details: %s", e.Details))
- if additionalInfo := FormatFabricAdditionalInfo(e.AdditionalInfo); additionalInfo != "" {
- errors = append(errors, fmt.Sprintf("AdditionalInfo: [%s]", additionalInfo))
- }
- }
- }
return errors
}
@@ -212,7 +182,7 @@ func HasApplicationErrorCode(errors []rest.ApplicationError, code string) bool {
return false
}
-func HasModelErrorCode(errors []fabric.ModelError, code string) bool {
+func HasErrorCode(errors []fabricv4.Error, code string) bool {
for _, err := range errors {
if err.ErrorCode == code {
return true
diff --git a/internal/fabric/schema/fabric_common_mapping_helpers.go b/internal/fabric/schema/fabric_common_mapping_helpers.go
index 129b5fa7f..387248bd1 100644
--- a/internal/fabric/schema/fabric_common_mapping_helpers.go
+++ b/internal/fabric/schema/fabric_common_mapping_helpers.go
@@ -1,80 +1,88 @@
package schema
import (
- v4 "github.com/equinix-labs/fabric-go/fabric/v4"
+ "github.com/equinix/equinix-sdk-go/services/fabricv4"
"github.com/equinix/terraform-provider-equinix/internal/converters"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
+ "strconv"
)
-func OrderToFabric(schemaOrder []interface{}) v4.Order {
- if schemaOrder == nil {
- return v4.Order{}
+func OrderTerraformToGo(orderTerraform []interface{}) fabricv4.Order {
+ if orderTerraform == nil || len(orderTerraform) == 0 {
+ return fabricv4.Order{}
}
- order := v4.Order{}
- for _, o := range schemaOrder {
- orderMap := o.(map[string]interface{})
- purchaseOrderNumber := orderMap["purchase_order_number"]
- billingTier := orderMap["billing_tier"]
- orderId := orderMap["order_id"]
- orderNumber := orderMap["order_number"]
- order = v4.Order{PurchaseOrderNumber: purchaseOrderNumber.(string), BillingTier: billingTier.(string), OrderId: orderId.(string), OrderNumber: orderNumber.(string)}
+ var order fabricv4.Order
+
+ orderMap := orderTerraform[0].(map[string]interface{})
+ purchaseOrderNumber := orderMap["purchase_order_number"].(string)
+ billingTier := orderMap["billing_tier"].(string)
+ orderId := orderMap["order_id"].(string)
+ orderNumber := orderMap["order_number"].(string)
+ if purchaseOrderNumber != "" {
+ order.SetPurchaseOrderNumber(purchaseOrderNumber)
+ }
+ if billingTier != "" {
+ order.SetBillingTier(billingTier)
+ }
+ if orderId != "" {
+ order.SetOrderId(orderId)
+ }
+ if orderNumber != "" {
+ order.SetOrderNumber(orderNumber)
}
+
return order
}
-func OrderToTerra(order *v4.Order) *schema.Set {
+func OrderGoToTerraform(order *fabricv4.Order) *schema.Set {
if order == nil {
return nil
}
- orders := []*v4.Order{order}
- mappedOrders := make([]interface{}, len(orders))
- for _, order := range orders {
- mappedOrder := make(map[string]interface{})
- mappedOrder["purchase_order_number"] = order.PurchaseOrderNumber
- mappedOrder["billing_tier"] = order.BillingTier
- mappedOrder["order_id"] = order.OrderId
- mappedOrder["order_number"] = order.OrderNumber
- mappedOrders = append(mappedOrders, mappedOrder)
- }
+ mappedOrder := make(map[string]interface{})
+ mappedOrder["purchase_order_number"] = order.GetPurchaseOrderNumber()
+ mappedOrder["billing_tier"] = order.GetBillingTier()
+ mappedOrder["order_id"] = order.GetOrderId()
+ mappedOrder["order_number"] = order.GetOrderNumber()
orderSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: OrderSch()}),
- mappedOrders,
+ []interface{}{mappedOrder},
)
return orderSet
}
-func AccountToTerra[Account *v4.SimplifiedAccount | *v4.AllOfServiceProfileAccount](account Account) *schema.Set {
- if account == nil {
+func AccountGoToTerraform[accountType *fabricv4.SimplifiedAccount | *fabricv4.SimplifiedAccountPortResponse](accountParam accountType) *schema.Set {
+ if accountParam == nil {
return nil
}
- var mappedAccount map[string]interface{}
- switch any(account).(type) {
- case *v4.SimplifiedAccount:
- simplifiedAccount := any(account).(*v4.SimplifiedAccount)
+
+ mappedAccount := map[string]interface{}{}
+
+ switch account := (interface{})(accountParam).(type) {
+ case *fabricv4.SimplifiedAccount:
mappedAccount = map[string]interface{}{
- "account_number": int(simplifiedAccount.AccountNumber),
- "account_name": simplifiedAccount.AccountName,
- "org_id": int(simplifiedAccount.OrgId),
- "organization_name": simplifiedAccount.OrganizationName,
- "global_org_id": simplifiedAccount.GlobalOrgId,
- "global_organization_name": simplifiedAccount.GlobalOrganizationName,
- "global_cust_id": simplifiedAccount.GlobalCustId,
- "ucm_id": simplifiedAccount.UcmId,
+ "account_number": int(account.GetAccountNumber()),
+ "account_name": account.GetAccountName(),
+ "org_id": int(account.GetOrgId()),
+ "organization_name": account.GetOrganizationName(),
+ "global_org_id": account.GetGlobalOrgId(),
+ "global_organization_name": account.GetGlobalOrganizationName(),
+ "global_cust_id": account.GetGlobalCustId(),
+ "ucm_id": account.GetUcmId(),
}
- case *v4.AllOfServiceProfileAccount:
- allSPAccount := any(account).(*v4.AllOfServiceProfileAccount)
+ case *fabricv4.SimplifiedAccountPortResponse:
+ accountNumber, _ := strconv.Atoi(account.GetAccountNumber())
+ orgId, _ := strconv.Atoi(account.GetOrgId())
+
mappedAccount = map[string]interface{}{
- "account_number": int(allSPAccount.AccountNumber),
- "account_name": allSPAccount.AccountName,
- "org_id": int(allSPAccount.OrgId),
- "organization_name": allSPAccount.OrganizationName,
- "global_org_id": allSPAccount.GlobalOrgId,
- "global_organization_name": allSPAccount.GlobalOrganizationName,
- "global_cust_id": allSPAccount.GlobalCustId,
- "ucm_id": allSPAccount.UcmId,
+ "account_number": accountNumber,
+ "account_name": account.GetAccountName(),
+ "org_id": orgId,
+ "organization_name": account.GetOrganizationName(),
+ "global_org_id": account.GetGlobalOrgId(),
+ "global_organization_name": account.GetGlobalOrganizationName(),
+ "global_cust_id": account.GetGlobalCustId(),
+ "ucm_id": account.GetUcmId(),
}
- default:
- return nil
}
accountSet := schema.NewSet(
@@ -85,66 +93,79 @@ func AccountToTerra[Account *v4.SimplifiedAccount | *v4.AllOfServiceProfileAccou
return accountSet
}
-func NotificationsToFabric(schemaNotifications []interface{}) []v4.SimplifiedNotification {
- if schemaNotifications == nil {
- return []v4.SimplifiedNotification{}
+func NotificationsTerraformToGo(notificationsTerraform []interface{}) []fabricv4.SimplifiedNotification {
+ if notificationsTerraform == nil || len(notificationsTerraform) == 0 {
+ return nil
}
- var notifications []v4.SimplifiedNotification
- for _, n := range schemaNotifications {
- ntype := n.(map[string]interface{})["type"].(string)
- interval := n.(map[string]interface{})["send_interval"].(string)
- emailsRaw := n.(map[string]interface{})["emails"].([]interface{})
+ notifications := make([]fabricv4.SimplifiedNotification, len(notificationsTerraform))
+ for index, notification := range notificationsTerraform {
+ notificationMap := notification.(map[string]interface{})
+ notificationType := fabricv4.SimplifiedNotificationType(notificationMap["type"].(string))
+ sendInterval := notificationMap["send_interval"].(string)
+ emailsRaw := notificationMap["emails"].([]interface{})
emails := converters.IfArrToStringArr(emailsRaw)
- notifications = append(notifications, v4.SimplifiedNotification{
- Type_: ntype,
- SendInterval: interval,
- Emails: emails,
- })
+ simplifiedNotification := fabricv4.SimplifiedNotification{}
+ simplifiedNotification.SetType(notificationType)
+ if sendInterval != "" {
+ simplifiedNotification.SetSendInterval(sendInterval)
+ }
+ simplifiedNotification.SetEmails(emails)
+ notifications[index] = simplifiedNotification
}
return notifications
}
-func NotificationsToTerra(notifications []v4.SimplifiedNotification) []map[string]interface{} {
+func NotificationsGoToTerraform(notifications []fabricv4.SimplifiedNotification) []map[string]interface{} {
if notifications == nil {
return nil
}
mappedNotifications := make([]map[string]interface{}, len(notifications))
for index, notification := range notifications {
mappedNotifications[index] = map[string]interface{}{
- "type": notification.Type_,
- "send_interval": notification.SendInterval,
- "emails": notification.Emails,
+ "type": string(notification.GetType()),
+ "send_interval": notification.GetSendInterval(),
+ "emails": notification.GetEmails(),
}
}
return mappedNotifications
}
-func LocationToFabric(locationList []interface{}) v4.SimplifiedLocation {
- sl := v4.SimplifiedLocation{}
- for _, ll := range locationList {
- llMap := ll.(map[string]interface{})
- metroName := llMap["metro_name"]
- var metroNamestr string
- if metroName != nil {
- metroNamestr = metroName.(string)
- }
- region := llMap["region"].(string)
- mc := llMap["metro_code"].(string)
- ibx := llMap["ibx"].(string)
- sl = v4.SimplifiedLocation{MetroCode: mc, Region: region, Ibx: ibx, MetroName: metroNamestr}
+func LocationTerraformToGo(locationList []interface{}) fabricv4.SimplifiedLocation {
+ if locationList == nil || len(locationList) == 0 {
+ return fabricv4.SimplifiedLocation{}
+ }
+
+ var location fabricv4.SimplifiedLocation
+ locationListMap := locationList[0].(map[string]interface{})
+ metroName := locationListMap["metro_name"].(string)
+ region := locationListMap["region"].(string)
+ metroCode := locationListMap["metro_code"].(string)
+ ibx := locationListMap["ibx"].(string)
+ if metroName != "" {
+ location.SetMetroName(metroName)
}
- return sl
+ if region != "" {
+ location.SetRegion(region)
+ }
+ if metroCode != "" {
+ location.SetMetroCode(metroCode)
+ }
+ if ibx != "" {
+ location.SetIbx(ibx)
+ }
+
+ return location
}
-func LocationToTerra(location *v4.SimplifiedLocation) *schema.Set {
+func LocationGoToTerraform(location *fabricv4.SimplifiedLocation) *schema.Set {
if location == nil {
return nil
}
mappedLocations := make(map[string]interface{})
- mappedLocations["region"] = location.Region
- mappedLocations["metro_name"] = location.MetroName
- mappedLocations["metro_code"] = location.MetroCode
- mappedLocations["ibx"] = location.Ibx
+ mappedLocations["region"] = location.GetRegion()
+ mappedLocations["metro_name"] = location.GetMetroName()
+ mappedLocations["metro_code"] = location.GetMetroCode()
+ mappedLocations["ibx"] = location.GetIbx()
locationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: LocationSch()}),
@@ -153,96 +174,77 @@ func LocationToTerra(location *v4.SimplifiedLocation) *schema.Set {
return locationSet
}
-func LocationWithoutIBXToFabric(locationList []interface{}) v4.SimplifiedLocationWithoutIbx {
- sl := v4.SimplifiedLocationWithoutIbx{}
- for _, ll := range locationList {
- llMap := ll.(map[string]interface{})
- mc := llMap["metro_code"].(string)
- sl = v4.SimplifiedLocationWithoutIbx{MetroCode: mc}
+func LocationWithoutIBXTerraformToGo(locationList []interface{}) fabricv4.SimplifiedLocationWithoutIBX {
+ if locationList == nil || len(locationList) == 0 {
+ return fabricv4.SimplifiedLocationWithoutIBX{}
}
- return sl
+
+ var locationWithoutIbx fabricv4.SimplifiedLocationWithoutIBX
+ locationMap := locationList[0].(map[string]interface{})
+ metro_code := locationMap["metro_code"].(string)
+ locationWithoutIbx.SetMetroCode(metro_code)
+ return locationWithoutIbx
}
-func LocationWithoutIBXToTerra(location *v4.SimplifiedLocationWithoutIbx) *schema.Set {
- locations := []*v4.SimplifiedLocationWithoutIbx{location}
- mappedLocations := make([]interface{}, len(locations))
- for i, location := range locations {
- mappedLocations[i] = map[string]interface{}{
- "region": location.Region,
- "metro_name": location.MetroName,
- "metro_code": location.MetroCode,
- }
+func LocationWithoutIBXGoToTerraform(location *fabricv4.SimplifiedLocationWithoutIBX) *schema.Set {
+ mappedLocation := map[string]interface{}{
+ "region": location.GetRegion(),
+ "metro_name": location.GetMetroName(),
+ "metro_code": location.GetMetroCode(),
}
+
locationSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: LocationSch()}),
- mappedLocations,
+ []interface{}{mappedLocation},
)
return locationSet
}
-func ProjectToFabric(projectRequest []interface{}) *v4.Project {
- if len(projectRequest) == 0 {
- return nil
+func ProjectTerraformToGo(projectTerraform []interface{}) fabricv4.Project {
+ if projectTerraform == nil || len(projectTerraform) == 0 {
+ return fabricv4.Project{}
+ }
+ var project fabricv4.Project
+ projectMap := projectTerraform[0].(map[string]interface{})
+ projectId := projectMap["project_id"].(string)
+ if projectId != "" {
+ project.SetProjectId(projectId)
}
- mappedPr := &v4.Project{}
- prMap := projectRequest[0].(map[string]interface{})
- projectId := prMap["project_id"].(string)
- mappedPr.ProjectId = projectId
- return mappedPr
+ return project
}
-func ProjectToTerra(project *v4.Project) *schema.Set {
+func ProjectGoToTerraform(project *fabricv4.Project) *schema.Set {
if project == nil {
return nil
}
mappedProject := make(map[string]interface{})
- mappedProject["project_id"] = project.ProjectId
+ mappedProject["project_id"] = project.GetProjectId()
projectSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: ProjectSch()}),
[]interface{}{mappedProject})
return projectSet
}
-func ChangeLogToTerra[ChangeLog *v4.Changelog | *v4.AllOfServiceProfileChangeLog](changeLog ChangeLog) *schema.Set {
+func ChangeLogGoToTerraform(changeLog *fabricv4.Changelog) *schema.Set {
if changeLog == nil {
return nil
}
- var mappedChangeLog map[string]interface{}
- switch any(changeLog).(type) {
- case *v4.Changelog:
- baseChangeLog := any(changeLog).(*v4.Changelog)
- mappedChangeLog = map[string]interface{}{
- "created_by": baseChangeLog.CreatedBy,
- "created_by_full_name": baseChangeLog.CreatedByFullName,
- "created_by_email": baseChangeLog.CreatedByEmail,
- "created_date_time": baseChangeLog.CreatedDateTime.String(),
- "updated_by": baseChangeLog.UpdatedBy,
- "updated_by_full_name": baseChangeLog.UpdatedByFullName,
- "updated_date_time": baseChangeLog.UpdatedDateTime.String(),
- "deleted_by": baseChangeLog.DeletedBy,
- "deleted_by_full_name": baseChangeLog.DeletedByFullName,
- "deleted_by_email": baseChangeLog.DeletedByEmail,
- "deleted_date_time": baseChangeLog.DeletedDateTime.String(),
- }
- case *v4.AllOfServiceProfileChangeLog:
- allOfChangeLog := any(changeLog).(*v4.AllOfServiceProfileChangeLog)
- mappedChangeLog = map[string]interface{}{
- "created_by": allOfChangeLog.CreatedBy,
- "created_by_full_name": allOfChangeLog.CreatedByFullName,
- "created_by_email": allOfChangeLog.CreatedByEmail,
- "created_date_time": allOfChangeLog.CreatedDateTime.String(),
- "updated_by": allOfChangeLog.UpdatedBy,
- "updated_by_full_name": allOfChangeLog.UpdatedByFullName,
- "updated_date_time": allOfChangeLog.UpdatedDateTime.String(),
- "deleted_by": allOfChangeLog.DeletedBy,
- "deleted_by_full_name": allOfChangeLog.DeletedByFullName,
- "deleted_by_email": allOfChangeLog.DeletedByEmail,
- "deleted_date_time": allOfChangeLog.DeletedDateTime.String(),
- }
- default:
- return nil
+
+ mappedChangeLog := map[string]interface{}{
+ "created_by": changeLog.GetCreatedBy(),
+ "created_by_full_name": changeLog.GetCreatedByFullName(),
+ "created_by_email": changeLog.GetCreatedByEmail(),
+ "created_date_time": changeLog.GetCreatedDateTime().String(),
+ "updated_by": changeLog.GetUpdatedBy(),
+ "updated_by_full_name": changeLog.GetUpdatedByFullName(),
+ "updated_date_time": changeLog.GetUpdatedDateTime().String(),
+ "deleted_by": changeLog.GetDeletedBy(),
+ "deleted_by_full_name": changeLog.GetDeletedByFullName(),
+ "deleted_by_email": changeLog.GetDeletedByEmail(),
+ "deleted_date_time": changeLog.GetDeletedDateTime().String(),
}
+
changeLogSet := schema.NewSet(
schema.HashResource(&schema.Resource{Schema: ChangeLogSch()}),
[]interface{}{mappedChangeLog},
@@ -250,33 +252,33 @@ func ChangeLogToTerra[ChangeLog *v4.Changelog | *v4.AllOfServiceProfileChangeLog
return changeLogSet
}
-func ErrorToTerra(errors []v4.ModelError) []interface{} {
- if errors == nil {
+func ErrorGoToTerraform(errors []fabricv4.Error) []interface{} {
+ if errors == nil || len(errors) == 0 {
return nil
}
mappedErrors := make([]interface{}, len(errors))
for index, mError := range errors {
mappedErrors[index] = map[string]interface{}{
- "error_code": mError.ErrorCode,
- "error_message": mError.ErrorMessage,
- "correlation_id": mError.CorrelationId,
- "details": mError.Details,
- "help": mError.Help,
- "additional_info": ErrorAdditionalInfoToTerra(mError.AdditionalInfo),
+ "error_code": mError.GetErrorCode(),
+ "error_message": mError.GetErrorMessage(),
+ "correlation_id": mError.GetCorrelationId(),
+ "details": mError.GetDetails(),
+ "help": mError.GetHelp(),
+ "additional_info": ErrorAdditionalInfoGoToTerraform(mError.GetAdditionalInfo()),
}
}
return mappedErrors
}
-func ErrorAdditionalInfoToTerra(additionalInfol []v4.PriceErrorAdditionalInfo) []interface{} {
+func ErrorAdditionalInfoGoToTerraform(additionalInfol []fabricv4.PriceErrorAdditionalInfo) []interface{} {
if additionalInfol == nil {
return nil
}
mappedAdditionalInfol := make([]interface{}, len(additionalInfol))
for index, additionalInfo := range additionalInfol {
mappedAdditionalInfol[index] = map[string]interface{}{
- "property": additionalInfo.Property,
- "reason": additionalInfo.Reason,
+ "property": additionalInfo.GetProperty(),
+ "reason": additionalInfo.GetReason(),
}
}
return mappedAdditionalInfol