From 584553a7f2f1319af873a85b02149acf2dc12088 Mon Sep 17 00:00:00 2001 From: Oriol Arbusi Date: Mon, 29 Apr 2024 17:38:12 +0200 Subject: [PATCH 1/7] initial migration to new SDK --- ...ata_source_privatelink_endpoint_service.go | 18 +-- .../resource_privatelink_endpoint_service.go | 137 ++++++++---------- 2 files changed, 70 insertions(+), 85 deletions(-) diff --git a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go index e8860cae68..6372137ec2 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, privateLinkID, endpointServiceID).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/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index 66293aaaba..2be262795e 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -16,8 +16,7 @@ import ( "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 +28,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": { @@ -139,8 +138,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 +148,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 +176,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 +208,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 +220,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, privateLinkID, endpointServiceID).Execute() if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -232,37 +230,37 @@ 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 { + if err := d.Set("interface_endpoint_id", privateEndpoint.GetInterfaceEndpointId()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) } - if err := d.Set("private_endpoint_connection_name", privateEndpoint.PrivateEndpointConnectionName); err != nil { + if err := d.Set("private_endpoint_connection_name", privateEndpoint.GetPrivateEndpointConnectionName()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) } - if err := d.Set("private_endpoint_ip_address", privateEndpoint.PrivateEndpointIPAddress); err != nil { + if err := d.Set("private_endpoint_ip_address", privateEndpoint.GetPrivateEndpointIPAddress()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) } - if err := d.Set("private_endpoint_resource_id", privateEndpoint.PrivateEndpointResourceID); err != nil { + if err := d.Set("private_endpoint_resource_id", privateEndpoint.GetPrivateEndpointResourceId()); err != nil { return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) } @@ -275,7 +273,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 +281,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 +291,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, privateLinkID, endpointServiceID).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorEndpointDelete, endpointServiceID, err)) } @@ -302,7 +299,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 +329,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 +342,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, privateLinkID, endpointServiceID).Execute() if err != nil { return nil, fmt.Errorf(ErrorServiceEndpointRead, endpointServiceID, err) } @@ -376,9 +373,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, privateLinkID, endpointServiceID).Execute() if err != nil { if resp != nil && resp.StatusCode == 404 { return "", "DELETED", nil @@ -388,85 +385,73 @@ 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() + //TODO: this is not in the entity of the new SDK, should be? this exists in privatelink_endpoint resource + // tfMap["service_attachment_name"] = apiObject.ServiceAttachmentName 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)) } From fc68c6b0667b9612bc39fae51fe2cd1af9010d64 Mon Sep 17 00:00:00 2001 From: Oriol Arbusi Date: Tue, 30 Apr 2024 17:43:29 +0200 Subject: [PATCH 2/7] final refactors --- ...ata_source_privatelink_endpoint_service.go | 2 +- ...ource_privatelink_endpoint_service_test.go | 2 +- .../resource_privatelink_endpoint_service.go | 29 ++++++++++--------- ...atelink_endpoint_service_migration_test.go | 8 ++--- ...ource_privatelink_endpoint_service_test.go | 22 +++++++------- 5 files changed, 33 insertions(+), 30 deletions(-) diff --git a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go index 6372137ec2..ed7ce5255f 100644 --- a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service.go @@ -109,7 +109,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. endpointServiceID := conversion.GetEncodedID(d.Get("endpoint_service_id").(string), "endpoint_service_id") providerName := d.Get("provider_name").(string) - serviceEndpoint, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID).Execute() + serviceEndpoint, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return diag.FromErr(fmt.Errorf(ErrorServiceEndpointRead, 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 index f06c088bbc..678498eaff 100644 --- a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go +++ b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go @@ -34,7 +34,7 @@ func TestAccNetworkDSPrivateLinkEndpointServiceAWS_basic(t *testing.T) { awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, ), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index 2be262795e..d89a022420 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -13,6 +13,7 @@ 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" @@ -120,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"), }, }, }, @@ -220,7 +222,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di endpointServiceID := ids["endpoint_service_id"] providerName := ids["provider_name"] - privateEndpoint, resp, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(context.Background(), projectID, providerName, privateLinkID, endpointServiceID).Execute() + 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("") @@ -249,19 +251,19 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di } if err := d.Set("interface_endpoint_id", privateEndpoint.GetInterfaceEndpointId()); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "interface_endpoint_id", endpointServiceID, err)) } if err := d.Set("private_endpoint_connection_name", privateEndpoint.GetPrivateEndpointConnectionName()); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_connection_name", endpointServiceID, err)) } if err := d.Set("private_endpoint_ip_address", privateEndpoint.GetPrivateEndpointIPAddress()); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_ip_address", endpointServiceID, err)) } if err := d.Set("private_endpoint_resource_id", privateEndpoint.GetPrivateEndpointResourceId()); err != nil { - return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "connection_status", endpointServiceID, err)) + return diag.FromErr(fmt.Errorf(ErrorEndpointSetting, "private_endpoint_resource_id", endpointServiceID, err)) } if err := d.Set("endpoint_service_id", endpointServiceID); err != nil { @@ -291,7 +293,7 @@ func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag. providerName := ids["provider_name"] if endpointServiceID != "" { - _, _, err := connV2.PrivateEndpointServicesApi.DeletePrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID).Execute() + _, _, err := connV2.PrivateEndpointServicesApi.DeletePrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorEndpointDelete, endpointServiceID, err)) } @@ -342,7 +344,7 @@ func resourceImportState(ctx context.Context, d *schema.ResourceData, meta any) endpointServiceID := parts[2] providerName := parts[3] - _, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID).Execute() + _, _, err := connV2.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { return nil, fmt.Errorf(ErrorServiceEndpointRead, endpointServiceID, err) } @@ -375,7 +377,7 @@ func resourceImportState(ctx context.Context, d *schema.ResourceData, meta any) func resourceRefreshFunc(ctx context.Context, client *admin.APIClient, projectID, providerName, privateLinkID, endpointServiceID string) retry.StateRefreshFunc { return func() (any, string, error) { - i, resp, err := client.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, privateLinkID, endpointServiceID).Execute() + i, resp, err := client.PrivateEndpointServicesApi.GetPrivateEndpoint(ctx, projectID, providerName, endpointServiceID, privateLinkID).Execute() if err != nil { if resp != nil && resp.StatusCode == 404 { return "", "DELETED", nil @@ -438,14 +440,15 @@ func flattenGCPEndpoint(apiObject admin.GCPConsumerForwardingRule) map[string]an tfMap["endpoint_name"] = apiObject.GetEndpointName() tfMap["ip_address"] = apiObject.GetIpAddress() tfMap["status"] = apiObject.GetStatus() - //TODO: this is not in the entity of the new SDK, should be? this exists in privatelink_endpoint resource - // tfMap["service_attachment_name"] = apiObject.ServiceAttachmentName return tfMap } func flattenGCPEndpoints(apiObjects *[]admin.GCPConsumerForwardingRule) []any { - if apiObjects != nil && len(*apiObjects) == 0 { + if apiObjects == nil { + return nil + } + if len(*apiObjects) == 0 { return nil } 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..2f3eddc56b 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go @@ -31,15 +31,15 @@ func TestMigNetworkRSPrivateLinkEndpointService_Complete(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, - CheckDestroy: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy, + CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProvidersWithAWS(), - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS( + Config: configCompleteAWS( awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, ), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasPrivateLinkEndpointServiceExists(resourceName), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), @@ -48,7 +48,7 @@ func TestMigNetworkRSPrivateLinkEndpointService_Complete(t *testing.T) { { ExternalProviders: acc.ExternalProvidersOnlyAWS(), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceConfigCompleteAWS( + Config: configCompleteAWS( awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, ), ConfigPlanChecks: resource.ConfigPlanChecks{ diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go index 69547803a0..244b30071a 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go @@ -32,16 +32,16 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, - CheckDestroy: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceDestroy, + 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), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), @@ -49,7 +49,7 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { }, { ResourceName: resourceName, - ImportStateIdFunc: testAccCheckMongoDBAtlasPrivateLinkEndpointServiceImportStateIDFunc(resourceName), + ImportStateIdFunc: importStateIDFunc(resourceName), ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"private_link_id"}, @@ -58,7 +58,7 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { }) } -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 +71,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 +81,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 +90,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 +104,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, serviceResourceName string) string { return fmt.Sprintf(` provider "aws" { region = "%[5]s" @@ -129,7 +129,7 @@ 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" } From 13cc780d7a4b6ee04b9d4ca5bc977cb5e0a2e6c1 Mon Sep 17 00:00:00 2001 From: Oriol Arbusi Date: Tue, 30 Apr 2024 17:51:46 +0200 Subject: [PATCH 3/7] change precheck --- .../data_source_privatelink_endpoint_service_test.go | 2 +- ...source_privatelink_endpoint_service_migration_test.go | 2 +- .../resource_privatelink_endpoint_service_test.go | 2 +- internal/testutil/acc/pre_check.go | 9 +++++++++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go index 678498eaff..a9a096f89c 100644 --- a/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go +++ b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go @@ -26,7 +26,7 @@ func TestAccNetworkDSPrivateLinkEndpointServiceAWS_basic(t *testing.T) { securityGroupID := os.Getenv("AWS_SECURITY_GROUP_ID") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, + PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnvPrivateLinkEndpointService(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, Steps: []resource.TestStep{ { 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 2f3eddc56b..1befe9340d 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_migration_test.go @@ -30,7 +30,7 @@ func TestMigNetworkRSPrivateLinkEndpointService_Complete(t *testing.T) { ) resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, + PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnvPrivateLinkEndpointService(t) }, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go index 244b30071a..4256e5a3fe 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go @@ -31,7 +31,7 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { ) resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t) }, + PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnvPrivateLinkEndpointService(t) }, CheckDestroy: checkDestroy, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, ExternalProviders: acc.ExternalProvidersOnlyAWS(), 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") != "" { From 5fc6eb3a8986862acf476101ab0492abb46f2293 Mon Sep 17 00:00:00 2001 From: EspenAlbert Date: Thu, 2 May 2024 09:53:14 +0100 Subject: [PATCH 4/7] test: refactor data source test to resource --- ...ource_privatelink_endpoint_service_test.go | 83 ------------------- ...ource_privatelink_endpoint_service_test.go | 36 +++++--- 2 files changed, 24 insertions(+), 95 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_test.go b/internal/service/privatelinkendpointservice/data_source_privatelink_endpoint_service_test.go deleted file mode 100644 index a9a096f89c..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.PreCheckAwsEnvPrivateLinkEndpointService(t) }, - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Steps: []resource.TestStep{ - { - Config: testAccMongoDBAtlasPrivateLinkEndpointServiceDataSourceConfig( - awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, - ), - Check: resource.ComposeTestCheckFunc( - checkExists(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_test.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service_test.go index 4256e5a3fe..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,10 +34,14 @@ 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.PreCheckAwsEnvPrivateLinkEndpointService(t) }, + return &resource.TestCase{ + PreCheck: func() { acc.PreCheck(tb); acc.PreCheckAwsEnvPrivateLinkEndpointService(tb) }, CheckDestroy: checkDestroy, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, ExternalProviders: acc.ExternalProvidersOnlyAWS(), @@ -40,12 +50,7 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { Config: configCompleteAWS( awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, ), - Check: resource.ComposeTestCheckFunc( - checkExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "private_link_id"), - resource.TestCheckResourceAttrSet(resourceName, "endpoint_service_id"), - ), + Check: resource.ComposeTestCheckFunc(checks...), }, { ResourceName: resourceName, @@ -55,7 +60,7 @@ func TestAccNetworkRSPrivateLinkEndpointServiceAWS_Complete(t *testing.T) { ImportStateVerifyIgnore: []string{"private_link_id"}, }, }, - }) + } } func importStateIDFunc(resourceName string) resource.ImportStateIdFunc { @@ -104,7 +109,7 @@ func checkDestroy(s *terraform.State) error { return nil } -func configCompleteAWS(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" @@ -133,5 +138,12 @@ func configCompleteAWS(awsAccessKey, awsSecretKey, projectID, providerName, regi 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) } From e398e2a5da8641b941fc07b9d26383ba8bf00e6b Mon Sep 17 00:00:00 2001 From: EspenAlbert Date: Thu, 2 May 2024 10:18:27 +0100 Subject: [PATCH 5/7] test: add NonParallell for CreateTestAndRunUseExternalProvider --- internal/testutil/mig/test_case.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/testutil/mig/test_case.go b/internal/testutil/mig/test_case.go index af9c7d118a..1e400b09ca 100644 --- a/internal/testutil/mig/test_case.go +++ b/internal/testutil/mig/test_case.go @@ -27,6 +27,12 @@ func CreateTestAndRunUseExternalProvider(t *testing.T, test *resource.TestCase, resource.ParallelTest(t, CreateTestUseExternalProvider(t, test, externalProviders, additionalProviders)) } +func CreateTestAndRunUseExternalProviderNonParallel(t *testing.T, test *resource.TestCase, externalProviders, additionalProviders map[string]resource.ExternalProvider) { + t.Helper() + acc.SkipInUnitTest(t) // Migration tests create external resources and use MONGODB_ATLAS_LAST_VERSION env-var. + resource.Test(t, CreateTestUseExternalProvider(t, test, externalProviders, additionalProviders)) +} + // CreateTest returns a new TestCase that reuses step 1 and adds a TestStepCheckEmptyPlan. // Requires: `MONGODB_ATLAS_LAST_VERSION` to be present. func CreateTest(t *testing.T, test *resource.TestCase) resource.TestCase { From a1db931f80eef64a1236de10f755527fe10b6f85 Mon Sep 17 00:00:00 2001 From: EspenAlbert Date: Thu, 2 May 2024 10:26:17 +0100 Subject: [PATCH 6/7] test: reuse test case for migration test --- ...atelink_endpoint_service_migration_test.go | 57 +------------------ 1 file changed, 3 insertions(+), 54 deletions(-) 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 1befe9340d..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.PreCheckAwsEnvPrivateLinkEndpointService(t) }, - CheckDestroy: checkDestroy, - Steps: []resource.TestStep{ - { - ExternalProviders: mig.ExternalProvidersWithAWS(), - Config: configCompleteAWS( - awsAccessKey, awsSecretKey, projectID, providerName, region, vpcID, subnetID, securityGroupID, resourceSuffix, - ), - Check: resource.ComposeTestCheckFunc( - checkExists(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: configCompleteAWS( - 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) } From cd6309547fb8c3c4c14448bc897dd20cd707c24c Mon Sep 17 00:00:00 2001 From: EspenAlbert Date: Fri, 3 May 2024 08:58:25 +0100 Subject: [PATCH 7/7] refactor: apply suggestion --- .../resource_privatelink_endpoint_service.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index d89a022420..e0e7f15dfa 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -445,10 +445,7 @@ func flattenGCPEndpoint(apiObject admin.GCPConsumerForwardingRule) map[string]an } func flattenGCPEndpoints(apiObjects *[]admin.GCPConsumerForwardingRule) []any { - if apiObjects == nil { - return nil - } - if len(*apiObjects) == 0 { + if apiObjects == nil || len(*apiObjects) == 0 { return nil }