From aea9eaf233a5be4f515e87ea550b45f282ba2241 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Fri, 23 Feb 2024 19:36:36 +0100 Subject: [PATCH] chore: Upgrades `ldap_configuration` and `ldap_verify` resources to auto-generated SDK (#1971) * rename in resources * refactor in tests * run skipped tests * checkExists only with resourceName param * refactor ldap verify tests * mig tests * new SDK in tests * ds, read, import and delete * no delete in ldap verify * create & update * enable skipped tests --- .github/workflows/acceptance-tests-runner.yml | 5 +- .github/workflows/acceptance-tests.yml | 1 + .github/workflows/migration-tests.yml | 34 +++- .../data_source_ldap_configuration.go | 46 ++--- .../data_source_ldap_configuration_test.go | 58 ++---- .../resource_ldap_configuration.go | 146 +++++++-------- ...ource_ldap_configuration_migration_test.go | 45 +++++ .../resource_ldap_configuration_test.go | 166 +++++++++--------- .../ldapverify/data_source_ldap_verify.go | 44 +++-- .../data_source_ldap_verify_test.go | 69 ++------ .../ldapverify/resource_ldap_verify.go | 144 +++++++-------- .../resource_ldap_verify_migration_test.go | 44 +++++ .../ldapverify/resource_ldap_verify_test.go | 159 ++++++++--------- internal/testutil/acc/ldap.go | 21 --- internal/testutil/acc/pre_check.go | 8 + internal/testutil/mig/pre_check.go | 6 + 16 files changed, 498 insertions(+), 498 deletions(-) create mode 100644 internal/service/ldapconfiguration/resource_ldap_configuration_migration_test.go create mode 100644 internal/service/ldapverify/resource_ldap_verify_migration_test.go delete mode 100644 internal/testutil/acc/ldap.go diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 4c593a631c..13c4629718 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -109,7 +109,9 @@ on: required: true mongodb_atlas_ldap_port: required: true - + mongodb_atlas_ldap_ca_certificate: + required: true + env: TF_ACC: 1 TF_LOG: ${{ vars.LOG_LEVEL }} @@ -653,6 +655,7 @@ jobs: MONGODB_ATLAS_LDAP_USERNAME: ${{ secrets.mongodb_atlas_ldap_username }} MONGODB_ATLAS_LDAP_PASSWORD: ${{ secrets.mongodb_atlas_ldap_password }} MONGODB_ATLAS_LDAP_PORT: ${{ secrets.mongodb_atlas_ldap_port }} + MONGODB_ATLAS_LDAP_CA_CERTIFICATE: ${{ secrets.mongodb_atlas_ldap_ca_certificate }} TEST_REGEX: "^TestAccLDAP" run: make testacc encryption: diff --git a/.github/workflows/acceptance-tests.yml b/.github/workflows/acceptance-tests.yml index bd38509321..78dd88f9b1 100644 --- a/.github/workflows/acceptance-tests.yml +++ b/.github/workflows/acceptance-tests.yml @@ -55,6 +55,7 @@ jobs: mongodb_atlas_ldap_username: ${{ secrets.MONGODB_ATLAS_LDAP_USERNAME }} mongodb_atlas_ldap_password: ${{ secrets.MONGODB_ATLAS_LDAP_PASSWORD }} mongodb_atlas_ldap_port: ${{ secrets.MONGODB_ATLAS_LDAP_PORT }} + mongodb_atlas_ldap_ca_certificate: ${{ secrets.MONGODB_ATLAS_LDAP_CA_CERTIFICATE }} with: terraform_version: ${{ inputs.terraform_version || vars.TF_VERSION_LATEST }} ref: ${{ inputs.ref }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 3279bc8297..63b093edd9 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -68,6 +68,7 @@ jobs: data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} + ldap: ${{ steps.filter.outputs.ldap == 'true' || env.mustTrigger == 'true' }} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: dorny/paths-filter@ebc4d7e9ebcb0b1eb21480bb8f43113e996ac77a @@ -139,6 +140,9 @@ jobs: cluster: - 'internal/service/cluster/*.go' - 'internal/service/globalclusterconfig/*.go' + ldap: + - 'internal/service/ldapconfiguration/*.go' + - 'internal/service/ldapverify/*.go' project: needs: [ change-detection, get-provider-version ] @@ -516,4 +520,32 @@ jobs: MONGODB_ATLAS_LAST_VERSION: ${{ needs.get-provider-version.outputs.provider_version }} TEST_REGEX: "^TestAccMigrationClusterRS" run: make testacc - \ No newline at end of file + ldap: + needs: [ change-detection, get-provider-version ] + if: ${{ needs.change-detection.outputs.ldap == 'true' || inputs.test_group == 'ldap' }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 + - name: Set up Go + uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 + with: + go-version-file: 'go.mod' + - uses: hashicorp/setup-terraform@a1502cd9e758c50496cc9ac5308c4843bcd56d36 + with: + terraform_version: ${{ env.terraform_version }} + terraform_wrapper: false + - name: Migration Tests + env: + MONGODB_ATLAS_PUBLIC_KEY: ${{ secrets.MONGODB_ATLAS_PUBLIC_KEY_CLOUD_DEV }} + MONGODB_ATLAS_PRIVATE_KEY: ${{ secrets.MONGODB_ATLAS_PRIVATE_KEY_CLOUD_DEV }} + MONGODB_ATLAS_ORG_ID: ${{ vars.MONGODB_ATLAS_ORG_ID_CLOUD_DEV }} + MONGODB_ATLAS_BASE_URL: ${{ vars.MONGODB_ATLAS_BASE_URL }} + MONGODB_ATLAS_LDAP_HOSTNAME: ${{ secrets.MONGODB_ATLAS_LDAP_HOSTNAME }} + MONGODB_ATLAS_LDAP_USERNAME: ${{ secrets.MONGODB_ATLAS_LDAP_USERNAME }} + MONGODB_ATLAS_LDAP_PASSWORD: ${{ secrets.MONGODB_ATLAS_LDAP_PASSWORD }} + MONGODB_ATLAS_LDAP_CA_CERTIFICATE: ${{ secrets.MONGODB_ATLAS_LDAP_CA_CERTIFICATE }} + MONGODB_ATLAS_LDAP_PORT: ${{ secrets.MONGODB_ATLAS_LDAP_PORT }} + MONGODB_ATLAS_LAST_VERSION: ${{ needs.get-provider-version.outputs.provider_version }} + TEST_REGEX: "^TestAccMigrationLDAP" + run: make testacc diff --git a/internal/service/ldapconfiguration/data_source_ldap_configuration.go b/internal/service/ldapconfiguration/data_source_ldap_configuration.go index 0b1faead09..9b4739b51b 100644 --- a/internal/service/ldapconfiguration/data_source_ldap_configuration.go +++ b/internal/service/ldapconfiguration/data_source_ldap_configuration.go @@ -11,7 +11,7 @@ import ( func DataSource() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceMongoDBAtlasLDAPConfigurationRead, + ReadContext: dataSourceRead, Schema: map[string]*schema.Schema{ "project_id": { Type: schema.TypeString, @@ -73,41 +73,41 @@ func DataSource() *schema.Resource { } } -func dataSourceMongoDBAtlasLDAPConfigurationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas +func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) - ldap, _, err := conn.LDAPConfigurations.Get(ctx, projectID) + resp, _, err := connV2.LDAPConfigurationApi.GetLDAPConfiguration(ctx, projectID).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationRead, projectID, err)) + return diag.FromErr(fmt.Errorf(errorRead, projectID, err)) } - if err = d.Set("authentication_enabled", ldap.LDAP.AuthenticationEnabled); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authentication_enabled", d.Id(), err)) + if err = d.Set("authentication_enabled", resp.Ldap.GetAuthenticationEnabled()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authentication_enabled", d.Id(), err)) } - if err = d.Set("authorization_enabled", ldap.LDAP.AuthorizationEnabled); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authorization_enabled", d.Id(), err)) + if err = d.Set("authorization_enabled", resp.Ldap.GetAuthorizationEnabled()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authorization_enabled", d.Id(), err)) } - if err = d.Set("hostname", ldap.LDAP.Hostname); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "hostname", d.Id(), err)) + if err = d.Set("hostname", resp.Ldap.GetHostname()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "hostname", d.Id(), err)) } - if err = d.Set("port", ldap.LDAP.Port); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "port", d.Id(), err)) + if err = d.Set("port", resp.Ldap.GetPort()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "port", d.Id(), err)) } - if err = d.Set("bind_username", ldap.LDAP.BindUsername); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "bind_username", d.Id(), err)) + if err = d.Set("bind_username", resp.Ldap.GetBindUsername()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "bind_username", d.Id(), err)) } - if err = d.Set("bind_password", ldap.LDAP.BindPassword); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "bind_password", d.Id(), err)) + if err = d.Set("bind_password", resp.Ldap.GetBindPassword()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "bind_password", d.Id(), err)) } - if err = d.Set("ca_certificate", ldap.LDAP.CaCertificate); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "ca_certificate", d.Id(), err)) + if err = d.Set("ca_certificate", resp.Ldap.GetCaCertificate()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "ca_certificate", d.Id(), err)) } - if err = d.Set("authz_query_template", ldap.LDAP.AuthzQueryTemplate); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authz_query_template", d.Id(), err)) + if err = d.Set("authz_query_template", resp.Ldap.GetAuthzQueryTemplate()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authz_query_template", d.Id(), err)) } - if err = d.Set("user_to_dn_mapping", flattenDNMapping(ldap.LDAP.UserToDNMapping)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "user_to_dn_mapping", d.Id(), err)) + if err = d.Set("user_to_dn_mapping", flattenDNMapping(resp.Ldap.GetUserToDNMapping())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "user_to_dn_mapping", d.Id(), err)) } d.SetId(projectID) diff --git a/internal/service/ldapconfiguration/data_source_ldap_configuration_test.go b/internal/service/ldapconfiguration/data_source_ldap_configuration_test.go index 0954a791fe..44fa10d161 100644 --- a/internal/service/ldapconfiguration/data_source_ldap_configuration_test.go +++ b/internal/service/ldapconfiguration/data_source_ldap_configuration_test.go @@ -1,68 +1,42 @@ package ldapconfiguration_test import ( - "fmt" "os" + "strconv" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/spf13/cast" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func TestAccLDAPConfigurationDS_basic(t *testing.T) { var ( - ldapConfiguration matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_configuration.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") - authEnabled = true - projectName = acc.RandomProjectName() + dataSourceName = "data.mongodbatlas_ldap_configuration.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + authEnabled = true + projectName = acc.RandomProjectName() ) resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyLDAPConfiguration, + CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasDataSourceLDAPConfigurationConfig(projectName, orgID, hostname, username, password, authEnabled, cast.ToInt(port)), + Config: configBasic(projectName, orgID, hostname, username, password, authEnabled, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName, &ldapConfiguration), - - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), - resource.TestCheckResourceAttrSet(resourceName, "authentication_enabled"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttrSet(dataSourceName, "project_id"), + resource.TestCheckResourceAttr(dataSourceName, "hostname", hostname), + resource.TestCheckResourceAttr(dataSourceName, "bind_username", username), + resource.TestCheckResourceAttr(dataSourceName, "authentication_enabled", strconv.FormatBool(authEnabled)), + resource.TestCheckResourceAttr(dataSourceName, "port", port), ), }, }, }) } - -func testAccMongoDBAtlasDataSourceLDAPConfigurationConfig(projectName, orgID, hostname, username, password string, authEnabled bool, port int) string { - return fmt.Sprintf(` - resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" - } - - resource "mongodbatlas_ldap_configuration" "test" { - project_id = mongodbatlas_project.test.id - authentication_enabled = %[6]t - hostname = "%[3]s" - port = %[7]d - bind_username = "%[4]s" - bind_password = "%[5]s" - } - - data "mongodbatlas_ldap_configuration" "test" { - project_id = mongodbatlas_ldap_configuration.test.id - } -`, projectName, orgID, hostname, username, password, authEnabled, port) -} diff --git a/internal/service/ldapconfiguration/resource_ldap_configuration.go b/internal/service/ldapconfiguration/resource_ldap_configuration.go index 1ecf0664ae..4fcb2fed70 100644 --- a/internal/service/ldapconfiguration/resource_ldap_configuration.go +++ b/internal/service/ldapconfiguration/resource_ldap_configuration.go @@ -9,23 +9,23 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115007/admin" ) const ( - errorLDAPConfigurationCreate = "error creating MongoDB LDAPConfiguration (%s): %s" - errorLDAPConfigurationUpdate = "error updating MongoDB LDAPConfiguration (%s): %s" - errorLDAPConfigurationRead = "error reading MongoDB LDAPConfiguration (%s): %s" - errorLDAPConfigurationDelete = "error deleting MongoDB LDAPConfiguration (%s): %s" - errorLDAPConfigurationSetting = "error setting `%s` for LDAPConfiguration(%s): %s" + errorCreate = "error creating MongoDB LDAPConfiguration (%s): %s" + errorUpdate = "error updating MongoDB LDAPConfiguration (%s): %s" + errorRead = "error reading MongoDB LDAPConfiguration (%s): %s" + errorDelete = "error deleting MongoDB LDAPConfiguration (%s): %s" + errorSettings = "error setting `%s` for LDAPConfiguration(%s): %s" ) func Resource() *schema.Resource { return &schema.Resource{ - CreateContext: resourceMongoDBAtlasLDAPConfigurationCreate, - ReadContext: resourceMongoDBAtlasLDAPConfigurationRead, - UpdateContext: resourceMongoDBAtlasLDAPConfigurationUpdate, - DeleteContext: resourceMongoDBAtlasLDAPConfigurationDelete, + CreateContext: resourceCreate, + ReadContext: resourceRead, + UpdateContext: resourceUpdate, + DeleteContext: resourceDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -99,11 +99,11 @@ func Resource() *schema.Resource { } } -func resourceMongoDBAtlasLDAPConfigurationCreate(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) - ldap := &matlas.LDAP{} + ldap := new(admin.LDAPSecuritySettings) if v, ok := d.GetOk("authentication_enabled"); ok { ldap.AuthenticationEnabled = conversion.Pointer(v.(bool)) @@ -141,66 +141,58 @@ func resourceMongoDBAtlasLDAPConfigurationCreate(ctx context.Context, d *schema. ldap.UserToDNMapping = expandDNMapping(v.([]any)) } - ladpReq := &matlas.LDAPConfiguration{ - LDAP: ldap, + params := &admin.UserSecurity{ + Ldap: ldap, } - - _, _, err := conn.LDAPConfigurations.Save(ctx, projectID, ladpReq) + _, _, err := connV2.LDAPConfigurationApi.SaveLDAPConfiguration(ctx, projectID, params).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationCreate, projectID, err)) + return diag.FromErr(fmt.Errorf(errorCreate, projectID, err)) } - d.SetId(projectID) - - return resourceMongoDBAtlasLDAPConfigurationRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasLDAPConfigurationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas - - ldapResp, resp, err := conn.LDAPConfigurations.Get(context.Background(), d.Id()) +func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 + resp, httpResp, err := connV2.LDAPConfigurationApi.GetLDAPConfiguration(context.Background(), d.Id()).Execute() if err != nil { - if resp != nil && resp.StatusCode == http.StatusNotFound { + if httpResp != nil && httpResp.StatusCode == http.StatusNotFound { d.SetId("") return nil } - - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationRead, d.Id(), err)) + return diag.FromErr(fmt.Errorf(errorRead, d.Id(), err)) } - if err = d.Set("authentication_enabled", ldapResp.LDAP.AuthenticationEnabled); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authentication_enabled", d.Id(), err)) + if err = d.Set("authentication_enabled", resp.Ldap.GetAuthenticationEnabled()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authentication_enabled", d.Id(), err)) } - if err = d.Set("authorization_enabled", ldapResp.LDAP.AuthorizationEnabled); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authorization_enabled", d.Id(), err)) + if err = d.Set("authorization_enabled", resp.Ldap.GetAuthorizationEnabled()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authorization_enabled", d.Id(), err)) } - if err = d.Set("hostname", ldapResp.LDAP.Hostname); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "hostname", d.Id(), err)) + if err = d.Set("hostname", resp.Ldap.GetHostname()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "hostname", d.Id(), err)) } - if err = d.Set("port", ldapResp.LDAP.Port); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "port", d.Id(), err)) + if err = d.Set("port", resp.Ldap.GetPort()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "port", d.Id(), err)) } - if err = d.Set("bind_username", ldapResp.LDAP.BindUsername); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "bind_username", d.Id(), err)) + if err = d.Set("bind_username", resp.Ldap.GetBindUsername()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "bind_username", d.Id(), err)) } - if err = d.Set("ca_certificate", ldapResp.LDAP.CaCertificate); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "ca_certificate", d.Id(), err)) + if err = d.Set("ca_certificate", resp.Ldap.GetCaCertificate()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "ca_certificate", d.Id(), err)) } - if err = d.Set("authz_query_template", ldapResp.LDAP.AuthzQueryTemplate); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "authz_query_template", d.Id(), err)) + if err = d.Set("authz_query_template", resp.Ldap.GetAuthzQueryTemplate()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "authz_query_template", d.Id(), err)) } - if err = d.Set("user_to_dn_mapping", flattenDNMapping(ldapResp.LDAP.UserToDNMapping)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationSetting, "user_to_dn_mapping", d.Id(), err)) + if err = d.Set("user_to_dn_mapping", flattenDNMapping(resp.Ldap.GetUserToDNMapping())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "user_to_dn_mapping", d.Id(), err)) } - return nil } -func resourceMongoDBAtlasLDAPConfigurationUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get the client connection. - conn := meta.(*config.MongoDBClient).Atlas - - ldap := &matlas.LDAP{} +func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 + ldap := new(admin.LDAPSecuritySettings) if d.HasChange("authentication_enabled") { ldap.AuthenticationEnabled = conversion.Pointer(d.Get("authentication_enabled").(bool)) @@ -238,53 +230,47 @@ func resourceMongoDBAtlasLDAPConfigurationUpdate(ctx context.Context, d *schema. ldap.UserToDNMapping = expandDNMapping(d.Get("user_to_dn_mapping").([]any)) } - ldapReq := &matlas.LDAPConfiguration{ - LDAP: ldap, + params := &admin.UserSecurity{ + Ldap: ldap, } - - _, _, err := conn.LDAPConfigurations.Save(ctx, d.Id(), ldapReq) + _, _, err := connV2.LDAPConfigurationApi.SaveLDAPConfiguration(ctx, d.Id(), params).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationUpdate, d.Id(), err)) + return diag.FromErr(fmt.Errorf(errorUpdate, d.Id(), err)) } - return nil } -func resourceMongoDBAtlasLDAPConfigurationDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get the client connection. - conn := meta.(*config.MongoDBClient).Atlas - _, _, err := conn.LDAPConfigurations.Delete(ctx, d.Id()) +func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 + _, _, err := connV2.LDAPConfigurationApi.DeleteLDAPConfiguration(ctx, d.Id()).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPConfigurationDelete, d.Id(), err)) + return diag.FromErr(fmt.Errorf(errorDelete, d.Id(), err)) } - return nil } -func expandDNMapping(p []any) []*matlas.UserToDNMapping { - mappings := make([]*matlas.UserToDNMapping, len(p)) - +func expandDNMapping(p []any) *[]admin.UserToDNMapping { + mappings := make([]admin.UserToDNMapping, len(p)) for k, v := range p { mapping := v.(map[string]any) - mappings[k] = &matlas.UserToDNMapping{ + mappings[k] = admin.UserToDNMapping{ Match: mapping["match"].(string), - Substitution: mapping["substitution"].(string), - LDAPQuery: mapping["ldap_query"].(string), + Substitution: conversion.StringPtr(mapping["substitution"].(string)), + LdapQuery: conversion.StringPtr(mapping["ldap_query"].(string)), } } - - return mappings + return &mappings } -func flattenDNMapping(usersDNMappings []*matlas.UserToDNMapping) []map[string]any { - usersDN := make([]map[string]any, 0) - for _, v := range usersDNMappings { - usersDN = append(usersDN, map[string]any{ - "match": v.Match, - "substitution": v.Substitution, - "ldap_query": v.LDAPQuery, - }) +func flattenDNMapping(mappings []admin.UserToDNMapping) []map[string]string { + ret := make([]map[string]string, len(mappings)) + for i := range mappings { + mapping := &mappings[i] + ret[i] = map[string]string{ + "match": mapping.GetMatch(), + "substitution": mapping.GetSubstitution(), + "ldap_query": mapping.GetLdapQuery(), + } } - - return usersDN + return ret } diff --git a/internal/service/ldapconfiguration/resource_ldap_configuration_migration_test.go b/internal/service/ldapconfiguration/resource_ldap_configuration_migration_test.go new file mode 100644 index 0000000000..acaa19c800 --- /dev/null +++ b/internal/service/ldapconfiguration/resource_ldap_configuration_migration_test.go @@ -0,0 +1,45 @@ +package ldapconfiguration_test + +import ( + "os" + "strconv" + "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" + "github.com/spf13/cast" +) + +func TestAccMigrationLDAPConfiguration_basic(t *testing.T) { + var ( + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + authEnabled = true + projectName = acc.RandomProjectName() + config = configBasic(projectName, orgID, hostname, username, password, authEnabled, cast.ToInt(port)) + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { mig.PreCheckLDAP(t) }, + CheckDestroy: checkDestroy, + Steps: []resource.TestStep{ + { + ExternalProviders: mig.ExternalProviders(), + Config: config, + Check: resource.ComposeTestCheckFunc( + checkExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "project_id"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "authentication_enabled", strconv.FormatBool(authEnabled)), + resource.TestCheckResourceAttr(resourceName, "port", port), + ), + }, + mig.TestStepCheckEmptyPlan(config), + }, + }) +} diff --git a/internal/service/ldapconfiguration/resource_ldap_configuration_test.go b/internal/service/ldapconfiguration/resource_ldap_configuration_test.go index be164d6f91..27766c9a43 100644 --- a/internal/service/ldapconfiguration/resource_ldap_configuration_test.go +++ b/internal/service/ldapconfiguration/resource_ldap_configuration_test.go @@ -4,38 +4,39 @@ import ( "context" "fmt" "os" + "strconv" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/spf13/cast" - matlas "go.mongodb.org/atlas/mongodbatlas" +) + +const ( + resourceName = "mongodbatlas_ldap_configuration.test" ) func TestAccLDAPConfiguration_basic(t *testing.T) { var ( - ldapConfiguration matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_configuration.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") - authEnabled = true - projectName = acc.RandomProjectName() + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + authEnabled = true + projectName = acc.RandomProjectName() ) resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyLDAPConfiguration, + CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPConfigurationConfig(projectName, orgID, hostname, username, password, authEnabled, port), + Config: configBasic(projectName, orgID, hostname, username, password, authEnabled, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName, &ldapConfiguration), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "hostname"), resource.TestCheckResourceAttrSet(resourceName, "bind_username"), @@ -48,49 +49,44 @@ func TestAccLDAPConfiguration_basic(t *testing.T) { } func TestAccLDAPConfiguration_withVerify_CACertificateComplete(t *testing.T) { - acc.SkipTestForCI(t) var ( - ldapConfiguration matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_configuration.test" resourceVerifyName = "mongodbatlas_ldap_verify.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") caCertificate = os.Getenv("MONGODB_ATLAS_LDAP_CA_CERTIFICATE") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheckLDAP(t) }, + PreCheck: func() { acc.PreCheckLDAPCert(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyLDAPConfiguration, + CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPConfigurationWithVerifyConfig(projectName, orgID, clusterName, hostname, username, password, caCertificate, cast.ToInt(port), true), + Config: configWithVerify(projectName, orgID, clusterName, hostname, username, password, caCertificate, cast.ToInt(port), true), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName, &ldapConfiguration), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), - resource.TestCheckResourceAttrSet(resourceName, "authentication_enabled"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "authentication_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "port", port), resource.TestCheckResourceAttr(resourceVerifyName, "status", "SUCCESS"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.0.validation_type", "SERVER_SPECIFIED"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.#", "5"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.0.validation_type", "CONNECT"), resource.TestCheckResourceAttr(resourceVerifyName, "validations.0.status", "OK"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.1.validation_type", "CONNECT"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.1.validation_type", "AUTHENTICATE"), resource.TestCheckResourceAttr(resourceVerifyName, "validations.1.status", "OK"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.2.validation_type", "AUTHENTICATE"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.2.validation_type", "AUTHORIZATION_ENABLED"), resource.TestCheckResourceAttr(resourceVerifyName, "validations.2.status", "OK"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.3.validation_type", "AUTHORIZATION_ENABLED"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.3.validation_type", "PARSE_AUTHZ_QUERY_TEMPLATE"), resource.TestCheckResourceAttr(resourceVerifyName, "validations.3.status", "OK"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.4.validation_type", "PARSE_AUTHZ_QUERY_TEMPLATE"), + resource.TestCheckResourceAttr(resourceVerifyName, "validations.4.validation_type", "QUERY_SERVER"), resource.TestCheckResourceAttr(resourceVerifyName, "validations.4.status", "OK"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.5.validation_type", "QUERY_SERVER"), - resource.TestCheckResourceAttr(resourceVerifyName, "validations.5.status", "OK"), ), }, }, @@ -99,37 +95,34 @@ func TestAccLDAPConfiguration_withVerify_CACertificateComplete(t *testing.T) { func TestAccLDAPConfiguration_importBasic(t *testing.T) { var ( - ldapConf = matlas.LDAPConfiguration{} - resourceName = "mongodbatlas_ldap_configuration.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") - authEnabled = true - projectName = acc.RandomProjectName() + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + authEnabled = true + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyLDAPConfiguration, + CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPConfigurationConfig(projectName, orgID, hostname, username, password, authEnabled, port), + Config: configBasic(projectName, orgID, hostname, username, password, authEnabled, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName, &ldapConf), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), - resource.TestCheckResourceAttrSet(resourceName, "authentication_enabled"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "authentication_enabled", strconv.FormatBool(authEnabled)), + resource.TestCheckResourceAttr(resourceName, "port", port), ), }, { ResourceName: resourceName, - ImportStateIdFunc: testAccCheckMongoDBAtlasLDAPConfigurationImportStateIDFunc(resourceName), + ImportStateIdFunc: importStateIDFunc(resourceName), ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"project_id", "bind_password"}, @@ -138,7 +131,7 @@ func TestAccLDAPConfiguration_importBasic(t *testing.T) { }) } -func testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName string, ldapConf *matlas.LDAPConfiguration) resource.TestCheckFunc { +func checkExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -147,16 +140,28 @@ func testAccCheckMongoDBAtlasLDAPConfigurationExists(resourceName string, ldapCo if rs.Primary.ID == "" { return fmt.Errorf("no ID is set") } - ldapConfRes, _, err := acc.Conn().LDAPConfigurations.Get(context.Background(), rs.Primary.ID) + _, _, err := acc.ConnV2().LDAPConfigurationApi.GetLDAPConfiguration(context.Background(), rs.Primary.ID).Execute() if err != nil { return fmt.Errorf("ldapConfiguration (%s) does not exist", rs.Primary.ID) } - ldapConf = ldapConfRes return nil } } -func testAccCheckMongoDBAtlasLDAPConfigurationImportStateIDFunc(resourceName string) resource.ImportStateIdFunc { +func checkDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "mongodbatlas_ldap_configuration" { + continue + } + _, _, err := acc.ConnV2().LDAPConfigurationApi.GetLDAPConfiguration(context.Background(), rs.Primary.ID).Execute() + if err == nil { + return fmt.Errorf("ldapConfiguration (%s) still exists", rs.Primary.ID) + } + } + return nil +} + +func importStateIDFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -167,35 +172,38 @@ func testAccCheckMongoDBAtlasLDAPConfigurationImportStateIDFunc(resourceName str } } -func testAccMongoDBAtlasLDAPConfigurationConfig(projectName, orgID, hostname, username, password string, authEnabled bool, port string) string { +func configBasic(projectName, orgID, hostname, username, password string, authEnabled bool, port int) string { return fmt.Sprintf(` resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" + name = %[1]q + org_id = %[2]q } resource "mongodbatlas_ldap_configuration" "test" { project_id = mongodbatlas_project.test.id - authentication_enabled = %[6]t - hostname = "%[3]s" - port = %[7]s - bind_username = "%[4]s" - bind_password = "%[5]s" - }`, projectName, orgID, hostname, username, password, authEnabled, port) + hostname = %[3]q + bind_username = %[4]q + bind_password = %[5]q + authentication_enabled = %[6]t + port = %[7]d + } + + data "mongodbatlas_ldap_configuration" "test" { + project_id = mongodbatlas_ldap_configuration.test.id + } + `, projectName, orgID, hostname, username, password, authEnabled, port) } -func testAccMongoDBAtlasLDAPConfigurationWithVerifyConfig(projectName, orgID, clusterName, hostname, username, password, caCertificate string, port int, authEnabled bool) string { +func configWithVerify(projectName, orgID, clusterName, hostname, username, password, caCertificate string, port int, authEnabled bool) string { return fmt.Sprintf(` resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" + name = %[1]q + org_id = %[2]q } resource "mongodbatlas_cluster" "test" { project_id = mongodbatlas_project.test.id - name = "%[3]s" - - // Provider Settings "block" + name = %[3]q provider_name = "AWS" provider_region_name = "US_EAST_2" provider_instance_size_name = "M10" @@ -204,10 +212,10 @@ func testAccMongoDBAtlasLDAPConfigurationWithVerifyConfig(projectName, orgID, cl resource "mongodbatlas_ldap_verify" "test" { project_id = mongodbatlas_project.test.id - hostname = "%[4]s" + hostname = %[4]q + bind_username = %[5]q + bind_password = %[6]q port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" ca_certificate = <<-EOF %[9]s EOF @@ -217,12 +225,12 @@ func testAccMongoDBAtlasLDAPConfigurationWithVerifyConfig(projectName, orgID, cl resource "mongodbatlas_ldap_configuration" "test" { project_id = mongodbatlas_project.test.id - authentication_enabled = %[8]t authorization_enabled = false - hostname = "%[4]s" + hostname = %[4]q + bind_username = %[5]q + bind_password = %[6]q port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" + authentication_enabled = %[8]t ca_certificate = <<-EOF %[9]s EOF diff --git a/internal/service/ldapverify/data_source_ldap_verify.go b/internal/service/ldapverify/data_source_ldap_verify.go index 303521b498..70eddfe720 100644 --- a/internal/service/ldapverify/data_source_ldap_verify.go +++ b/internal/service/ldapverify/data_source_ldap_verify.go @@ -12,7 +12,7 @@ import ( func DataSource() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceMongoDBAtlasLDAPVerifyRead, + ReadContext: dataSourceRead, Schema: map[string]*schema.Schema{ "project_id": { Type: schema.TypeString, @@ -74,42 +74,38 @@ func DataSource() *schema.Resource { } } -func dataSourceMongoDBAtlasLDAPVerifyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas +func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) requestID := d.Get("request_id").(string) - - ldapResp, _, err := conn.LDAPConfigurations.GetStatus(ctx, projectID, requestID) + ldapResp, _, err := connV2.LDAPConfigurationApi.GetLDAPConfigurationStatus(ctx, projectID, requestID).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifyRead, projectID, err)) + return diag.FromErr(fmt.Errorf(errorRead, projectID, err)) } - - if err := d.Set("hostname", ldapResp.Request.Hostname); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "hostname", d.Id(), err)) + if err := d.Set("hostname", ldapResp.Request.GetHostname()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "hostname", d.Id(), err)) } - if err := d.Set("port", ldapResp.Request.Port); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "port", d.Id(), err)) + if err := d.Set("port", ldapResp.Request.GetPort()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "port", d.Id(), err)) } - if err := d.Set("bind_username", ldapResp.Request.BindUsername); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "bind_username", d.Id(), err)) + if err := d.Set("bind_username", ldapResp.Request.GetBindUsername()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "bind_username", d.Id(), err)) } - if err := d.Set("links", FlattenLinks(ldapResp.Links)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "links", d.Id(), err)) + if err := d.Set("links", conversion.FlattenLinks(ldapResp.GetLinks())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "links", d.Id(), err)) } - if err := d.Set("validations", flattenValidations(ldapResp.Validations)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "validations", d.Id(), err)) + if err := d.Set("validations", flattenValidations(ldapResp.GetValidations())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "validations", d.Id(), err)) } - if err := d.Set("request_id", ldapResp.RequestID); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "request_id", d.Id(), err)) + if err := d.Set("request_id", ldapResp.GetRequestId()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "request_id", d.Id(), err)) } - if err := d.Set("status", ldapResp.Status); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "status", d.Id(), err)) + if err := d.Set("status", ldapResp.GetStatus()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "status", d.Id(), err)) } - d.SetId(conversion.EncodeStateID(map[string]string{ "project_id": projectID, - "request_id": ldapResp.RequestID, + "request_id": ldapResp.GetRequestId(), })) - return nil } diff --git a/internal/service/ldapverify/data_source_ldap_verify_test.go b/internal/service/ldapverify/data_source_ldap_verify_test.go index 8034b5b854..d4d3e047df 100644 --- a/internal/service/ldapverify/data_source_ldap_verify_test.go +++ b/internal/service/ldapverify/data_source_ldap_verify_test.go @@ -1,81 +1,40 @@ package ldapverify_test import ( - "fmt" "os" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/spf13/cast" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func TestAccLDAPVerifyDS_basic(t *testing.T) { - acc.SkipTestForCI(t) var ( - ldapVerify matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_verify.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + dataSourceName = "data.mongodbatlas_ldap_verify.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyLDAPConfiguration, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasDataSourceLDAPVerifyConfig(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), + Config: configBasic(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName, &ldapVerify), - - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), - resource.TestCheckResourceAttrSet(resourceName, "request_id"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttrSet(dataSourceName, "project_id"), + resource.TestCheckResourceAttrSet(dataSourceName, "request_id"), + resource.TestCheckResourceAttr(dataSourceName, "hostname", hostname), + resource.TestCheckResourceAttr(dataSourceName, "bind_username", username), + resource.TestCheckResourceAttr(dataSourceName, "port", port), ), }, }, }) } - -func testAccMongoDBAtlasDataSourceLDAPVerifyConfig(projectName, orgID, clusterName, hostname, username, password string, port int) string { - return fmt.Sprintf(` - resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" - } - - resource "mongodbatlas_cluster" "test" { - project_id = mongodbatlas_project.test.id - name = "%[3]s" - - // Provider Settings "block" - provider_name = "AWS" - provider_region_name = "US_EAST_2" - provider_instance_size_name = "M10" - cloud_backup = true //enable cloud provider snapshots - } - - resource "mongodbatlas_ldap_verify" "test" { - project_id = mongodbatlas_project.test.id - hostname = "%[4]s" - port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" - depends_on = ["mongodbatlas_cluster.test"] - } - - data "mongodbatlas_ldap_verify" "test" { - project_id = mongodbatlas_ldap_verify.test.project_id - request_id = mongodbatlas_ldap_verify.test.request_id - } -`, projectName, orgID, clusterName, hostname, username, password, port) -} diff --git a/internal/service/ldapverify/resource_ldap_verify.go b/internal/service/ldapverify/resource_ldap_verify.go index 5a3e6040bc..b81e64221b 100644 --- a/internal/service/ldapverify/resource_ldap_verify.go +++ b/internal/service/ldapverify/resource_ldap_verify.go @@ -13,22 +13,22 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115007/admin" ) const ( - errorLDAPVerifyCreate = "error creating MongoDB LDAPVerify (%s): %s" - errorLDAPVerifyRead = "error reading MongoDB LDAPVerify (%s): %s" - errorLDAPVerifySetting = "error setting `%s` for LDAPVerify(%s): %s" + errorCreate = "error creating MongoDB LDAPVerify (%s): %s" + errorRead = "error reading MongoDB LDAPVerify (%s): %s" + errorSettings = "error setting `%s` for LDAPVerify(%s): %s" ) func Resource() *schema.Resource { return &schema.Resource{ - CreateContext: resourceMongoDBAtlasLDAPVerifyCreate, - ReadContext: resourceMongoDBAtlasLDAPVerifyRead, - DeleteContext: resourceMongoDBAtlasLDAPVerifyDelete, + CreateContext: resourceCreate, + ReadContext: resourceRead, + DeleteContext: resourceDelete, Importer: &schema.ResourceImporter{ - StateContext: resourceMongoDBAtlasLDAPVerifyImportState, + StateContext: resourceImport, }, Schema: map[string]*schema.Schema{ "project_id": { @@ -112,174 +112,152 @@ func Resource() *schema.Resource { } } -func resourceMongoDBAtlasLDAPVerifyCreate(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) - ldapReq := &matlas.LDAP{} + params := new(admin.LDAPVerifyConnectivityJobRequestParams) if v, ok := d.GetOk("hostname"); ok { - ldapReq.Hostname = conversion.Pointer(v.(string)) + params.Hostname = v.(string) } if v, ok := d.GetOk("port"); ok { - ldapReq.Port = conversion.Pointer(v.(int)) + params.Port = v.(int) } if v, ok := d.GetOk("bind_username"); ok { - ldapReq.BindUsername = conversion.Pointer(v.(string)) + params.BindUsername = v.(string) } if v, ok := d.GetOk("bind_password"); ok { - ldapReq.BindPassword = conversion.Pointer(v.(string)) + params.BindPassword = v.(string) } if v, ok := d.GetOk("ca_certificate"); ok { - ldapReq.CaCertificate = conversion.Pointer(v.(string)) + params.CaCertificate = conversion.Pointer(v.(string)) } if v, ok := d.GetOk("authz_query_template"); ok { - ldapReq.AuthzQueryTemplate = conversion.Pointer(v.(string)) + params.AuthzQueryTemplate = conversion.Pointer(v.(string)) } - ldap, _, err := conn.LDAPConfigurations.Verify(ctx, projectID, ldapReq) + ldap, _, err := connV2.LDAPConfigurationApi.VerifyLDAPConfiguration(ctx, projectID, params).Execute() if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifyCreate, projectID, err)) + return diag.FromErr(fmt.Errorf(errorCreate, projectID, err)) } stateConf := &retry.StateChangeConf{ Pending: []string{"PENDING"}, Target: []string{"SUCCESS", "FAILED"}, - Refresh: resourceLDAPGetStatusRefreshFunc(ctx, projectID, ldap.RequestID, conn), + Refresh: resourceRefreshFunc(ctx, projectID, ldap.GetRequestId(), connV2), Timeout: 3 * time.Hour, MinTimeout: 1 * time.Minute, Delay: 3 * time.Minute, } - // Wait, catching any errors _, err = stateConf.WaitForStateContext(ctx) if err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifyCreate, projectID, err)) + return diag.FromErr(fmt.Errorf(errorCreate, projectID, err)) } d.SetId(conversion.EncodeStateID(map[string]string{ "project_id": projectID, - "request_id": ldap.RequestID, + "request_id": ldap.GetRequestId(), })) - return resourceMongoDBAtlasLDAPVerifyRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasLDAPVerifyRead(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"] requestID := ids["request_id"] - - ldapResp, resp, err := conn.LDAPConfigurations.GetStatus(context.Background(), projectID, requestID) + ldapResp, resp, err := connV2.LDAPConfigurationApi.GetLDAPConfigurationStatus(context.Background(), projectID, requestID).Execute() if err != nil || ldapResp == nil { if resp != nil && resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } - - return diag.FromErr(fmt.Errorf(errorLDAPVerifyRead, d.Id(), err)) + return diag.FromErr(fmt.Errorf(errorRead, d.Id(), err)) } - if err := d.Set("hostname", ldapResp.Request.Hostname); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "hostname", d.Id(), err)) + if err := d.Set("hostname", ldapResp.Request.GetHostname()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "hostname", d.Id(), err)) } if err := d.Set("port", ldapResp.Request.Port); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "port", d.Id(), err)) + return diag.FromErr(fmt.Errorf(errorSettings, "port", d.Id(), err)) } - if err := d.Set("bind_username", ldapResp.Request.BindUsername); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "bind_username", d.Id(), err)) + if err := d.Set("bind_username", ldapResp.Request.GetBindUsername()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "bind_username", d.Id(), err)) } - if err := d.Set("links", FlattenLinks(ldapResp.Links)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "links", d.Id(), err)) + if err := d.Set("links", conversion.FlattenLinks(ldapResp.GetLinks())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "links", d.Id(), err)) } - if err := d.Set("validations", flattenValidations(ldapResp.Validations)); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "validations", d.Id(), err)) + if err := d.Set("validations", flattenValidations(ldapResp.GetValidations())); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "validations", d.Id(), err)) } - if err := d.Set("request_id", ldapResp.RequestID); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "request_id", d.Id(), err)) + if err := d.Set("request_id", ldapResp.GetRequestId()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "request_id", d.Id(), err)) } - if err := d.Set("status", ldapResp.Status); err != nil { - return diag.FromErr(fmt.Errorf(errorLDAPVerifySetting, "status", d.Id(), err)) + if err := d.Set("status", ldapResp.GetStatus()); err != nil { + return diag.FromErr(fmt.Errorf(errorSettings, "status", d.Id(), err)) } return nil } -func resourceMongoDBAtlasLDAPVerifyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { d.SetId("") - return nil } -func FlattenLinks(linksArray []*matlas.Link) []map[string]any { - links := make([]map[string]any, 0) - for _, v := range linksArray { - links = append(links, map[string]any{ - "href": v.Href, - "rel": v.Rel, - }) - } - - return links -} - -func flattenValidations(validationsArray []*matlas.LDAPValidation) []map[string]any { - validations := make([]map[string]any, 0) - for _, v := range validationsArray { - validations = append(validations, map[string]any{ - "status": v.Status, - "validation_type": v.ValidationType, - }) +func flattenValidations(validations []admin.LDAPVerifyConnectivityJobRequestValidation) []map[string]string { + ret := make([]map[string]string, len(validations)) + for i := range validations { + validation := &validations[i] + ret[i] = map[string]string{ + "status": validation.GetStatus(), + "validation_type": validation.GetValidationType(), + } } - - return validations + return ret } -func resourceMongoDBAtlasLDAPVerifyImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - conn := meta.(*config.MongoDBClient).Atlas - +func resourceImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { + connV2 := meta.(*config.MongoDBClient).AtlasV2 parts := strings.SplitN(d.Id(), "-", 2) if len(parts) != 2 { return nil, errors.New("import format error: to import a LDAP Verify use the format {project_id}-{request_id}") } - projectID := parts[0] requestID := parts[1] - _, _, err := conn.LDAPConfigurations.GetStatus(ctx, projectID, requestID) + _, _, err := connV2.LDAPConfigurationApi.GetLDAPConfigurationStatus(ctx, projectID, requestID).Execute() if err != nil { - return nil, fmt.Errorf(errorLDAPVerifyRead, requestID, err) + return nil, fmt.Errorf(errorRead, requestID, err) } if err := d.Set("project_id", projectID); err != nil { - return nil, fmt.Errorf(errorLDAPVerifySetting, "project_id", requestID, err) + return nil, fmt.Errorf(errorSettings, "project_id", requestID, err) } if err := d.Set("request_id", requestID); err != nil { - return nil, fmt.Errorf(errorLDAPVerifySetting, "request_id", requestID, err) + return nil, fmt.Errorf(errorSettings, "request_id", requestID, err) } d.SetId(conversion.EncodeStateID(map[string]string{ "project_id": projectID, "request_id": requestID, })) - return []*schema.ResourceData{d}, nil } -func resourceLDAPGetStatusRefreshFunc(ctx context.Context, projectID, requestID string, client *matlas.Client) retry.StateRefreshFunc { +func resourceRefreshFunc(ctx context.Context, projectID, requestID string, connV2 *admin.APIClient) retry.StateRefreshFunc { return func() (any, string, error) { - p, resp, err := client.LDAPConfigurations.GetStatus(ctx, projectID, requestID) + ldap, resp, err := connV2.LDAPConfigurationApi.GetLDAPConfigurationStatus(ctx, projectID, requestID).Execute() if err != nil { - if resp.Response.StatusCode == 404 { + if resp.StatusCode == 404 { return "", "DELETED", nil } - return nil, "", err } - - return p, p.Status, nil + status := ldap.GetStatus() + return ldap, status, nil } } diff --git a/internal/service/ldapverify/resource_ldap_verify_migration_test.go b/internal/service/ldapverify/resource_ldap_verify_migration_test.go new file mode 100644 index 0000000000..07435ceca1 --- /dev/null +++ b/internal/service/ldapverify/resource_ldap_verify_migration_test.go @@ -0,0 +1,44 @@ +package ldapverify_test + +import ( + "os" + "testing" + + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" + "github.com/spf13/cast" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccMigrationLDAPVerify_basic(t *testing.T) { + var ( + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + config = configBasic(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)) + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { mig.PreCheckLDAP(t) }, + Steps: []resource.TestStep{ + { + ExternalProviders: mig.ExternalProviders(), + Config: config, + Check: resource.ComposeTestCheckFunc( + checkExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "project_id"), + resource.TestCheckResourceAttrSet(resourceName, "request_id"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "port", port), + ), + }, + mig.TestStepCheckEmptyPlan(config), + }, + }) +} diff --git a/internal/service/ldapverify/resource_ldap_verify_test.go b/internal/service/ldapverify/resource_ldap_verify_test.go index 5ba7d12628..675d8b5e63 100644 --- a/internal/service/ldapverify/resource_ldap_verify_test.go +++ b/internal/service/ldapverify/resource_ldap_verify_test.go @@ -11,37 +11,36 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - matlas "go.mongodb.org/atlas/mongodbatlas" +) + +const ( + resourceName = "mongodbatlas_ldap_verify.test" ) func TestAccLDAPVerify_basic(t *testing.T) { var ( - ldapVerify matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_verify.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: testAccCheckMongoDBAtlasLDAPVerifyDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPVerifyConfig(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), + Config: configBasic(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName, &ldapVerify), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), resource.TestCheckResourceAttrSet(resourceName, "request_id"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "port", port), ), }, }, @@ -49,42 +48,36 @@ func TestAccLDAPVerify_basic(t *testing.T) { } func TestAccLDAPVerify_withConfiguration_CACertificate(t *testing.T) { - acc.SkipTestForCI(t) var ( - ldapVerify matlas.LDAPConfiguration - resourceName = "mongodbatlas_ldap_verify.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") caCertificate = os.Getenv("MONGODB_ATLAS_LDAP_CA_CERTIFICATE") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.PreCheckLDAP(t) }, + PreCheck: func() { acc.PreCheckLDAPCert(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: testAccCheckMongoDBAtlasLDAPVerifyDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPVerifyWithConfigurationConfig(projectName, orgID, clusterName, hostname, username, password, caCertificate, cast.ToInt(port), true), + Config: configWithConfiguration(projectName, orgID, clusterName, hostname, username, password, caCertificate, cast.ToInt(port), true), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName, &ldapVerify), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), resource.TestCheckResourceAttrSet(resourceName, "request_id"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "port", port), resource.TestCheckResourceAttr(resourceName, "status", "SUCCESS"), - resource.TestCheckResourceAttr(resourceName, "validations.0.validation_type", "SERVER_SPECIFIED"), + resource.TestCheckResourceAttr(resourceName, "validations.#", "2"), + resource.TestCheckResourceAttr(resourceName, "validations.0.validation_type", "CONNECT"), resource.TestCheckResourceAttr(resourceName, "validations.0.status", "OK"), - resource.TestCheckResourceAttr(resourceName, "validations.1.validation_type", "CONNECT"), + resource.TestCheckResourceAttr(resourceName, "validations.1.validation_type", "AUTHENTICATE"), resource.TestCheckResourceAttr(resourceName, "validations.1.status", "OK"), - resource.TestCheckResourceAttr(resourceName, "validations.2.validation_type", "AUTHENTICATE"), - resource.TestCheckResourceAttr(resourceName, "validations.2.status", "OK"), ), }, }, @@ -93,37 +86,33 @@ func TestAccLDAPVerify_withConfiguration_CACertificate(t *testing.T) { func TestAccLDAPVerify_importBasic(t *testing.T) { var ( - ldapConf = matlas.LDAPConfiguration{} - resourceName = "mongodbatlas_ldap_verify.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() - hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") - username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") - password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") - port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + hostname = os.Getenv("MONGODB_ATLAS_LDAP_HOSTNAME") + username = os.Getenv("MONGODB_ATLAS_LDAP_USERNAME") + password = os.Getenv("MONGODB_ATLAS_LDAP_PASSWORD") + port = os.Getenv("MONGODB_ATLAS_LDAP_PORT") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckLDAP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: testAccCheckMongoDBAtlasLDAPVerifyDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasLDAPVerifyConfig(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), + Config: configBasic(projectName, orgID, clusterName, hostname, username, password, cast.ToInt(port)), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName, &ldapConf), - + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttrSet(resourceName, "hostname"), - resource.TestCheckResourceAttrSet(resourceName, "bind_username"), resource.TestCheckResourceAttrSet(resourceName, "request_id"), - resource.TestCheckResourceAttrSet(resourceName, "port"), + resource.TestCheckResourceAttr(resourceName, "hostname", hostname), + resource.TestCheckResourceAttr(resourceName, "bind_username", username), + resource.TestCheckResourceAttr(resourceName, "port", port), ), }, { ResourceName: resourceName, - ImportStateIdFunc: testAccCheckMongoDBAtlasLDAPVerifyImportStateIDFunc(resourceName), + ImportStateIdFunc: importStateIDFunc(resourceName), ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"project_id", "bind_password"}, @@ -132,7 +121,7 @@ func TestAccLDAPVerify_importBasic(t *testing.T) { }) } -func testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName string, ldapConf *matlas.LDAPConfiguration) resource.TestCheckFunc { +func checkExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -141,30 +130,15 @@ func testAccCheckMongoDBAtlasLDAPVerifyExists(resourceName string, ldapConf *mat if rs.Primary.ID == "" { return fmt.Errorf("no ID is set") } - ldapConfRes, _, err := acc.Conn().LDAPConfigurations.GetStatus(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["request_id"]) + _, _, err := acc.ConnV2().LDAPConfigurationApi.GetLDAPConfigurationStatus(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["request_id"]).Execute() if err != nil { return fmt.Errorf("ldapVerify (%s) does not exist", rs.Primary.ID) } - ldapConf = ldapConfRes return nil } } -func testAccCheckMongoDBAtlasLDAPVerifyDestroy(s *terraform.State) error { - for _, rs := range s.RootModule().Resources { - if rs.Type != "mongodbatlas_ldap_verify" { - continue - } - - _, _, err := acc.Conn().LDAPConfigurations.GetStatus(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["request_id"]) - if err == nil { - return fmt.Errorf("ldapVerify (%s) still exists", rs.Primary.ID) - } - } - return nil -} - -func testAccCheckMongoDBAtlasLDAPVerifyImportStateIDFunc(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 { @@ -174,16 +148,16 @@ func testAccCheckMongoDBAtlasLDAPVerifyImportStateIDFunc(resourceName string) re } } -func testAccMongoDBAtlasLDAPVerifyConfig(projectName, orgID, clusterName, hostname, username, password string, port int) string { +func configBasic(projectName, orgID, clusterName, hostname, username, password string, port int) string { return fmt.Sprintf(` resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" + name = %[1]q + org_id = %[2]q } resource "mongodbatlas_cluster" "test" { project_id = mongodbatlas_project.test.id - name = "%[3]s" + name = %[3]q // Provider Settings "block" provider_name = "AWS" @@ -194,38 +168,44 @@ func testAccMongoDBAtlasLDAPVerifyConfig(projectName, orgID, clusterName, hostna resource "mongodbatlas_ldap_verify" "test" { project_id = mongodbatlas_project.test.id - hostname = "%[4]s" + hostname = %[4]q port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" + bind_username = %[5]q + bind_password = %[6]q depends_on = ["mongodbatlas_cluster.test"] - }`, projectName, orgID, clusterName, hostname, username, password, port) + } + + data "mongodbatlas_ldap_verify" "test" { + project_id = mongodbatlas_ldap_verify.test.project_id + request_id = mongodbatlas_ldap_verify.test.request_id + } + `, projectName, orgID, clusterName, hostname, username, password, port) } -func testAccMongoDBAtlasLDAPVerifyWithConfigurationConfig(projectName, orgID, clusterName, hostname, username, password, caCertificate string, port int, authEnabled bool) string { +func configWithConfiguration(projectName, orgID, clusterName, hostname, username, password, caCertificate string, port int, authEnabled bool) string { return fmt.Sprintf(` resource "mongodbatlas_project" "test" { - name = "%[1]s" - org_id = "%[2]s" + name = %[1]q + org_id = %[2]q } resource "mongodbatlas_cluster" "test" { project_id = mongodbatlas_project.test.id - name = "%[3]s" + name = %[3]q // Provider Settings "block" provider_name = "AWS" provider_region_name = "US_EAST_2" provider_instance_size_name = "M10" - backup_enabled = true //enable cloud provider snapshots + } resource "mongodbatlas_ldap_verify" "test" { project_id = mongodbatlas_project.test.id - hostname = "%[4]s" + hostname = %[4]q port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" + bind_username = %[5]q + bind_password = %[6]q ca_certificate = <<-EOF %[9]s EOF @@ -236,13 +216,14 @@ func testAccMongoDBAtlasLDAPVerifyWithConfigurationConfig(projectName, orgID, cl project_id = mongodbatlas_project.test.id authentication_enabled = %[8]t authorization_enabled = false - hostname = "%[4]s" + hostname = %[4]q port = %[7]d - bind_username = "%[5]s" - bind_password = "%[6]s" + bind_username = %[5]q + bind_password = %[6]q ca_certificate = <<-EOF %[9]s EOF depends_on = [mongodbatlas_ldap_verify.test] - }`, projectName, orgID, clusterName, hostname, username, password, port, authEnabled, caCertificate) + } + `, projectName, orgID, clusterName, hostname, username, password, port, authEnabled, caCertificate) } diff --git a/internal/testutil/acc/ldap.go b/internal/testutil/acc/ldap.go deleted file mode 100644 index 9f5ed4b05b..0000000000 --- a/internal/testutil/acc/ldap.go +++ /dev/null @@ -1,21 +0,0 @@ -package acc - -import ( - "context" - "fmt" - - "github.com/hashicorp/terraform-plugin-testing/terraform" -) - -func CheckDestroyLDAPConfiguration(s *terraform.State) error { - for _, rs := range s.RootModule().Resources { - if rs.Type != "mongodbatlas_ldap_configuration" { - continue - } - _, _, err := Conn().LDAPConfigurations.Get(context.Background(), rs.Primary.ID) - if err == nil { - return fmt.Errorf("ldapConfiguration (%s) still exists", rs.Primary.ID) - } - } - return nil -} diff --git a/internal/testutil/acc/pre_check.go b/internal/testutil/acc/pre_check.go index f7dc72cae2..d47160d415 100644 --- a/internal/testutil/acc/pre_check.go +++ b/internal/testutil/acc/pre_check.go @@ -226,6 +226,14 @@ func PreCheckLDAP(tb testing.TB) { PreCheckBasic(tb) } +func PreCheckLDAPCert(tb testing.TB) { + tb.Helper() + if os.Getenv("MONGODB_ATLAS_LDAP_CA_CERTIFICATE") == "" { + tb.Fatal("`MONGODB_ATLAS_LDAP_CA_CERTIFICATE` must be set") + } + PreCheckLDAP(tb) +} + func PreCheckFederatedSettings(tb testing.TB) { tb.Helper() if os.Getenv("MONGODB_ATLAS_FEDERATED_PROJECT_ID") == "" || diff --git a/internal/testutil/mig/pre_check.go b/internal/testutil/mig/pre_check.go index ca34c9484f..add602d2d2 100644 --- a/internal/testutil/mig/pre_check.go +++ b/internal/testutil/mig/pre_check.go @@ -29,6 +29,12 @@ func PreCheckCert(tb testing.TB) { acc.PreCheckCert(tb) } +func PreCheckLDAP(tb testing.TB) { + tb.Helper() + checkLastVersion(tb) + acc.PreCheckLDAP(tb) +} + func PreCheckAtlasUsername(tb testing.TB) { tb.Helper() checkLastVersion(tb)