Skip to content

Commit

Permalink
feat: Adds auto_indexing attribute to resource_serverless_instance (
Browse files Browse the repository at this point in the history
#2100)

* auto_indexing in data sources

* auto_indexing in resource

* doc

* refactor tests

* test for auto_indexing

* doc change

* fix doc

* simplify test

* fix test

* auto_indexing in its test
  • Loading branch information
lantoli authored Apr 1, 2024
1 parent 107c4b1 commit fa8aa89
Show file tree
Hide file tree
Showing 11 changed files with 180 additions and 164 deletions.
Original file line number Diff line number Diff line change
@@ -1,36 +1,11 @@
package privatelinkendpointserverless_test

import (
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig"
)

func TestMigServerlessPrivateLinkEndpoint_basic(t *testing.T) {
var (
resourceName = "mongodbatlas_privatelink_endpoint_serverless.test"
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID")
projectName = acc.RandomProjectName()
instanceName = acc.RandomClusterName()
config = configBasic(orgID, projectName, instanceName, true)
)

resource.Test(t, resource.TestCase{
PreCheck: func() { mig.PreCheckBasic(t) },
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
ExternalProviders: mig.ExternalProviders(),
Config: config,
Check: resource.ComposeTestCheckFunc(
checkExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "instance_name", instanceName),
),
},
mig.TestStepCheckEmptyPlan(config),
},
})
mig.CreateAndRunTest(t, basicTestCase(t))
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package privatelinkendpointserverless_test
import (
"context"
"fmt"
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
Expand All @@ -12,58 +11,44 @@ import (
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
)

func TestAccServerlessPrivateLinkEndpoint_basic(t *testing.T) {
var (
resourceName = "mongodbatlas_privatelink_endpoint_serverless.test"
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID")
projectName = acc.RandomProjectName()
instanceName = acc.RandomClusterName()
)
const (
resourceName = "mongodbatlas_privatelink_endpoint_serverless.test"
)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acc.PreCheckBasic(t) },
ProtoV6ProviderFactories: acc.TestAccProviderV6Factories,
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
Config: configBasic(orgID, projectName, instanceName, true),
Check: resource.ComposeTestCheckFunc(
checkExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "instance_name", instanceName),
),
},
},
})
func TestAccServerlessPrivateLinkEndpoint_basic(t *testing.T) {
resource.ParallelTest(t, *basicTestCase(t))
}

func TestAccServerlessPrivateLinkEndpoint_importBasic(t *testing.T) {
func basicTestCase(tb testing.TB) *resource.TestCase {
tb.Helper()

var (
resourceName = "mongodbatlas_privatelink_endpoint_serverless.test"
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID")
projectName = acc.RandomProjectName()
projectID = acc.ProjectIDExecution(tb)
instanceName = acc.RandomClusterName()
)
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acc.PreCheckBasic(t) },

return &resource.TestCase{
PreCheck: func() { acc.PreCheckBasic(tb) },
ProtoV6ProviderFactories: acc.TestAccProviderV6Factories,
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
Config: configBasic(orgID, projectName, instanceName, true),
Config: configBasic(projectID, instanceName, true),
Check: resource.ComposeTestCheckFunc(
checkExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "instance_name", instanceName),
),
},
{
Config: configBasic(orgID, projectName, instanceName, false),
Config: configBasic(projectID, instanceName, false),
ResourceName: resourceName,
ImportStateIdFunc: importStateIDFuncBasic(resourceName),
ImportStateIdFunc: importStateIDFunc(resourceName),
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"connection_strings_private_endpoint_srv"},
},
},
})
}
}

