Using MongoDb with Terraform

Bouajina Montassar
2 min readNov 6, 2020

In This article i will show you how to provision database users and roles using terraform with mongodb provider from terraform.

Did you come across a need to provision a database user or a database role with Terraform and you couldn’t find a solution ?
I did and i found myself using a Mongo client with a null_resource from Terraform and the was sad:(

Hopefully there’s another solution.

So i create a Terraform provider that can help us :D

Thanks to Kaginari’s mongodb provider now we can provision database users and role using Terraform

https://registry.terraform.io/providers/Kaginari/mongodb/latest/docs

1- Configuring the provider :

provider "mongodb" {
host = "127.0.0.1"
port = "27017"
username = "root"
password = "root"
auth_database = "admin"
}

2- another way to configure it :

You can also provide your credentials via the environment variables, MONGO_HOST, MONGO_PORT, MONGO_USR, and MONGO_PWD respectively:

provider "mongodb" {
auth_database = "admin"
}

3- Creating a database user :

3.1 - create user with predefined role :

resource "mongodb_db_user" "user" {
auth_database = "my_database"
name = "example"
password = "example"
role {
role = "readAnyDatabase"
db = "my_database"
}
}

4 - Creating a database custom role :

4.1 - Create a custom role :

resource "mongodb_db_role" "example_role" {
name = "role_name"
database = "my_database"
privilege {
db = "admin"
collection = "*"
actions = ["collStats"]
}
privilege {
db = "my_database"
collection = ""
actions = ["listCollections", "createCollection"]
}
}

4.2 - Create custom role with inherited roles :

resource "mongodb_db_role" "role" {
database = "admin"
name = "new_role"
privilege {
db = "admin"
collection = ""
actions = ["collStats"]
}
}

resource "mongodb_db_role" "role_2" {
depends_on = [mongodb_db_role.role]
database = "admin"
name = "new_role3"

inherited_role {
role = mongodb_db_role.role.name
db = "admin"
}
}

5- Creating a database user with custom role(s):

variable "username" {
description = "the user name"
}
variable "password" {
description = "the user password"
}

resource "mongodb_db_user" "user_with_custom role" {
depends_on = [mongodb_db_role.example_role]
auth_database = "my_database"
name = var.username
password = var.password
role {
role = mongodb_db_role.example_role.name
db = "my_database"
}
role {
role = "readAnyDatabase"
db = "admin"
}
}

Conclusion

Currently the provider help us to provision database and users , next releases will support much more resources as i am counting on you with you feedback to help me see what else we can add to the provider.

--

--