Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implements mongodbatlas_flex_cluster plural data source #2767

Merged
merged 10 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/2767.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-datasource
mongodbatlas_flex_clusters
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,7 @@ func (p *MongodbtlasProvider) DataSources(context.Context) []func() datasource.D
resourcepolicy.DataSource,
resourcepolicy.PluralDataSource,
flexcluster.DataSource,
flexcluster.PluralDataSource,
} // Data sources not yet in GA
if providerEnablePreview {
dataSources = append(dataSources, previewDataSources...)
Expand Down
19 changes: 19 additions & 0 deletions internal/service/flexcluster/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,25 @@ func NewTFModel(ctx context.Context, apiResp *admin.FlexClusterDescription202411
}, nil
}

func NewTFModelDSP(ctx context.Context, projectID string, input *admin.PaginatedFlexClusters20241113) (*TFModelDSP, diag.Diagnostics) {
diags := &diag.Diagnostics{}
results := input.GetResults()
tfModels := make([]TFModel, len(results))
for i := range results {
item := &results[i]
tfModel, diagsLocal := NewTFModel(ctx, item)
diags.Append(diagsLocal...)
tfModels[i] = *tfModel
AgustinBettati marked this conversation as resolved.
Show resolved Hide resolved
}
if diags.HasError() {
return nil, *diags
}
return &TFModelDSP{
ProjectId: types.StringValue(projectID),
Results: tfModels,
}, *diags
}

func NewAtlasCreateReq(ctx context.Context, plan *TFModel) (*admin.FlexClusterDescriptionCreate20241113, diag.Diagnostics) {
providerSettings := &TFProviderSettings{}
if diags := plan.ProviderSettings.As(ctx, providerSettings, basetypes.ObjectAsOptions{}); diags.HasError() {
Expand Down
133 changes: 133 additions & 0 deletions internal/service/flexcluster/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ type NewTFModelTestCase struct {
expectedTFModel *flexcluster.TFModel
}

type NewTFModelDSPTestCase struct {
input *admin.PaginatedFlexClusters20241113
expectedTFModelDSP *flexcluster.TFModelDSP
}

type NewAtlasCreateReqTestCase struct {
input *flexcluster.TFModel
expectedSDKReq *admin.FlexClusterDescriptionCreate20241113
Expand Down Expand Up @@ -164,6 +169,134 @@ func TestNewTFModel(t *testing.T) {
}
}

func TestNewTFModelDSP(t *testing.T) {
testCases := map[string]NewTFModelDSPTestCase{
"Complete TF state": {
expectedTFModelDSP: &flexcluster.TFModelDSP{
ProjectId: types.StringValue(projectID),
Results: []flexcluster.TFModel{
{
ProjectId: types.StringValue(projectID),
Id: types.StringValue(id),
Tags: types.MapValueMust(types.StringType, map[string]attr.Value{
key1: types.StringValue(value1),
}),
ProviderSettings: *providerSettingsObject,
ConnectionStrings: *connectionStringsObject,
CreateDate: types.StringValue(createDate),
MongoDbversion: types.StringValue(mongoDBVersion),
Name: types.StringValue(name),
ClusterType: types.StringValue(clusterType),
StateName: types.StringValue(stateName),
VersionReleaseSystem: types.StringValue(versionReleaseSystem),
BackupSettings: *backupSettingsObject,
TerminationProtectionEnabled: types.BoolValue(terminationProtectionEnabled),
},
{
ProjectId: types.StringValue(projectID),
Id: types.StringValue("id-2"),
Tags: types.MapValueMust(types.StringType, map[string]attr.Value{
key1: types.StringValue(value1),
}),
ProviderSettings: *providerSettingsObject,
ConnectionStrings: *connectionStringsObject,
CreateDate: types.StringValue(createDate),
MongoDbversion: types.StringValue(mongoDBVersion),
Name: types.StringValue(name),
ClusterType: types.StringValue(clusterType),
StateName: types.StringValue(stateName),
VersionReleaseSystem: types.StringValue(versionReleaseSystem),
BackupSettings: *backupSettingsObject,
TerminationProtectionEnabled: types.BoolValue(terminationProtectionEnabled),
},
},
},
input: &admin.PaginatedFlexClusters20241113{
Results: &[]admin.FlexClusterDescription20241113{
{
GroupId: &projectID,
Id: &id,
Tags: &[]admin.ResourceTag{
{
Key: key1,
Value: value1,
},
},
ProviderSettings: admin.FlexProviderSettings20241113{
ProviderName: &providerName,
RegionName: &regionName,
BackingProviderName: &backingProviderName,
DiskSizeGB: &diskSizeGb,
},
ConnectionStrings: &admin.FlexConnectionStrings20241113{
Standard: &standardConnectionString,
StandardSrv: &standardSrvConnectionString,
},
CreateDate: &createDateTime,
MongoDBVersion: &mongoDBVersion,
Name: &name,
ClusterType: &clusterType,
StateName: &stateName,
VersionReleaseSystem: &versionReleaseSystem,
BackupSettings: &admin.FlexBackupSettings20241113{
Enabled: conversion.Pointer(true),
},
TerminationProtectionEnabled: &terminationProtectionEnabled,
},
{
GroupId: &projectID,
Id: conversion.StringPtr("id-2"),
Tags: &[]admin.ResourceTag{
{
Key: key1,
Value: value1,
},
},
ProviderSettings: admin.FlexProviderSettings20241113{
ProviderName: &providerName,
RegionName: &regionName,
BackingProviderName: &backingProviderName,
DiskSizeGB: &diskSizeGb,
},
ConnectionStrings: &admin.FlexConnectionStrings20241113{
Standard: &standardConnectionString,
StandardSrv: &standardSrvConnectionString,
},
CreateDate: &createDateTime,
MongoDBVersion: &mongoDBVersion,
Name: &name,
ClusterType: &clusterType,
StateName: &stateName,
VersionReleaseSystem: &versionReleaseSystem,
BackupSettings: &admin.FlexBackupSettings20241113{
Enabled: conversion.Pointer(true),
},
TerminationProtectionEnabled: &terminationProtectionEnabled,
},
},
},
},
"No Flex Clusters": {
expectedTFModelDSP: &flexcluster.TFModelDSP{
ProjectId: types.StringValue(projectID),
Results: []flexcluster.TFModel{},
},
input: &admin.PaginatedFlexClusters20241113{
Results: &[]admin.FlexClusterDescription20241113{},
},
},
}
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
tfModelDSP, diags := flexcluster.NewTFModelDSP(context.Background(), projectID, tc.input)
if diags.HasError() {
t.Errorf("unexpected errors found: %s", diags.Errors()[0].Summary())
}
assert.Equal(t, tc.expectedTFModelDSP, tfModelDSP, "created TF model DSP did not match expected output")
})
}
}

