Managing a MongoDB Atlas deployment through the web console works for exploration, but production databases need repeatability, auditability, and coordination with the rest of the infrastructure. Terraform provides that layer. By describing clusters, users, network access, and backup policies as code, the entire Atlas footprint becomes version-controlled, reproducible, and consistent across environments.
MongoDB Atlas is the managed database service for MongoDB, and managing it through Terraform makes sense when your clusters are part of a larger infrastructure setup. Instead of clicking through the Atlas web console to create clusters, configure users, and set up network peering, you define everything in code. This means your database infrastructure is version-controlled, reproducible, and consistent across environments. The MongoDB Atlas Terraform provider covers cluster management, database users, network access, backup configuration, and more.
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.
Provider Installation and Initialization
The first operational step is getting Terraform to recognize the MongoDB Atlas provider.
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.
Documentation about the provider specific configuration options can be found on the provider's website. To help with issues, you can turn on Logs with export TF_LOG=TRACE.
Create the Atlas Cluster using Terraform after the Terraform file is created. The initialization workflow is:
- Go to the directory containing your main.tf file.
- Execute terraform init to install necessary providers.
terraform init
The following output indicates that the MongoDB Atlas Terraform Provider is installed and ready for use:
- Initializing the backend: This step involves setting up the backend configuration for Terraform, which could include storing the state file remotely for collaboration and version control.
- Initializing provider plugins: Terraform is checking for available provider plugins, which are responsible for managing resources in different infrastructure providers.
- Downloading plugin for provider "mongodbatlas": Terraform is downloading the MongoDB Atlas Terraform Provider plugin. The version specified is 0.5.1.
- Version constraints: It's recommended to add version constraints to prevent automatic upgrades to new major versions that may contain breaking changes. For the mongodbatlas provider, the suggested constraint is ~> 0.5, which means it will use version 0.5.x but not automatically upgrade to version 1.0 or higher.
- Initialization complete: Terraform has been successfully initialized, and the MongoDB Atlas Terraform Provider is ready for use.
Version pinning is important for teams. Creating the Terraform version file starts by specifying the version of Terraform that your project requires. Inside versions.tf file, you will start by specifying the version of Terraform that your project requires.
A typical versions constraint block looks like:
terraform {
required_version = ">= 1.0"
required_providers {
mongodbatlas = {
source = "mongodb/mongodbatlas"
version = "~> 0.5"
}
}
}
Authentication to Atlas
Terraform must authenticate to the Atlas API before it can read or write resources. The repository for the Terraform MongoDB Atlas Provider, which allows one to use Terraform with MongoDB's Database as a Service offering, Atlas. Learn more about Atlas at https://www.mongodb.com/cloud/atlas.
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.
Authentication options have evolved toward least privilege and secret management.
Terraform provider configuration for MongoDB Atlas is the first step to configure the Terraform provider for MongoDB Atlas. This will allow 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 the previous article, we configured the Terraform provider by directly entering our public and private keys. Now, in order to adopt more professional practices, we have chosen to use environment variables for authentication. The MongoDB Atlas provider, like many others, supports several authentication methodologies. 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.
The guide for enterprise deployments uses an Atlas Service Account for authentication. Service Accounts are the recommended authentication method for programmatic access.
Set your Service Account credentials as environment variables:
export MONGODB_ATLAS_CLIENT_ID="<your-client-id>"
export MONGODB_ATLAS_CLIENT_SECRET="<your-client-secret>"
Service Accounts are the recommended authentication method for programmatic access with Terraform.
For API key based access, 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.
Core Provider Capabilities
You can use Terraform to manage your MongoDB Atlas infrastructure as code with the Atlas Terraform provider. The Atlas Terraform provider automates infrastructure deployments by simplifying the process to provision, manage, and control Atlas infrastructure as code.
This guide teaches you how to create, modify, and destroy Atlas clusters in an existing MongoDB Atlas organization and project.
Once you have configured a test environment, continue to experiment with a Terraform-managed infrastructure with additional resources from MongoDB and HashiCorp.
The provider covers:
| Capability | Example Resources |
|---|---|
| Cluster management | mongodbatlas_cluster |
| Database users | mongodbatlasdatabaseuser |
| Network access | mongodbatlasprojectipaccesslist |
| Backup configuration | mongodbatlascloudbackupsnapshotschedule |
| Project and organization | mongodbatlasproject, mongodbatlasorganization |
Before deploying MongoDB Atlas with Terraform, you must update configuration fields in your main.tf file. The provider expects organization ID and project ID, plus authentication credentials via environment variables.
You can output information from your Terraform configuration to your terminal window. This is useful for values you won't know until Atlas creates the resources, such as your connection string.
If you want to display your parameters after you deploy your project, add some output lines of code to your main.tf file.
To deploy your infrastructure, run the following command:
terraform apply
When prompted Do you want to perform these actions?, enter yes.
Note New Atlas resources can take a few minutes to provision.
Enterprise Deployment with Official Modules
This guide walks you through deploying an enterprise-ready MongoDB Atlas environment using the official Terraform MongoDB Atlas Modules, which facilitate going from zero to a full Atlas deployment using Terraform.
Each module is a reusable building block that provisions Atlas resources alongside dependencies required for secure and private connectivity with cloud providers.
This guide provides examples to deploy the following resources in AWS, Azure, or Google Cloud:
An Atlas project and sharded cluster.
Cloud provider networking with PrivateLink connectivity.
Backup export to cloud storage.
An optional validation virtual machine to confirm end-to-end connectivity (not currently available in Google Cloud. A virtual machine will be available in a future update).
Prerequisites before starting include tools and credentials. This guide uses an Atlas Service Account for authentication. Service Accounts are the recommended authentication method for programmatic access with Terraform.
Set your Service Account credentials as environment variables:
export MONGODB_ATLAS_CLIENT_ID="<your-client-id>"
export MONGODB_ATLAS_CLIENT_SECRET="<your-client-secret>"
Note Service Accounts are the recommended authentication method for programmatic access with Terraform.
The module approach separates concerns. The landing zone modules handle project creation, cluster provisioning, network peering, PrivateLink/VPC peering, and backup export. This reduces boilerplate and enforces secure defaults.
Typical workflow steps:
- Initialize provider and modules
- Define variables for cloud provider, region, cluster tier
- Apply to create project and cluster
- Apply networking module for PrivateLink
- Apply backup export module to cloud storage
Practical Configuration Patterns
Terraform provider configuration for MongoDB Atlas starts minimal and grows with requirements.
Minimal provider block:
provider "mongodbatlas" {}
With explicit project and organization references:
resource "mongodbatlas_cluster" "example" {
project_id = var.project_id
name = "example-cluster"
cluster_type = "REPLICA_SET"
replication_specs {
region_configs {
region_name = "US_EAST_1"
electable_count = 3
priority = 7
}
}
}
Outputs for connection strings:
output "connection_string" {
value = mongodbatlas_cluster.example.mongo_uri
sensitive = true
}
These steps are essential to ensure the success of creating your replica set cluster.
The first step is to configure the Terraform provider for MongoDB Atlas. This will allow Terraform to communicate with the MongoDB Atlas API and manage resources within your account.
Operational Tips
Keep state remote and encrypted. Initialization completes the backend setup which could include storing the state file remotely for collaboration and version control.
Pin provider versions to avoid unexpected breaking changes. The suggested constraint is ~> 0.5, which means it will use version 0.5.x but not automatically upgrade to version 1.0 or higher.
Use environment variables for all secrets. Do not commit API keys or client secrets.
Validate IP access list requirements in Organization Settings before running apply in restricted environments.
Expect provisioning latency. New Atlas resources can take a few minutes to provision.
Use TF_LOG=TRACE for troubleshooting provider API interactions.
Conclusion
Terraform with MongoDB Atlas shifts database operations from manual clicks to declarative infrastructure. The Atlas Terraform provider covers cluster management, database users, network access, backup configuration, and more, allowing a full database lifecycle to be versioned alongside application code.
Authentication best practice has moved to Service Accounts with environment variables, replacing long-lived API keys in code. Provider initialization, version pinning, and remote state management form the foundation for reliable runs.
For enterprise requirements, official Terraform MongoDB Atlas Modules add reusable building blocks for projects, sharded clusters, PrivateLink connectivity, and backup exports to cloud storage. These modules enforce secure connectivity patterns across AWS, Azure, and Google Cloud while keeping the core provider configuration minimal.
The combination of the core provider for granular control and the modules for landing zone patterns gives teams a path from a single development cluster to a production-grade, multi-cloud Atlas footprint managed entirely as code.
Sources
- oneuptime.com/blog/post/2026-02-23-how-to-configure-mongodb-atlas-provider-in-terraform/view
- samuelmolling.github.io/publications/mongodb-atlas-with-terraform
- github.com/mongodb/terraform-provider-mongodbatlas
- www.mongodb.com/docs/atlas/terraform/
- www.mongodb.com/docs/atlas/terraform-modules-landing-zone/
- www.geeksforgeeks.org/devops/creating-an-atlas-cluster-from-a-terraform-template-in-mongodb/
- samuelmolling.github.io/publications/mongodb-atlas-with-terraform-cluster-and-backup-policies