From 3f877209c20938f842d48afa3db836b1678d4dda Mon Sep 17 00:00:00 2001 From: Oriol Date: Fri, 3 May 2024 11:06:14 +0200 Subject: [PATCH] chore: Migrates `privatelink_endpoint_service` to new auto-generated SDK (#2222) --- ...ata_source_privatelink_endpoint_service.go | 18 +-- ...ource_privatelink_endpoint_service_test.go | 83 ---------- .../resource_privatelink_endpoint_service.go | 149 ++++++++---------- ...atelink_endpoint_service_migration_test.go | 57 +------ ...ource_privatelink_endpoint_service_test.go | 54 ++++--- internal/testutil/acc/pre_check.go | 9 ++ 6 files changed, 121 insertions(+), 249 deletions(-) delete mode 100644 internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go diff --git a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go index e8860cae68..ed7ce5255f 100644 --- a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go @@ -14,7 +14,7 @@ import ( func DataSource() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceMongoDBAtlasPrivateEndpointServiceLinkRead, + ReadContext: dataSourceRead, Schema: map[string]*schema.Schema{ "project_id": { Type: schema.TypeString, @@ -100,34 +100,34 @@ func DataSource() *schema.Resource { } } -func dataSourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. - conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) privateLinkID := conversion.GetEncodedID(d.Get("private_link_id").(string), "private_link_id") endpointServiceID := conversion.GetEncodedID(d.Get("endpoint_service_id").(string), "endpoint_service_id") providerName := d.Get("provider_name").(string) - serviceEndpoint, _, err := conn.PrivateEndpoints.GetOnePrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID) + serviceEndpoint, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return diag.FromErr(fmt.Errorf(ErrorServiceEndpointRead, endpointServiceID, err)) } - if err := d.Set("delete_requested", cast.ToBool(serviceEndpoint.DeleteRequested)); err != nil { + if err := d.Set("delete_requested", cast.ToBool(serviceEndpoint.GetDeleteRequested())); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "delete_requested", endpointServiceID, err)) } - if err := d.Set("error_message", serviceEndpoint.ErrorMessage); err != nil { + if err := d.Set("error_message", serviceEndpoint.GetErrorMessage()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "error_message", endpointServiceID, err)) } - if err := d.Set("aws_connection_status", serviceEndpoint.AWSConnectionStatus); err != nil { + if err := d.Set("aws_connection_status", serviceEndpoint.GetConnectionStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "aws_connection_status", endpointServiceID, err)) } if strings.EqualFold(providerName, "azure") { - if err := d.Set("azure_status", serviceEndpoint.Status); err != nil { + if err := d.Set("azure_status", serviceEndpoint.GetStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "azure_status", endpointServiceID, err)) } } @@ -137,7 +137,7 @@ func dataSourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d } if strings.EqualFold(providerName, "gcp") { - if err := d.Set("gcp_status", serviceEndpoint.Status); err != nil { + if err := d.Set("gcp_status", serviceEndpoint.GetStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "gcp_status", endpointServiceID, err)) } } diff --git a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go deleted file mode 100644 index f06c088bbc..0000000000 --- a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package privatelinkendpointservice_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" -) - -func TestAccNetworkDSPrivateLinkEndpointServiceAWS_basic(t *testing.T) { - acc.SkipTestForCI(t) // needs AWS configuration - - resourceName := "data.mongodbatlas_privatelink_endpoint_service.test" - - awsAccessKey := os.Getenv("AWS_ACCESS_KEY_ID") - awsSecretKey := os.Getenv("AWS_SECRET_ACCESS_KEY") - - projectID := os.Getenv("MONGODB_ATLAS_PROJECT_ID") - region := os.Getenv("AWS_REGION") - providerName := "AWS" - - vpcID := os.Getenv("AWS_VPC_ID") - subnetID := os.Getenv("AWS_SUBNET_ID") - securityGroupID := os.Getenv("AWS_SECURITY_GROUP_ID") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Steps: []resource.TestStep{ - { - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceDataSourceConfig( - awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, - ), - Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), - resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), - ), - }, - }, - }) -} - -func testAccMongoDBAtlasPrivateLinkEndpointServiceDataSourceConfig(awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID string) string { - return fmt.Sprintf(` - provider "aws" { - region = "us-east-1" - access_key = "%s" - secret_key = "%s" - } - - resource "mongodbatlas_privatelink_endpoint" "test" { - project_id = "%s" - provider_name = "%s" - region = "%s" - } - - resource "aws_vpc_endpoint" "ptfe_service" { - vpc_id = "%s" - service_name = mongodbatlas_privatelink_endpoint.test.endpoint_service_name - vpc_endpoint_type = "Interface" - subnet_ids = ["%s"] - security_group_ids = ["%s"] - } - - resource "mongodbatlas_privatelink_endpoint_service" "test" { - project_id = mongodbatlas_privatelink_endpoint.test.project_id - endpoint_service_id = aws_vpc_endpoint.ptfe_service.id - private_link_id = mongodbatlas_privatelink_endpoint.test.private_link_id - provider_name = "%[4]s" - } - - data "mongodbatlas_privatelink_endpoint_service" "test" { - project_id = mongodbatlas_privatelink_endpoint.test.project_id - private_link_id = mongodbatlas_privatelink_endpoint_service.test.private_link_id - endpoint_service_id = mongodbatlas_privatelink_endpoint_service.test.endpoint_service_id - provider_name = "%[4]s" - } - `, awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID) -} diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index 66293aaaba..e0e7f15dfa 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -13,11 +13,11 @@ import ( "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" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" - "github.com/spf13/cast" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115012/admin" ) const ( @@ -29,11 +29,11 @@ const ( func Resource() *schema.Resource { return &schema.Resource{ - CreateContext: resourceMongoDBAtlasPrivateEndpointServiceLinkCreate, - ReadWithoutTimeout: resourceMongoDBAtlasPrivateEndpointServiceLinkRead, - DeleteContext: resourceMongoDBAtlasPrivateEndpointServiceLinkDelete, + CreateContext: resourceCreate, + ReadWithoutTimeout: resourceRead, + DeleteContext: resourceDelete, Importer: &schema.ResourceImporter{ - StateContext: resourceMongoDBAtlasPrivateEndpointServiceLinkImportState, + StateContext: resourceImportState, }, Schema: map[string]*schema.Schema{ "project_id": { @@ -121,8 +121,9 @@ func Resource() *schema.Resource { Optional: true, }, "service_attachment_name": { - Type: schema.TypeString, - Computed: true, + Type: schema.TypeString, + Computed: true, + Deprecated: fmt.Sprintf(constant.DeprecationParamByVersion, "1.18.0"), }, }, }, @@ -139,8 +140,7 @@ func Resource() *schema.Resource { } } -func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas +func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) privateLinkID := conversion.GetEncodedID(d.Get("private_link_id").(string), "private_link_id") @@ -150,27 +150,27 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d gPI, gPIOk := d.GetOk("gcp_project_id") e, eOk := d.GetOk("endpoints") - request := &matlas.InterfaceEndpointConnection{} + createEndpointRequest := &admin.CreateEndpointRequest{} switch providerName { case "AWS": - request.ID = endpointServiceID + createEndpointRequest.Id = &endpointServiceID case "AZURE": if !pEIAOk { return diag.FromErr(errors.New("`private_endpoint_ip_address` must be set when `provider_name` is `AZURE`")) } - request.ID = endpointServiceID - request.PrivateEndpointIPAddress = pEIA.(string) + createEndpointRequest.Id = &endpointServiceID + createEndpointRequest.PrivateEndpointIPAddress = conversion.Pointer(pEIA.(string)) case "GCP": if !gPIOk || !eOk { return diag.FromErr(errors.New("`gcp_project_id`, `endpoints` must be set when `provider_name` is `GCP`")) } - request.EndpointGroupName = endpointServiceID - request.GCPProjectID = gPI.(string) - request.Endpoints = expandGCPEndpoints(e.([]any)) + createEndpointRequest.EndpointGroupName = &endpointServiceID + createEndpointRequest.GcpProjectId = conversion.Pointer(gPI.(string)) + createEndpointRequest.Endpoints = expandGCPEndpoints(e.([]any)) } - _, _, err := conn.PrivateEndpoints.AddOnePrivateEndpoint(ctx, projectID, providerName, privateLinkID, request) + _, _, err := connV2.PrivateEndpointServicesApi.CreatePrivateEndpoint(ctx, projectID, providerName, privateLinkID, createEndpointRequest).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorServiceEndpointAdd, providerName, privateLinkID, err)) } @@ -178,7 +178,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d stateConf := &retry.StateChangeConf{ Pending: []string{"NONE", "INITIATING", "PENDING_ACCEPTANCE", "PENDING", "DELETING", "VERIFIED"}, Target: []string{"AVAILABLE", "REJECTED", "DELETED", "FAILED"}, - Refresh: resourceServiceEndpointRefreshFunc(ctx, conn, projectID, providerName, privateLinkID, endpointServiceID), + Refresh: resourceRefreshFunc(ctx, connV2, projectID, providerName, privateLinkID, endpointServiceID), Timeout: d.Timeout(schema.TimeoutCreate), MinTimeout: 5 * time.Second, Delay: 5 * time.Minute, @@ -210,11 +210,11 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d "provider_name": providerName, })) - return resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas +func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] @@ -222,7 +222,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d * endpointServiceID := ids["endpoint_service_id"] providerName := ids["provider_name"] - privateEndpoint, resp, err := conn.PrivateEndpoints.GetOnePrivateEndpoint(context.Background(), projectID, providerName, privateLinkID, endpointServiceID) + privateEndpoint, resp, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(context.Background(), projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -232,38 +232,38 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d * return diag.FromErr(fmt.Errorf(ErrorServiceEndpointRead, endpointServiceID, err)) } - if err := d.Set("delete_requested", cast.ToBool(privateEndpoint.DeleteRequested)); err != nil { + if err := d.Set("delete_requested", privateEndpoint.GetDeleteRequested()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "delete_requested", endpointServiceID, err)) } - if err := d.Set("error_message", privateEndpoint.ErrorMessage); err != nil { + if err := d.Set("error_message", privateEndpoint.GetErrorMessage()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "error_message", endpointServiceID, err)) } - if err := d.Set("aws_connection_status", privateEndpoint.AWSConnectionStatus); err != nil { + if err := d.Set("aws_connection_status", privateEndpoint.GetConnectionStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "aws_connection_status", endpointServiceID, err)) } if providerName == "AZURE" { - if err := d.Set("azure_status", privateEndpoint.Status); err != nil { + if err := d.Set("azure_status", privateEndpoint.GetStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "azure_status", endpointServiceID, err)) } } - if err := d.Set("interface_endpoint_id", privateEndpoint.InterfaceEndpointID); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + if err := d.Set("interface_endpoint_id", privateEndpoint.GetInterfaceEndpointId()); err != nil { + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "interface_endpoint_id", endpointServiceID, err)) } - if err := d.Set("private_endpoint_connection_name", privateEndpoint.PrivateEndpointConnectionName); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + if err := d.Set("private_endpoint_connection_name", privateEndpoint.GetPrivateEndpointConnectionName()); err != nil { + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_connection_name", endpointServiceID, err)) } - if err := d.Set("private_endpoint_ip_address", privateEndpoint.PrivateEndpointIPAddress); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + if err := d.Set("private_endpoint_ip_address", privateEndpoint.GetPrivateEndpointIPAddress()); err != nil { + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_ip_address", endpointServiceID, err)) } - if err := d.Set("private_endpoint_resource_id", privateEndpoint.PrivateEndpointResourceID); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + if err := d.Set("private_endpoint_resource_id", privateEndpoint.GetPrivateEndpointResourceId()); err != nil { + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_resource_id", endpointServiceID, err)) } if err := d.Set("endpoint_service_id", endpointServiceID); err != nil { @@ -275,7 +275,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d * } if providerName == "GCP" { - if err := d.Set("gcp_status", privateEndpoint.Status); err != nil { + if err := d.Set("gcp_status", privateEndpoint.GetStatus()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "gcp_status", endpointServiceID, err)) } } @@ -283,8 +283,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d * return nil } -func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas +func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) @@ -294,7 +293,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d providerName := ids["provider_name"] if endpointServiceID != "" { - _, err := conn.PrivateEndpoints.DeleteOnePrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID) + _, _, err := connV2.PrivateEndpointServicesApi.DeletePrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorEndpointDelete, endpointServiceID, err)) } @@ -302,7 +301,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d stateConf := &retry.StateChangeConf{ Pending: []string{"NONE", "PENDING_ACCEPTANCE", "PENDING", "DELETING", "INITIATING"}, Target: []string{"REJECTED", "DELETED", "FAILED"}, - Refresh: resourceServiceEndpointRefreshFunc(ctx, conn, projectID, providerName, privateLinkID, endpointServiceID), + Refresh: resourceRefreshFunc(ctx, connV2, projectID, providerName, privateLinkID, endpointServiceID), Timeout: d.Timeout(schema.TimeoutDelete), MinTimeout: 5 * time.Second, Delay: 3 * time.Second, @@ -332,8 +331,8 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d return nil } -func resourceMongoDBAtlasPrivateEndpointServiceLinkImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - conn := meta.(*config.MongoDBClient).Atlas +func resourceImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { + connV2 := meta.(*config.MongoDBClient).AtlasV2 parts := strings.SplitN(d.Id(), "--", 4) if len(parts) != 4 { @@ -345,7 +344,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkImportState(ctx context.Conte endpointServiceID := parts[2] providerName := parts[3] - _, _, err := conn.PrivateEndpoints.GetOnePrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID) + _, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return nil, fmt.Errorf(ErrorServiceEndpointRead, endpointServiceID, err) } @@ -376,9 +375,9 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkImportState(ctx context.Conte return []*schema.ResourceData{d}, nil } -func resourceServiceEndpointRefreshFunc(ctx context.Context, client *matlas.Client, projectID, providerName, privateLinkID, endpointServiceID string) retry.StateRefreshFunc { +func resourceRefreshFunc(ctx context.Context, client *admin.APIClient, projectID, providerName, privateLinkID, endpointServiceID string) retry.StateRefreshFunc { return func() (any, string, error) { - i, resp, err := client.PrivateEndpoints.GetOnePrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID) + i, resp, err := client.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { if resp != nil && resp.StatusCode == 404 { return "", "DELETED", nil @@ -388,85 +387,71 @@ func resourceServiceEndpointRefreshFunc(ctx context.Context, client *matlas.Clie } if strings.EqualFold(providerName, "azure") || strings.EqualFold(providerName, "gcp") { - if i.Status != "AVAILABLE" { - return "", i.Status, nil + if i.GetStatus() != "AVAILABLE" { + return "", i.GetStatus(), nil } - return i, i.Status, nil + return i, *i.Status, nil } - if i.AWSConnectionStatus != "AVAILABLE" { - return "", i.AWSConnectionStatus, nil + if i.GetConnectionStatus() != "AVAILABLE" { + return "", i.GetConnectionStatus(), nil } - return i, i.AWSConnectionStatus, nil + return i, *i.ConnectionStatus, nil } } -func expandGCPEndpoint(tfMap map[string]any) *matlas.GCPEndpoint { - if tfMap == nil { - return nil - } - - apiObject := &matlas.GCPEndpoint{} +func expandGCPEndpoint(tfMap map[string]any) admin.CreateGCPForwardingRuleRequest { + apiObject := admin.CreateGCPForwardingRuleRequest{} if v, ok := tfMap["endpoint_name"]; ok { - apiObject.EndpointName = cast.ToString(v) + apiObject.EndpointName = conversion.Pointer(v.(string)) } if v, ok := tfMap["ip_address"]; ok { - apiObject.IPAddress = cast.ToString(v) + apiObject.IpAddress = conversion.Pointer(v.(string)) } return apiObject } -func expandGCPEndpoints(tfList []any) []*matlas.GCPEndpoint { +func expandGCPEndpoints(tfList []any) *[]admin.CreateGCPForwardingRuleRequest { if len(tfList) == 0 { return nil } - var apiObjects []*matlas.GCPEndpoint + var apiObjects []admin.CreateGCPForwardingRuleRequest for _, tfMapRaw := range tfList { if tfMap, ok := tfMapRaw.(map[string]any); ok { - apiObject := expandGCPEndpoint(tfMap) - if apiObject == nil { - continue + if tfMap != nil { + apiObject := expandGCPEndpoint(tfMap) + apiObjects = append(apiObjects, apiObject) } - apiObjects = append(apiObjects, apiObject) } } - return apiObjects + return &apiObjects } -func flattenGCPEndpoint(apiObject *matlas.GCPEndpoint) map[string]any { - if apiObject == nil { - return nil - } - +func flattenGCPEndpoint(apiObject admin.GCPConsumerForwardingRule) map[string]any { tfMap := map[string]any{} log.Printf("[DEBIG] apiObject : %+v", apiObject) - tfMap["endpoint_name"] = apiObject.EndpointName - tfMap["ip_address"] = apiObject.IPAddress - tfMap["status"] = apiObject.Status - tfMap["service_attachment_name"] = apiObject.ServiceAttachmentName + tfMap["endpoint_name"] = apiObject.GetEndpointName() + tfMap["ip_address"] = apiObject.GetIpAddress() + tfMap["status"] = apiObject.GetStatus() return tfMap } -func flattenGCPEndpoints(apiObjects []*matlas.GCPEndpoint) []any { - if len(apiObjects) == 0 { +func flattenGCPEndpoints(apiObjects *[]admin.GCPConsumerForwardingRule) []any { + if apiObjects == nil || len(*apiObjects) == 0 { return nil } var tfList []any - for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - + for _, apiObject := range *apiObjects { tfList = append(tfList, flattenGCPEndpoint(apiObject)) } diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go index 5fd5088eff..1d7cf7ef72 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go @@ -1,63 +1,12 @@ package privatelinkendpointservice_test import ( - "fmt" - "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/plancheck" - "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" ) -func TestMigNetworkRSPrivateLinkEndpointService_Complete(t *testing.T) { - acc.SkipTestForCI(t) // needs AWS configuration - - var ( - resourceSuffix = "test" - resourceName = fmt.Sprintf("mongodbatlas_privatelink_endpoint_service.%s", resourceSuffix) - - awsAccessKey = os.Getenv("AWS_ACCESS_KEY_ID") - awsSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY") - - providerName = "AWS" - projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - region = os.Getenv("AWS_REGION") - vpcID = os.Getenv("AWS_VPC_ID") - subnetID = os.Getenv("AWS_SUBNET_ID") - securityGroupID = os.Getenv("AWS_SECURITY_GROUP_ID") - ) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, - CheckDestroy: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy, - Steps: []resource.TestStep{ - { - ExternalProviders: mig.ExternalProvidersWithAWS(), - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS( - awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, - ), - Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), - resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), - ), - }, - { - ExternalProviders: acc.ExternalProvidersOnlyAWS(), - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS( - awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, - ), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, - }, - }) +func TestMigNetworkNetworkPeering_basicAWS(t *testing.T) { + // can only be one privatelinkendpointservice per project + mig.CreateTestAndRunUseExternalProviderNonParallel(t, basicAWSTestCase(t), mig.ExternalProvidersWithAWS(), nil) } diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go index 69547803a0..4a5162a421 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go @@ -13,11 +13,17 @@ import ( ) func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { - acc.SkipTestForCI(t) // needs AWS configuration + testCase := basicAWSTestCase(t) + resource.Test(t, *testCase) +} +func basicAWSTestCase(tb testing.TB) *resource.TestCase { + tb.Helper() + acc.SkipTestForCI(tb) // needs AWS configuration var ( resourceSuffix = "test" resourceName = fmt.Sprintf("mongodbatlas_privatelink_endpoint_service.%s", resourceSuffix) + datasourceName = fmt.Sprintf("data.mongodbatlas_privatelink_endpoint_service.%s", resourceSuffix) awsAccessKey = os.Getenv("AWS_ACCESS_KEY_ID") awsSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY") @@ -28,37 +34,36 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { vpcID = os.Getenv("AWS_VPC_ID") subnetID = os.Getenv("AWS_SUBNET_ID") securityGroupID = os.Getenv("AWS_SECURITY_GROUP_ID") + checkAttrs = []string{"project_id", "private_link_id", "endpoint_service_id"} ) + checks := []resource.TestCheckFunc{checkExists(resourceName)} + checks = acc.AddAttrSetChecks(resourceName, checks, checkAttrs...) + checks = acc.AddAttrSetChecks(datasourceName, checks, checkAttrs...) - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, - CheckDestroy: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy, + return &resource.TestCase{ + PreCheck: func() { acc.PreCheck(tb); acc.PreCheckAwsEnvPrivateLinkEndpointService(tb) }, + CheckDestroy: checkDestroy, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, ExternalProviders: acc.ExternalProvidersOnlyAWS(), Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS( + Config: configCompleteAWS( awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, ), - Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), - resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), - ), + Check: resource.ComposeTestCheckFunc(checks...), }, { ResourceName: resourceName, - ImportStateIdFunc: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceImportStateIDFunc(resourceName), + ImportStateIdFunc: importStateIDFunc(resourceName), ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"private_link_id"}, }, }, - }) + } } -func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceImportStateIDFunc(resourceName string) resource.ImportStateIdFunc { +func importStateIDFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -71,7 +76,7 @@ func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceImportStateIDFunc(resourc } } -func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName string) resource.TestCheckFunc { +func checkExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -81,7 +86,7 @@ func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName strin return fmt.Errorf("no ID is set") } ids := conversion.DecodeStateID(rs.Primary.ID) - _, _, err := acc.Conn().PrivateEndpoints.GetOnePrivateEndpoint(context.Background(), ids["project_id"], ids["provider_name"], ids["private_link_id"], ids["endpoint_service_id"]) + _, _, err := acc.ConnV2().PrivateEndpointServicesApi.GetPrivateEndpoint(context.Background(), ids["project_id"], ids["provider_name"], ids["endpoint_service_id"], ids["private_link_id"]).Execute() if err == nil { return nil } @@ -90,13 +95,13 @@ func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName strin } } -func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy(s *terraform.State) error { +func checkDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "mongodbatlas_privatelink_endpoint_service" { continue } ids := conversion.DecodeStateID(rs.Primary.ID) - _, _, err := acc.Conn().PrivateEndpoints.GetOnePrivateEndpoint(context.Background(), ids["project_id"], ids["provider_name"], ids["private_link_id"], ids["endpoint_service_id"]) + _, _, err := acc.ConnV2().PrivateEndpointServicesApi.GetPrivateEndpoint(context.Background(), ids["project_id"], ids["provider_name"], ids["endpoint_service_id"], ids["private_link_id"]).Execute() if err == nil { return fmt.Errorf("the MongoDB Private Endpoint(%s) still exists", ids["endpoint_service_id"]) } @@ -104,7 +109,7 @@ func testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy(s *terraform.Stat return nil } -func testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS(awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, serviceResourceName string) string { +func configCompleteAWS(awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix string) string { return fmt.Sprintf(` provider "aws" { region = "%[5]s" @@ -129,9 +134,16 @@ func testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS(awsAccessKey resource "mongodbatlas_privatelink_endpoint_service" %[9]q { project_id = mongodbatlas_privatelink_endpoint.test.project_id - endpoint_service_id = aws_vpc_endpoint.ptfe_service.id + endpoint_service_id = aws_vpc_endpoint.ptfe_service.id private_link_id = mongodbatlas_privatelink_endpoint.test.id provider_name = "%[4]s" } - `, awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, serviceResourceName) + + data "mongodbatlas_privatelink_endpoint_service" %[9]q { + project_id = %[3]q + private_link_id = mongodbatlas_privatelink_endpoint_service.%[9]s.private_link_id + endpoint_service_id = mongodbatlas_privatelink_endpoint_service.%[9]s.endpoint_service_id + provider_name = "%[4]s" + } + `, awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix) } diff --git a/internal/testutil/acc/pre_check.go b/internal/testutil/acc/pre_check.go index 9c8af6edfa..23e52636ce 100644 --- a/internal/testutil/acc/pre_check.go +++ b/internal/testutil/acc/pre_check.go @@ -187,6 +187,15 @@ func PreCheckAwsEnv(tb testing.TB) { } } +func PreCheckAwsEnvPrivateLinkEndpointService(tb testing.TB) { + tb.Helper() + if os.Getenv("AWS_ACCESS_KEY_ID") == "" || + os.Getenv("AWS_SECRET_ACCESS_KEY") == "" || + os.Getenv("AWS_VPC_ID") == "" { + tb.Fatal("`AWS_ACCESS_KEY_ID`, `AWS_VPC_ID` and `AWS_SECRET_ACCESS_KEY` must be set for acceptance testing") + } +} + func PreCheckRegularCredsAreEmpty(tb testing.TB) { tb.Helper() if os.Getenv("MONGODB_ATLAS_PUBLIC_KEY") != "" || os.Getenv("MONGODB_ATLAS_PRIVATE_KEY") != "" {