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.
Why Infrastructure as Code for MongoDB Atlas
Managing Atlas through code removes manual steps from the console and places database operations alongside the rest of an application platform. With Terraform, clusters, users, network access, and backups become declarative resources that can be reviewed, tested, and rolled back.
The 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 additional resources from MongoDB and HashiCorp.
Provider Installation and Initialization
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.
The typical initialization workflow for an Atlas project 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.
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
Authentication Strategies and API Key Management
To get started, you’ll 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
For programmatic access, service accounts are the recommended method. This guide 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>"
Note Service Accounts are the recommended authentication method for programmatic access with Terraform
The Terraform provider for MongoDB Atlas supports several authentication methodologies. The safest and most recommended option is to use environment variables. This implies only defining the provider in your 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.
Provider Configuration and Version Management
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.
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.
Creating the Terraform version file
Inside the versions.tf file, you will start by specifying the version of Terraform that your project requires.
Before deploying MongoDB Atlas with Terraform, you must update the following fields in your main.tf file:
| Field | New Value |
|---|---|
| Your provider. Possible values are: | See Cloud Providers and Regions for all the regions you can use. |
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
Cluster Provisioning Workflow
Create the Atlas Cluster using Terraform
After we create a Terraform file using the template, create the Atlas cluster:
- Go to the directory containing your main.tf file.
- Execute terraform init to install necessary providers.
- Execute terraform apply to create resources.
The provider covers cluster management, database users, network access, backup configuration, and more.
These steps are essential to ensure the success of creating your replica set cluster.
Terraform Modules for Enterprise Landing Zone
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).
Note Ensure you have the following prerequisites before starting this tutorial:
You need the following tools to go through the process outlined in this guide.
The repository for the Terraform MongoDB Atlas Provider 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.
Operational Best Practices and Troubleshooting
Version pinning prevents unexpected 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.
Keep provider configuration minimal and externalize secrets. Define provider "mongodbatlas" {} in code and supply credentials via environment variables or secret stores.
Use outputs to surface connection strings and resource identifiers after apply. Connection strings are generated by Atlas after provisioning and cannot be known ahead of time.
Enable detailed logs when diagnosing issues with TF_LOG=TRACE.
Maintain state safely. Initializing the backend to store the state file remotely enables collaboration and version control.
Conclusion
The MongoDB Atlas Terraform provider transforms Atlas operations from manual console work into repeatable, auditable infrastructure as code. Starting with provider installation via terraform init, securing access through API keys or service accounts, and adopting environment variable based authentication creates a safe and reproducible foundation.
Provider configuration remains minimal while versions.tf governs Terraform and provider version constraints. Cluster provisioning follows a standard init and apply cycle, with outputs exposing connection details once Atlas finishes provisioning. For larger environments, official Terraform MongoDB Atlas Modules provide reusable building blocks for projects, sharded clusters, PrivateLink networking, and backup exports across AWS, Azure, and Google Cloud.
Adopting these patterns ensures database infrastructure is version-controlled, consistent across environments, and aligned with enterprise security practices for programmatic access to MongoDB Atlas.