func TestNewAtlasCreateReq(t *testing.T) {
testCases := map[string]NewAtlasCreateReqTestCase{
"Complete TF state": {
Expand Down
51 changes: 51 additions & 0 deletions internal/service/flexcluster/plural_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package flexcluster

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
)

var _ datasource.DataSource = &pluralDS{}
var _ datasource.DataSourceWithConfigure = &pluralDS{}

func PluralDataSource() datasource.DataSource {
return &pluralDS{
DSCommon: config.DSCommon{
DataSourceName: fmt.Sprintf("%ss", resourceName),
},
}
}

type pluralDS struct {
config.DSCommon
}

func (d *pluralDS) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = PluralDataSourceSchema(ctx)
}

func (d *pluralDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var tfModel TFModelDSP
resp.Diagnostics.Append(req.Config.Get(ctx, &tfModel)...)
if resp.Diagnostics.HasError() {
return
}

connV2 := d.Client.AtlasV2
apiResp, _, err := connV2.FlexClustersApi.ListFlexClusters(ctx, tfModel.ProjectId.ValueString()).Execute()
AgustinBettati marked this conversation as resolved.
Show resolved Hide resolved

if err != nil {
resp.Diagnostics.AddError("error reading plural data source", err.Error())
return
}

newFlexClustersModel, diags := NewTFModelDSP(ctx, tfModel.ProjectId.ValueString(), apiResp)
if diags.HasError() {
resp.Diagnostics.Append(diags...)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, newFlexClustersModel)...)
}
8 changes: 4 additions & 4 deletions internal/service/flexcluster/plural_data_source_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types"
)