func checkDestroy(state *terraform.State) error {
Expand All @@ -80,7 +65,7 @@ func checkDestroy(state *terraform.State) error {
return nil
}

func configBasic(orgID, projectName, instanceName string, ignoreConnectionStrings bool) string {
func configBasic(projectID, instanceName string, ignoreConnectionStrings bool) string {
return fmt.Sprintf(`
resource "mongodbatlas_privatelink_endpoint_serverless" "test" {
Expand All @@ -90,7 +75,7 @@ func configBasic(orgID, projectName, instanceName string, ignoreConnectionString
}
%s
`, acc.ConfigServerlessInstanceBasic(orgID, projectName, instanceName, ignoreConnectionStrings))
`, acc.ConfigServerlessInstance(projectID, instanceName, ignoreConnectionStrings, nil, nil))
}

func checkExists(resourceName string) resource.TestCheckFunc {
Expand All @@ -111,7 +96,7 @@ func checkExists(resourceName string) resource.TestCheckFunc {
}
}

func importStateIDFuncBasic(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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ func dataSourceSchema() map[string]*schema.Schema {
Optional: true,
Computed: true,
},
"auto_indexing": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"tags": &advancedcluster.DSTagsSchema,
}
}
Expand Down Expand Up @@ -160,6 +165,15 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.
if err := d.Set("continuous_backup_enabled", instance.ServerlessBackupOptions.GetServerlessContinuousBackupEnabled()); err != nil {
return diag.Errorf(errorServerlessInstanceSetting, "continuous_backup_enabled", d.Id(), err)
}

autoIndexing, _, err := connV2.PerformanceAdvisorApi.GetServerlessAutoIndexing(ctx, projectID.(string), instanceName.(string)).Execute()
if err != nil {
return diag.Errorf("error getting serverless instance information for auto_indexing: %s", err)
}
if err := d.Set("auto_indexing", autoIndexing); err != nil {
return diag.Errorf(errorServerlessInstanceSetting, "auto_indexing", d.Id(), err)
}

if err := d.Set("tags", conversion.FlattenTags(instance.GetTags())); err != nil {
return diag.Errorf(advancedcluster.ErrorClusterAdvancedSetting, "tags", d.Id(), err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,29 @@ func PluralDataSource() *schema.Resource {

func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
projectID, projectIDOK := d.GetOk("project_id")
projectIDValue, projectIDOK := d.GetOk("project_id")
if !(projectIDOK) {
return diag.Errorf("project_id must be configured")
}
projectID := projectIDValue.(string)
options := &admin.ListServerlessInstancesApiParams{
ItemsPerPage: conversion.IntPtr(500),
IncludeCount: conversion.Pointer(true),
GroupId: projectID.(string),
GroupId: projectID,
}

serverlessInstances, err := getServerlessList(ctx, connV2, options, 0)
if err != nil {
return diag.Errorf("error getting serverless instances information: %s", err)
}

flatServerlessInstances := flattenServerlessInstances(serverlessInstances)
autoIndexingList := make([]bool, len(serverlessInstances))
for i := range serverlessInstances {
resp, _, _ := connV2.PerformanceAdvisorApi.GetServerlessAutoIndexing(ctx, projectID, serverlessInstances[i].GetName()).Execute()
autoIndexingList[i] = resp
}

flatServerlessInstances := flattenServerlessInstances(serverlessInstances, autoIndexingList)
if err := d.Set("results", flatServerlessInstances); err != nil {
return diag.Errorf("error setting `results` for serverless instances: %s", err)
}
Expand Down Expand Up @@ -82,7 +89,7 @@ func getServerlessList(ctx context.Context, connV2 *admin.APIClient, options *ad
return list, nil
}

func flattenServerlessInstances(serverlessInstances []admin.ServerlessInstanceDescription) []map[string]any {
func flattenServerlessInstances(serverlessInstances []admin.ServerlessInstanceDescription, autoIndexingList []bool) []map[string]any {
var serverlessInstancesMap []map[string]any
if len(serverlessInstances) == 0 {
return nil
Expand All @@ -104,6 +111,7 @@ func flattenServerlessInstances(serverlessInstances []admin.ServerlessInstanceDe
"termination_protection_enabled": serverlessInstances[i].GetTerminationProtectionEnabled(),
"continuous_backup_enabled": serverlessInstances[i].ServerlessBackupOptions.GetServerlessContinuousBackupEnabled(),
"tags": conversion.FlattenTags(serverlessInstances[i].GetTags()),
"auto_indexing": autoIndexingList[i],
}
}
return serverlessInstancesMap
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ func resourceSchema() map[string]*schema.Schema {
Optional: true,
Computed: true,
},
"auto_indexing": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"tags": &advancedcluster.RSTagsSchema,
}
}
Expand Down Expand Up @@ -164,6 +169,18 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.
return diag.Errorf("error creating MongoDB Serverless Instance: %s", err)
}

if _, ok := d.GetOkExists("auto_indexing"); ok {
params := &admin.SetServerlessAutoIndexingApiParams{
GroupId: projectID,
ClusterName: name,
Enable: conversion.Pointer(d.Get("auto_indexing").(bool)),
}
_, _, err := connV2.PerformanceAdvisorApi.SetServerlessAutoIndexingWithParams(ctx, params).Execute()
if err != nil {
return diag.Errorf("error creating MongoDB Serverless Instance setting auto_indexing: %s", err)
}
}

d.SetId(conversion.EncodeStateID(map[string]string{
"project_id": projectID,
"name": name,
Expand Down Expand Up @@ -240,14 +257,22 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di
return diag.Errorf(errorServerlessInstanceSetting, "tags", d.Id(), err)
}

autoIndexing, _, err := connV2.PerformanceAdvisorApi.GetServerlessAutoIndexing(ctx, projectID, instanceName).Execute()
if err != nil {
return diag.Errorf("error getting serverless instance information for auto_indexing: %s", err)
}
if err := d.Set("auto_indexing", autoIndexing); err != nil {
return diag.Errorf(errorServerlessInstanceSetting, "auto_indexing", d.Id(), err)
}

return nil
}

func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
ids := conversion.DecodeStateID(d.Id())
projectID := ids["project_id"]
instanceName := ids["name"]
name := ids["name"]

if d.HasChange("termination_protection_enabled") || d.HasChange("continuous_backup_enabled") || d.HasChange("tags") {
serverlessBackupOptions := &admin.ClusterServerlessBackupOptions{
Expand All @@ -263,7 +288,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.
params.Tags = conversion.ExpandTagsFromSetSchema(d)
}

_, _, err := connV2.ServerlessInstancesApi.UpdateServerlessInstance(ctx, projectID, instanceName, params).Execute()
_, _, err := connV2.ServerlessInstancesApi.UpdateServerlessInstance(ctx, projectID, name, params).Execute()
if err != nil {
return diag.Errorf("error updating serverless instance: %s", err)
}
Expand All @@ -282,6 +307,19 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.
return diag.Errorf("error updating MongoDB Serverless Instance: %s", err)
}
}

if d.HasChange("auto_indexing") {
params := &admin.SetServerlessAutoIndexingApiParams{
GroupId: projectID,
ClusterName: name,
Enable: conversion.Pointer(d.Get("auto_indexing").(bool)),
}
_, _, err := connV2.PerformanceAdvisorApi.SetServerlessAutoIndexingWithParams(ctx, params).Execute()
if err != nil {
return diag.Errorf("error updating MongoDB Serverless Instance setting auto_indexing: %s", err)
}
}

return resourceRead(ctx, d, meta)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,11 @@
package serverlessinstance_test

import (
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig"
)

func TestMigServerlessInstance_basic(t *testing.T) {
var (
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID")
projectName = acc.RandomProjectName()
instanceName = acc.RandomClusterName()
config = acc.ConfigServerlessInstanceBasic(orgID, projectName, instanceName, true)
)
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { mig.PreCheckBasic(t) },
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
ExternalProviders: mig.ExternalProviders(),
Config: config,
Check: resource.ComposeTestCheckFunc(
checkConnectionStringPrivateEndpointIsPresentWithNoElement(resourceName),
checkExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", instanceName),
resource.TestCheckResourceAttr(resourceName, "termination_protection_enabled", "false"),
),
},
mig.TestStepCheckEmptyPlan(config),
},
})
mig.CreateAndRunTest(t, basicTestCase(t, mig.ProjectIDGlobal(t)))
}
Loading

0 comments on commit fa8aa89

Please sign in to comment.