Infrastructure as code provides a consistent and reliable way to manage database resources in the cloud. Terraform is a powerful infrastructure-as-code tool that allows you to manage and provision IT resources in an efficient and predictable way. By using it in conjunction with MongoDB Atlas, you can automate the creation and management of database resources in the cloud, ensuring a consistent and reliable infrastructure.
MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing and managing data. It is known for its document-oriented data model, which allows you to store data in JSON-like documents. MongoDB is widely used in modern web applications, mobile apps, and other data-intensive use cases. MongoDB is designed to be highly scalable and fault-tolerant, making it a great choice for applications that require high availability and performance.
When MongoDB runs on AWS, automation options expand. This is a great way to automate the deployment of MongoDB on AWS using Terraform. Remember to delete the stacks after you are done to avoid any charges. In practice two deployment scenarios are common: running MongoDB as a service on Amazon Elastic Container Service and leveraging Amazon DocumentDB, a fully managed, MongoDB-compatible database service. By following the step-by-step walkthrough, you learned how to automate your MongoDB deployments on AWS, ensuring they are secure, scalable, and cost-effective.
Terraform and MongoDB Atlas Fundamentals
The Terraform MongoDB Atlas Provider allows one to use Terraform with MongoDB's Database as a Service offering, Atlas. The provider repository is the authoritative source for integration between Terraform and Atlas.
To use a released provider in your Terraform environment, run terraform init and Terraform will automatically install the provider. To specify a particular provider version when installing released providers, see the Terraform documentation on provider versioning.
Support for the Terraform MongoDB Atlas Provider is provided under MongoDB Atlas support plans. Please submit support questions within the Atlas UI. Support questions submitted under the Issues section of this repo will be handled on a best effort basis. Bugs should be filed under the Issues section of this repo. Feature requests can be submitted at the MongoDB feedback portal - select Atlas -> infra-as-code as the category or vote for an already suggested feature.
To help with issues, you can turn on Logs with export TF_LOG=TRACE.
Provider Setup and Authentication
To get started, you will need to install Terraform in your development environment. This step is crucial as it is the basis for running all the scripts and infrastructure definitions we will create. After installation, the next step is to configure Terraform to work with MongoDB Atlas. You will need an API key that has permission to create a project at this time.
To create an API key, you must:
- Select Access Manager at the top of the page, and click Organization Access
- Click Create API Key
- Enter a brief description of the API key and the necessary permission. In this case, I put it as Organization Owner. After that, click Next
- Your API key will be displayed on the screen
Release IP in the Access List is optional. If you have enabled your organization to use API keys, the requestor's IP must be released in the Access List; you must include your IP in this list. To validate whether it is enabled or not, go to Organization Settings -> Require IP Access List for the Atlas Administration API
Prerequisites for a typical Atlas Terraform project are:
| Item | Requirement |
|---|---|
| Terraform | 1.0+ |
| MongoDB Atlas account | With an organization |
| Atlas API keys | Public and private |
The Terraform provider configuration for MongoDB Atlas allows Terraform to communicate with the MongoDB Atlas API and manage resources within your account. Add the following block of code to your provider.tf file:
provider "mongodbatlas" {}
In production environments authentication is handled via variables. Provider configuration can be expressed with required_providers block:
terraform {
required_providers {
mongodbatlas = {
source = "mongodb/mongodbatlas"
version = "~> 1.15"
}
}
}
Provider block with variables:
provider "mongodbatlas" {
public_key = var.atlas_public_key
private_key = var.atlas_private_key
}
Variables used for secure configuration:
variable "atlas_public_key" {
description = "MongoDB Atlas public API key"
type = string
sensitive = true
}
variable "atlas_private_key" {
description = "MongoDB Atlas private API key"
type = string
sensitive = true
}
variable "atlas_org_id" {
description = "MongoDB Atlas organization ID"
type = string
}
variable "environment" {
description = "Deployment environment (dev, staging, prod)"
type = string
default = "dev"
}
variable "db_password" {
description = "Password for the application database user"
type = string
sensitive = true
}
variable "readonly_password" {
description = "Password for the read-only database user"
type = string
sensitive = true
}
The safest and most recommended option is to use environment variables. This implies only defining the provider in our Terraform code and exporting the relevant environment variables where Terraform will be executed, whether in the terminal, as a secret in Kubernetes, or a secret in GitHub Actions, among other possible contexts. There are other forms of authentication, such as using MongoDB CLI, AWS Secrets Manager, directly through variables in Terraform, or even specifying the keys in the code. However, to ensure security and avoid exposing our keys in accessible locations, we opt for the safer approaches mentioned.
Version Pinning and Environment Configuration
Inside the versions.tf file, you will start by specifying the version of Terraform that your project requires.
Creating the Terraform version file ensures reproducible builds across teams and CI pipelines.
Pre-requisites for following along with an AWS focused MongoDB deployment are:
- Basic AWS knowledge
- Github account to follow along with Github actions
- An AWS account
- AWS CLI installed and configured
- Basic Terraform knowledge
- Terraform Cloud free account. You can sign up here. Its not mandatory but I have used this for state management in the Terraform scripts. You can use S3 as well
Whether you are a DevOps engineer, a cloud architect, or a developer looking to automate your infrastructure, this blog post will equip you with the knowledge to deploy MongoDB efficiently on AWS using Terraform.
Project and Cluster Provisioning
These steps are essential to ensure the success of creating your replica set cluster.
Creating a Project:
resource "mongodbatlas_project" "main" {
name = "myapp-${var.environment}"
org_id = var.atlas_org_id
}
Provisioning a Cluster:
resource "mongodbatlas_cluster" "main" {
project_id = mongodbatlas_project.main.id
name = "myapp-${var.environment}"
provider_name = "AWS"
provider_region_name = "US_EAST_1"
provider_instance_size_name = var.environment == "prod"
The provider supports several authentication methodologies. The safest and most recommended option is to use environment variables for authentication. The MongoDB Atlas provider, like many others, supports several authentication methodologies.
AWS Deployment Scenarios
Automating MongoDB on AWS using Terraform can be achieved via self-managed containers or managed compatible services. The whole code for this solution is available on Github Here. If you want to follow along, this can be used to stand up your own infrastructure.
Deployment approach comparison:
| Approach | Service | Management Overhead | Use Case |
|---|---|---|---|
| Self managed | MongoDB on ECS | Higher | Full control over version and configuration |
| Managed compatible | Amazon DocumentDB | Lower | MongoDB API compatibility with AWS operations |
The conclusion from the explored material is that we explored how to deploy MongoDB on AWS using Terraform. We covered two deployment scenarios: running MongoDB as a service on Amazon Elastic Container Service and leveraging Amazon DocumentDB, a fully managed, MongoDB-compatible database service.
Workspace and Lifecycle Operations
Practical workflow for local development:
- Copy example variables file and edit
- Create a new Terraform Workspace
- Prepare working directory
- Apply infrastructure
- Connect and validate
- Destroy infrastructure
Commands:
cp -v terraform.tfvars.example terraform.tfvars
terraform workspace new local
terraform init
terraform apply -auto-aprove
If using mongo shell, just connect with the cluster and run your MongoDB commands:
mongosh "mongodb+srv://cluster01.<REPLACE>.mongodb.net/myApp" --username "my_user" --password "pass986@41"
db.products.insertOne( { item: "card", qty: 15 } ); db.products.find();
Destroy previously-created infrastructure:
terraform destroy
After copying the example file with the command above, you must edit the file to add your mongodbatlasorg_id and update any desired variable.
Documentation about the provider specific configuration options can be found on the provider's website.
Conclusion
Terraform automation for MongoDB delivers repeatable, versioned, and auditable infrastructure for both Atlas managed clusters and self-managed AWS deployments. The combination of provider version pinning, environment variable authentication, and workspace isolation creates a secure foundation for dev, staging, and prod environments.
Project creation and cluster provisioning are expressed declaratively, allowing teams to promote infrastructure changes through code review rather than manual console actions. Using sensitive variables for API keys and database passwords prevents secret leakage, while IP access list enforcement adds an additional layer of protection for Atlas administration APIs.
For AWS scenarios, Terraform enables side-by-side evaluation of containerized MongoDB on ECS versus DocumentDB compatibility, with the ability to tear down stacks to avoid charges. The workflow of init, workspace creation, plan, apply, and destroy provides a complete lifecycle that aligns with CI/CD pipelines and GitHub Actions automation.
Adopting these patterns reduces operational drift, improves compliance, and accelerates delivery for DevOps engineers, cloud architects, and developers automating MongoDB infrastructure at scale.
Sources
- https://samuelmolling.github.io/publications/mongodb-atlas-with-terraform
- https://github.com/mongodb/terraform-provider-mongodbatlas
- https://samuelmolling.github.io/publications/mongodb-atlas-with-terraform-cluster-and-backup-policies
- https://amlanscloud.com/mongodeploy/
- https://oneuptime.com/blog/post/2026-03-31-mongodb-how-to-provision-mongodb-atlas-with-terraform/view
- https://github.com/leogomesdev/mongodb-terraform-deployment