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

Error creating user (mongodbatlas_database_user) #1852

Closed
Kikivsantos opened this issue Jan 18, 2024 · 2 comments
Closed

Error creating user (mongodbatlas_database_user) #1852

Kikivsantos opened this issue Jan 18, 2024 · 2 comments

Comments

@Kikivsantos
Copy link

Hi, there.

I'm trying to run a terraform code (that we usually run to create new users) and it's returning error.

Variable:

variable "project_id" {
    description = <<HEREDOC
    Required - The unique identifier of the project for the Atlas cluster.
    HEREDOC
    default = {
        production            = "5f9ae09f623d2e2943ee8dd7",
        staging               = "5f8b580239daa751b82afe9d",
        develop               = "5f6f9959a55ed91e80e4f7d1"
    }
}
variable "environment" {
    description = <<HEREDOC
    Required - The environment of the project for the Atlas cluster.
    HEREDOC
    type = string
}
variable "username" {
    description = <<HEREDOC
    Required - The name of database user.
    HEREDOC
}
variable "password" {
    description = <<HEREDOC
    Optional - The password of database user.
    HEREDOC
    default     = null
}
variable "password_length" {
    description = <<HEREDOC
    Optional - The length of password of database user.
    HEREDOC
    default     = 20
}
variable "roles" {
    description = <<HEREDOC
    Required - One or more user roles blocks.
    HEREDOC
    type        = list(map(string))
    default = []
}
variable "scope_name" {
    description = <<HEREDOC
    Required - One or more user cluster scopes blocks.
    HEREDOC
    type        = list(string)
    default = null
}

variable "type" {
    description = <<HEREDOC
    Optional - The type of database user. Valid values are:
    - "dbre" (database team member)
    - "developer" (developer team member)
    - "application" (is application user)
    HEREDOC
    default     = "developer"
}

main:

# ------------------------------------------------------------------------------
# RANDOM PASSWORD
# ------------------------------------------------------------------------------
resource "random_password" "default" {
    length                    = var.password_length
    special                   = false
}
# ------------------------------------------------------------------------------
# DATABASE USER FOR DBRE, DEVELOPER, AND APPLICATION
# ------------------------------------------------------------------------------
resource "mongodbatlas_database_user" "dbre" {
    count                     = var.type == "dbre" ? 1 : 0
    project_id                = var.project_id[var.environment]
    username                  = "dbre_${var.username}"
    password                  = random_password.default.result
    auth_database_name        = "admin"

    roles {
        role_name               = "atlasAdmin"
        database_name           = "admin"
    }

    roles {
        role_name               = "dbAdmin"
        database_name           = "local"
    }

    labels {
        key   = "Environment"
        value = var.environment
    }

    labels {
        key   = "DBRE"
        value = true
    }
}

resource "mongodbatlas_database_user" "developer" {
    count                     = var.type == "developer" ? 1 : 0
    project_id                = var.project_id[var.environment]
    username                  = "user_${var.username}"
    password                  = random_password.default.result
    auth_database_name        = "admin"

    dynamic "roles" {
        for_each              = var.roles
        content {
            role_name         = roles.value["role_name"]
            database_name     = roles.value["database_name"]
            collection_name   = try(roles.value["collection_name"], null)
        }
    }

    
    dynamic "scopes" {
        for_each              = var.scope_name
        content {
            name              = scopes.value
            type              = "CLUSTER"
        }
    }

    labels {
        key   = "Environment"
        value = var.environment
    }

    labels {
        key   = "Developer"
        value = true
    }
}

resource "mongodbatlas_database_user" "application" {
    count                     = var.type == "application" ? 1 : 0
    project_id                = var.project_id[var.environment]
    username                  = "${var.username}"
    password                  = random_password.default.result
    auth_database_name        = "admin"

    dynamic "roles" {
        for_each              = var.roles
        content {
            role_name         = roles.value["role_name"]
            database_name     = roles.value["database_name"]
        }
    }

    labels {
        key   = "Environment"
        value = var.environment
    }

    labels {
        key   = "Application"
        value = true
    }
}

My terragrunt code (that calls my terraform code):

include {
  path = find_in_parent_folders()
}

locals {
  component_name = "modules/nominal-users"
  environment_vars = read_terragrunt_config(find_in_parent_folders("environment.hcl")).locals
  role = read_terragrunt_config(find_in_parent_folders("role.hcl")).locals
}

inputs = {
  environment = local.environment_vars.environment
  type = local.role.type
  username = "sergiohgs"

  roles = [
    {
      database_name = "admin"
      collection_name = ""
      role_name = "readAnyDatabase"
    }
  ]

  scope_name = [
    "mgo-prd-tmp-bil", 
    "eng-prd-mas-db-mongo-230-01", 
    "mgo-prd-bil"
  ]
}

Terraform CLI and Terraform MongoDB Atlas Provider Version

Terraform v1.6.6

provider:

#  # ------------------------------------------------------------------------------
#  # TERRAGRUNT CONFIGURATION
#  # ------------------------------------------------------------------------------

terraform {
  source               = "${local.blueprint_repository}//${local.component_name}?ref=${local.component_version}"
}

locals {
  repo_root            = run_cmd("--terragrunt-quiet", "git", "rev-parse", "--show-toplevel")
  blueprint_repository = "git::https://github.com/tag-trade-repository/tf-module-atlas.git"
  #component_version_type = can(regex("^([0-9]\\.+)", local.component_version)) ? "v${local.component_version}" : "${local.component_version}"
  component_name       = tostring(run_cmd("--terragrunt-quiet", "${local.repo_root}/_bin/read-component-value.sh", "component_name", "${local.repo_root}/${path_relative_to_include()}/"))
  component_version    = tostring(run_cmd("--terragrunt-quiet", "${local.repo_root}/_bin/read-component-value.sh", "component_version", "${local.repo_root}/${path_relative_to_include()}/"))
}

