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 all 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
20 changes: 20 additions & 0 deletions internal/service/flexcluster/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,26 @@ func NewTFModel(ctx context.Context, apiResp *admin.FlexClusterDescription202411
}, nil
}

func NewTFModelDSP(ctx context.Context, projectID string, input []admin.FlexClusterDescription20241113) (*TFModelDSP, diag.Diagnostics) {
diags := &diag.Diagnostics{}
tfModels := make([]TFModel, len(input))
for i := range input {
item := &input[i]
tfModel, diagsLocal := NewTFModel(ctx, item)
diags.Append(diagsLocal...)
if tfModel != nil {
tfModels[i] = *tfModel
}
}
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
131 changes: 130 additions & 1 deletion internal/service/flexcluster/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,13 @@ var (
)

type NewTFModelTestCase struct {
input *admin.FlexClusterDescription20241113
expectedTFModel *flexcluster.TFModel
input *admin.FlexClusterDescription20241113
}

type NewTFModelDSPTestCase struct {
expectedTFModelDSP *flexcluster.TFModelDSP
input []admin.FlexClusterDescription20241113
}

type NewAtlasCreateReqTestCase struct {
Expand Down Expand Up @@ -164,6 +169,130 @@ 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.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.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
63 changes: 63 additions & 0 deletions internal/service/flexcluster/plural_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package flexcluster

import (
"context"
"fmt"
"net/http"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/dsschema"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"go.mongodb.org/atlas-sdk/v20241023001/admin"
)

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

params := admin.ListFlexClustersApiParams{
GroupId: tfModel.ProjectId.ValueString(),
}

sdkProcessors, err := dsschema.AllPages(ctx, func(ctx context.Context, pageNum int) (dsschema.PaginateResponse[admin.FlexClusterDescription20241113], *http.Response, error) {
request := connV2.FlexClustersApi.ListFlexClustersWithParams(ctx, &params)
request = request.PageNum(pageNum)
return request.Execute()
})

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

newFlexClustersModel, diags := NewTFModelDSP(ctx, tfModel.ProjectId.ValueString(), sdkProcessors)
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"`
}
26 changes: 16 additions & 10 deletions internal/service/flexcluster/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,21 @@ 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)
// Tests include testing of plural data source and so cannot be run in parallel
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 Down Expand Up @@ -115,6 +117,9 @@ 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)
}

Expand All @@ -125,6 +130,10 @@ func checksFlexCluster(projectID, clusterName string, terminationProtectionEnabl
"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 +145,8 @@ 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)
return acc.CheckRSAndDS(resourceName, &dataSourceName, &dataSourcePluralName, attrSet, attrMap, checks...)
}

func checkExists() resource.TestCheckFunc {
Expand Down