func DataSourcePluralSchema(ctx context.Context) schema.Schema {
func PluralDataSourceSchema(ctx context.Context) schema.Schema {
return schema.Schema{
Attributes: map[string]schema.Attribute{
"project_id": schema.StringAttribute{
Required: true,
MarkdownDescription: "Unique 24-hexadecimal digit string that identifies your project. Use the [/groups](#tag/Projects/operation/listProjects) endpoint to retrieve all projects to which the authenticated user has access.\n\n**NOTE**: Groups and projects are synonymous terms. Your group id is the same as your project id. For existing groups, your group/project id remains the same. The resource and corresponding endpoints use the term groups.",
},
"flex_clusters": schema.ListNestedAttribute{
"results": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: dataSourceSchema(true),
Expand All @@ -26,6 +26,6 @@ func DataSourcePluralSchema(ctx context.Context) schema.Schema {
}

type TFModelDSP struct {
ProjectId types.String `tfsdk:"project_id"`
FlexClusters []TFModel `tfsdk:"flex_clusters"`
ProjectId types.String `tfsdk:"project_id"`
Results []TFModel `tfsdk:"results"`
}
38 changes: 24 additions & 14 deletions internal/service/flexcluster/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,20 @@ import (
)

var (
resourceType = "mongodbatlas_flex_cluster"
resourceName = "mongodbatlas_flex_cluster.test"
dataSourceName = "data.mongodbatlas_flex_cluster.test"
resourceType = "mongodbatlas_flex_cluster"
resourceName = "mongodbatlas_flex_cluster.test"
dataSourceName = "data.mongodbatlas_flex_cluster.test"
dataSourcePluralName = "data.mongodbatlas_flex_clusters.test"
)

func TestAccFlexClusterRS_basic(t *testing.T) {
tc := basicTestCase(t)
resource.ParallelTest(t, *tc)
resource.Test(t, *tc)
AgustinBettati marked this conversation as resolved.
Show resolved Hide resolved
}

func TestAccFlexClusterRS_failedUpdate(t *testing.T) {
tc := failedUpdateTestCase(t)
resource.ParallelTest(t, *tc)
resource.Test(t, *tc)
}

func basicTestCase(t *testing.T) *resource.TestCase {
Expand All @@ -43,11 +44,11 @@ func basicTestCase(t *testing.T) *resource.TestCase {
Steps: []resource.TestStep{
{
Config: configBasic(projectID, clusterName, provider, region, true),
Check: checksFlexCluster(projectID, clusterName, true),
Check: checksFlexCluster(projectID, clusterName, true, 1),
},
{
Config: configBasic(projectID, clusterName, provider, region, false),
Check: checksFlexCluster(projectID, clusterName, false),
Check: checksFlexCluster(projectID, clusterName, false, 1),
},
{
Config: configBasic(projectID, clusterName, provider, region, true),
Expand Down Expand Up @@ -79,7 +80,7 @@ func failedUpdateTestCase(t *testing.T) *resource.TestCase {
Steps: []resource.TestStep{
{
Config: configBasic(projectID, clusterName, provider, region, false),
Check: checksFlexCluster(projectID, clusterName, false),
Check: checksFlexCluster(projectID, clusterName, false, 1),
},
{
Config: configBasic(projectID, clusterNameUpdated, provider, region, false),
Expand Down Expand Up @@ -115,16 +116,23 @@ func configBasic(projectID, clusterName, provider, region string, terminationPro
data "mongodbatlas_flex_cluster" "test" {
project_id = mongodbatlas_flex_cluster.test.project_id
name = mongodbatlas_flex_cluster.test.name
}
data "mongodbatlas_flex_clusters" "test" {
project_id = mongodbatlas_flex_cluster.test.project_id
}`, projectID, clusterName, provider, region, terminationProtectionEnabled)
}

func checksFlexCluster(projectID, clusterName string, terminationProtectionEnabled bool) resource.TestCheckFunc {
func checksFlexCluster(projectID, clusterName string, terminationProtectionEnabled bool, flexClusterCount int) resource.TestCheckFunc {
checks := []resource.TestCheckFunc{checkExists()}
attrMap := map[string]string{
"project_id": projectID,
"name": clusterName,
"termination_protection_enabled": fmt.Sprintf("%v", terminationProtectionEnabled),
}
pluralMap := map[string]string{
"project_id": projectID,
"results.#": "1",
AgustinBettati marked this conversation as resolved.
Show resolved Hide resolved
}
attrSet := []string{
"backup_settings.enabled",
"cluster_type",
Expand All @@ -136,11 +144,13 @@ func checksFlexCluster(projectID, clusterName string, terminationProtectionEnabl
"version_release_system",
"provider_settings.provider_name",
}
checks = acc.AddAttrChecks(resourceName, checks, attrMap)
checks = acc.AddAttrChecks(dataSourceName, checks, attrMap)
checks = acc.AddAttrSetChecks(resourceName, checks, attrSet...)
checks = acc.AddAttrSetChecks(dataSourceName, checks, attrSet...)
return resource.ComposeAggregateTestCheckFunc(checks...)
checks = acc.AddAttrChecks(dataSourcePluralName, checks, pluralMap)
for i := 0; i < flexClusterCount; i++ {
checks = acc.AddAttrSetChecks(resourceName, checks, "name", "termination_protection_enabled")
checks = acc.AddAttrSetChecks(dataSourceName, checks, "id")
checks = acc.AddAttrSetChecks(dataSourcePluralName, checks, "results.0.id")
}
AgustinBettati marked this conversation as resolved.
Show resolved Hide resolved
return acc.CheckRSAndDS(resourceName, &dataSourceName, &dataSourcePluralName, attrSet, attrMap, resource.ComposeAggregateTestCheckFunc(checks...))
}

func checkExists() resource.TestCheckFunc {
Expand Down