In this gist you can find some information on how to write a Terraform code to deploy a MongoDB Atlas project, user and cluster.
- MongoDB Atlas account
- Create an organization inside your account
- Create API keys for that organization with permission role set at least to Organization Project Creator
- After API keys are created, set one or more IP addresses to allow those API keys access your MongoDB Atlas endpoints
terraform {
required_version = "1.3.9"
required_providers {
mongodbatlas = {
source = "mongodb/mongodbatlas"
version = "1.8.1"
}
}
}
# variables
variable "mongodbatlas_public_key" {
type = string
}
variable "mongodbatlas_secret_key" {
type = string
}
variable "mongodbatlas_org_id" {
type = string
}
variable "mongodbatlas_ip_address" {
type = string
}
variable "mongodbatlas_mongodb_major_version" {
type = string
description = "Major version of MongoDB. Example: 5.0, 6.0"
}
variable "mongodbatlas_cluster_instance_size_name" {
type = string
description = "M2, M5, and so on (it doesn't accept M0 free cluster)"
}
variable "mongodbatlas_region" {
type = string
description = "For example. AWS -> us-east-1 use US_EAST_1"
}
variable "mongodbatlas_cloud_provider" {
type = string
description = "A cloud provider. For exemple: AWS, GCP, etc"
}
# provider
provider "mongodbatlas" {
public_key = var.mongodbatlas_public_key
private_key = var.mongodbatlas_private_key
}
# resources
resource "mongodbatlas_project" "this" {
org_id = var.mongodbatlas_org_id
name = "my-project"
}
resource "random_password" "this" {
length = 16
special = true
override_special = "_%@"
}
resource "mongodbatlas_database_user" "this" {
username = "admin"
password = random_password.this.result
project_id = mongodbatlas_project.this.id
auth_database_name = "admin"
roles {
role_name = "readWrite"
database_name = "my-db"
}
}
resource "mongodbatlas_project_ip_access_list" "this" {
project_id = mongodbatlas_project.this.id
ip_address = var.mongodbatlas_ip_address
}
resource "mongodbatlas_advanced_cluster" "this" {
project_id = mongodbatlas_project.this.id
name = "my-cluster"
cluster_type = "REPLICASET"
backup_enabled = false
mongo_db_major_version = var.mongodbatlas_mongodb_major_version
replication_specs {
region_configs {
electable_specs {
instance_size = var.mongodbatlas_cluster_instance_size_name
node_count = 3
}
priority = 7
provider_name = var.mongodbatlas_cloud_provider
region_name = var.mongodbatlas_region
}
}
}
# outputs
output "mongodb_connection_strings" {
value = mongodbatlas_advanced_cluster.this.connection_strings
}
If you want, you can set API keys in environment variables instead of using Terraform vars. First you need to export them in your terminal.
export MONGODB_ATLAS_PUBLIC_KEY="YOUR_PUBLIC_KEY"
export MONGODB_ATLAS_PRIVATE_KEY="YOUR_SECRET_KEY"
Now you remove API keys options from mongodbatlas
provider block.
provider "mongodbatlas" {}