# Generate the remote state block
remote_state {
  backend = "gcs"
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite"
  }
  config = {
    bucket = "gcs-db-services-tfstate"
    prefix = "${path_relative_to_include()}/terraform.tfstate"
  }
}

# Generate the provider block
generate "provider" {
  path = "provider.tf"
  if_exists = "overwrite"
  contents = <<EOF
    provider "mongodbatlas" {}
EOF
} 

# Generate the version block
generate "versions" {
  path = "versions.tf"
  if_exists = "overwrite"
  contents = <<EOF
    terraform {
      required_providers {
        mongodbatlas = {
          source = "mongodb/mongodbatlas"
        }
      }
    }
EOF
}

Steps to Reproduce

terragrunt init
terragrunt plan
terragrunt apply

Expected Behavior

the apply should create the user

Actual Behavior

Got an error

https://cloud.mongodb.com/api/atlas/v2/groups/5f9ae09f623d2e2943ee8dd7/databaseUsers
POST: HTTP [40](https://github.com/tag-trade-repository/mongodb-atlas-org/actions/runs/7574016372/job/20627877078#step:11:41)0 Bad Request (Error code: "INVALID_ATTRIBUTE") Detail: Invalid
attribute roleName specified. Reason: Bad Request. Params: [roleName]

Crash Output

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of mongodb/mongodbatlas from the dependency lock file
- Reusing previous version of hashicorp/random from the dependency lock file
- Using previously-installed mongodb/mongodbatlas v1.14.0
- Using previously-installed hashicorp/random v3.6.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
random_password.default: Refreshing state... [id=none]

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # mongodbatlas_database_user.developer[0] will be created
  + resource "mongodbatlas_database_user" "developer" ***
      + auth_database_name = "admin"
      + aws_iam_type       = "NONE"
      + id                 = (known after apply)
      + ldap_auth_type     = "NONE"
      + oidc_auth_type     = "NONE"
      + password           = (sensitive value)
      + project_id         = "5f9ae09f623d2e[29](https://github.com/tag-trade-repository/mongodb-atlas-org/actions/runs/7574016372/job/20627877078#step:11:30)43ee8dd7"
      + username           = "user_caiojbm"
      + x509_type          = "NONE"

      + labels ***
          + key   = "Developer"
          + value = "true"
        ***
      + labels ***
          + key   = "Environment"
          + value = "production"
        ***

      + roles ***
          + database_name = "admin"
          + role_name     = "readAnyDatabase"
        ***

      + scopes ***
          + name = "eng-prd-mas-db-mongo-2[30](https://github.com/tag-trade-repository/mongodb-atlas-org/actions/runs/7574016372/job/20627877078#step:11:31)-01"
          + type = "CLUSTER"
        ***
      + scopes ***
          + name = "mgo-prd-bil"
          + type = "CLUSTER"
        ***
      + scopes ***
          + name = "mgo-prd-tmp-bil"
          + type = "CLUSTER"
        ***
    ***

Plan: 1 to add, 0 to change, 0 to destroy.
mongodbatlas_database_user.developer[0]: Creating...

Error: error during database user creation

  with mongodbatlas_database_user.developer[0],
  on main.tf line 39, in resource "mongodbatlas_database_user" "developer":
  39: resource "mongodbatlas_database_user" "developer" ***

https://cloud.mongodb.com/api/atlas/v2/groups/5f9ae09f623d2e2943ee8dd7/databaseUsers
POST: HTTP [40](https://github.com/tag-trade-repository/mongodb-atlas-org/actions/runs/7574016372/job/20627877078#step:11:41)0 Bad Request (Error code: "INVALID_ATTRIBUTE") Detail: Invalid
attribute roleName specified. Reason: Bad Request. Params: [roleName]
time=2024-01-18T18:05:[55](https://github.com/tag-trade-repository/mongodb-atlas-org/actions/runs/7574016372/job/20627877078#step:11:56)Z level=error msg=terraform invocation failed in /home/gitrunner/actions-runner/_work/mongodb-atlas-org/mongodb-atlas-org/terraform/resources/database-users/production/developers/caiojbm/.terragrunt-cache/O4lWeAg4FIkSh4zlrLTslVS8jDI/pzZ6kKKOog-nM-3feLfydekfdws/modules/nominal-users prefix=[terraform/resources/database-users/production/developers/caiojbm] 
time=2024-01-18T18:05:55Z level=error msg=1 error occurred:
	* [/home/gitrunner/actions-runner/_work/mongodb-atlas-org/mongodb-atlas-org/terraform/resources/database-users/production/developers/caiojbm/.terragrunt-cache/O4lWeAg4FIkSh4zlrLTslVS8jDI/pzZ6kKKOog-nM-3feLfydekfdws/modules/nominal-users] exit status 1


Error: Process completed with exit code 1.

Additional Context

Could you guys help me on that?

Thanks,
Cristiana Santos

Copy link
Contributor

Thanks for opening this issue! Please make sure you've followed our guidelines when opening the issue. In short, to help us reproduce the issue we need:

  • Terraform configuration file used to reproduce the issue
  • Terraform log files from the run where the issue occurred
  • Terraform Atlas provider version used to reproduce the issue
  • Terraform version used to reproduce the issue
  • Confirmation if Terraform OSS, Terraform Cloud, or Terraform Enterprise deployment

The ticket CLOUDP-224238 was created for internal tracking.

@Kikivsantos
Copy link
Author

My bad.

https://github.com/mongodb/terraform-provider-mongodbatlas/blob/master/CHANGELOG.md#v1120-2023-09-20

The error is because of the empty (roles.collection_name = "")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant