Creating an Atlas Cluster from a Terraform Template in MongoDB
Last Updated :
04 Apr, 2024
Introducing automation into database management can greatly enhance efficiency and consistency. MongoDB Atlas, a popular cloud database service, offers a convenient platform for managing MongoDB databases. By using Terraform, an Infrastructure as Code (IaC) tool, users can automate the provisioning and management of MongoDB Atlas clusters.
In this article, We will learn the process of creating an Atlas Cluster from a Template using Terraform, providing a structured approach to setting up and configuring MongoDB Atlas clusters in a scalable and repeatable manner
What is Terraform?
- Terraform is an Infrastructure as Code (IaC) tool used for building, changing, and versioning infrastructure safely and efficiently.
- It uses a high-level configuration language (HCL) to describe the desired state of your infrastructure.
- Terraform supports multiple cloud providers (AWS, Azure, Google Cloud, etc.) and other infrastructure platforms (VMware, Docker, etc.).
- It manages resources across providers, allowing us to create, update, and delete infrastructure components as needed.
- Terraform maintains a state file to keep track of the current state of our infrastructure and to plan and execute changes
Prerequisites
Before going, Please ensure that you have the following prerequisites:
- MongoDB for VS Code installed
- Terraform installed
- An Atlas account
- An Atlas organization
- An API key with the Organization Owner or Organization Project Creator role
Steps to Create an Atlas Cluster
1. Create an Atlas Terraform File using the Template
Use the Atlas template for Terraform files included with the MongoDB for VS Code to configure an Atlas cluster:

2. Update the Atlas Terraform Configuration to Configure Our Cluster
To update the Atlas Terraform configuration to configure your cluster, you need to provide values for each of the attributes mentioned. Below is a guide to help you update the configuration:
- mongodbatlas_project .name: Name of the Atlas project.
- Value: Specify a name for your Atlas project.
- mongodbatlas_cluster.name: Name of the Atlas cluster.
- Value: Choose a name for your Atlas cluster.
- mongodbatlas_cluster.backing_provider_name: Provider on which the Atlas cluster is hosted.
- Value: Choose one of the accepted values: AWS, AZURE, GCP.
- mongodbatlas_cluster.provider_region_name: Region to which the Atlas cluster is deployed.
- Value: Select a region supported by your chosen provider and compatible with the instance size you want to deploy.
- mongodbatlas_cluster.provider_instance_size_name: Instance size of the Atlas cluster.
- Value: Choose one of the shared tier instance sizes (M2 or M5) or another supported instance size.
- mongodbatlas_cluster.disk_size_gbs: Disk size of the Atlas cluster.
- Value: Enter a value equal to or less than the maximum disk size allowed for the instance size chosen (2 for M2 clusters, 5 for M5 clusters).
3. Update the Local Variables
Warning: The local variables contain sensitive information. Do not check these values in to a repository that is available publicly.
Provide values for the following local variables:
- Atlas Public API Key:
- Variable Name: mongodb_atlas_api_pub_key
- Description: Public API key required for accessing MongoDB Atlas services.
- New Value: Input the designated Atlas public API key here.
- Atlas Private API Key:
- Variable Name: mongodb_atlas_api_pri_key
- Description: Private API key used for secure interactions with MongoDB Atlas.
- New Value: Enter the corresponding Atlas private API key in this field.
- Atlas Organization ID:
- Variable Name: mongodb_atlas_org_id.
- Description: Unique identifier of the Atlas organization where the project will be created.
- New Value: Specify the organization ID where you intend to create the project in Atlas.
- Database Username:
- Variable Name: mongodb_atlas_database_username
- Description:Username assigned to the MongoDB database user, automatically generated by Atlas for your cluster.
- New Value: Provide the desired username for accessing the MongoDB database.
- Database User Password:
- Variable Name: mongodb_atlas_database_user_password
- Description: Secure password associated with the MongoDB database user specified in mongodb_atlas_database_username.
- New Value: Set a strong and confidential password for authentication purposes.
- Atlas Whitelist IP:
- Variable Name: mongodb_atlas_whitelistip
- Description: IP address or CIDR block defining the authorized access to your Atlas cluster.
- New Value: Specify the IP address or CIDR block from which access to your Atlas cluster is permitted.
Example: Maximizing Security with Input Variables File
Use an Input Variables File to Maximize security
To maximize security, consider taking the following steps :
a. Create an Input Variables File:
Begin by creating an input variables file (e.g., vars.tfvars) where you'll define your sensitive data. This file will securely store your MongoDB Atlas API keys.
# vars.tfvars
variable "mongodb_atlas_api_pub_key" {
default = "my-public-key"
}
variable "mongodb_atlas_api_pri_key" {
default = "my-private-key"
}
b. Exclude Input Variables File from Version Control:
For enhanced security, ensure that the input variables file is excluded from your repository. Add the filename (vars.tfvars) to your .gitignore file to prevent it from being tracked by version control systems.
# .gitignore
vars.tfvars
c. Reference Variables in Main Configuration File:
In your main configuration file (main.tf), reference the variables defined in the input variables file. Prefix the variable names with vars. to access them.
provider "mongodbatlas" {
public_key = vars.mongodb_atlas_api_pub_key
private_key = vars.mongodb_atlas_api_pri_key
}
4. Adding Optional Configuration Options to the Terraform Main Configuration File
When configuring your MongoDB Atlas clusters using Terraform, you may want to include optional configurations to tailor the setup according to your specific requirements. Here's a brief note with sample code on how to add optional configuration options to your Terraform .tf file:
# main.tf
provider "mongodbatlas" {
// Specify your MongoDB Atlas provider configuration here
// For example:
public_key = var.mongodb_atlas_api_pub_key
private_key = var.mongodb_atlas_api_pri_key
}
resource "mongodbatlas_cluster" "my_cluster" {
// Define your MongoDB Atlas cluster configuration here
// Add any optional configurations as needed
// For example:
name = "my-cluster"
cluster_type = "REPLICASET"
provider_instance_size_name = "M10"
disk_size_gb = 40
// Add more configurations as required
}
5. Create the Atlas Cluster using Terraform
After we create a Terraform file using the template, create the Atlas cluster:
1. Go to the directory containing your main.tf file.
2. 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.
3. Run the terraform plan command to view what happens when you apply the configuration
terraform plan
Here's the combined breakdown of the Terraform execution plan output:
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# mongodbatlas_cluster.my_cluster will be created
+ resource "mongodbatlas_cluster" "my_cluster" {
...
}
# mongodbatlas_database_user.my_user will be created
+ resource "mongodbatlas_database_user" "my_user" {
...
}
# mongodbatlas_project.my_project will be created
+ resource "mongodbatlas_project" "my_project" {
...
}
# mongodbatlas_project_ip_whitelist.my_ipaddress will be created
+ resource "mongodbatlas_project_ip_whitelist" "my_ipaddress" {
...
}
Plan: 4 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions
will be performed if "terraform apply" is subsequently run.
6. Delete the Atlas Cluster using Terraform
Deleting a cluster destroys databases, collections, and documents stored on it and all other resources defined in the Terraform configuration in which you configured the cluster. Proceed with caution. To delete the Atlas cluster:
- Navigate to the directory in which you saved your main.tf file.
- Run the terraform destroy command to install the required providers.
- Type yes when prompted to confirm that you want to destroy the resources defined in the configuration.
Note: The terraform destroy command might take several minutes to complete. The following output indicates that the Atlas cluster and all associated resources are deleted:
Destroy complete! Resources: 4 destroyed.
Conclusion
In conclusion, by understanding the Terraform to automate the creation of MongoDB Atlas clusters significantly fast the deployment process. It enhances efficiency, ensures consistency in configurations, and enables scalability. By following the steps outlined in this guide, users can easily manage and maintain their MongoDB Atlas clusters, improving overall infrastructure management. This approach not only saves time and effort but also enhances the reliability and security of MongoDB Atlas deployments.
Similar Reads
Creating and Deploying an Atlas Cluster in MongoDB
MongoDB Atlas is a fully-managed cloud database platform that simplifies deploying, managing, and scaling MongoDB clusters in the cloud. Whether you're a developer or a database administrator, understanding how to set up and deploy a MongoDB Atlas cluster is crucial for leveraging MongoDBâs powerful
6 min read
How to Connect MongoDB Atlas Cluster From an Application?
To connect your application to MongoDB Atlas, a cloud-based, fully-managed NoSQL database, you'll first need to set up a MongoDB Atlas cluster and configure a few essential settings. MongoDB Atlas offers a secure, scalable platform to manage your database without the hassle of manual maintenance, ba
7 min read
Convert a Replica Set to a Sharded Cluster in Mongodb
MongoDB provides high availability and scalability through replica sets and sharding. A replica set ensures data redundancy and fault tolerance while sharding distributes data across multiple servers to handle large datasets and high traffic efficiently. You can convert it into a shared cluster if y
3 min read
Creating AWS DynamoDB Table Using Terraform
I'm going to show how to use Terraform to create a DynamoDB table in AWS. Terraform lets you define infrastructure like databases as code. This makes it easy to version control and share with others. In this article, I'll walk through the steps to set up a Terraform file and define a DynamoDB table
15+ min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. We might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. By connecting MongoDB Atlas, the fully managed cloud database service, to MongoDB Compass, developers can easily interact with th
6 min read
How To Create EMR Cluster In AWS Using Terraform ?
In today's data-driven world, big data processing has become an integral part of many organizations' workflows. Amazon EMR (Elastic MapReduce) is a cloud-based platform provided by Amazon Web Services (AWS) that simplifies the process of running and scaling Apache Hadoop and Apache Spark clusters fo
10 min read
How To Create AKS Cluster In Azure Using Terraform ?
Azure AKS also called as Azure Kubernetes Service is service that provides Kubernetes implementation in the Azure cloud. Azure Kubernetes service is a managed service that allows deployment of containerized applications in azure cloud. Setting up a Kubernetes cluster in azure is tedious task so lets
4 min read
How to Get the Database URL in MongoDB
When working with MongoDB, it is important to know how to retrieve the database URL because as it enables applications to connect to the database. In this article, we'll explore how to obtain the database URL in MongoDB by covering various scenarios and providing examples.How to Get the Database URL
3 min read
How to Change the Data Store Directory in MongoDB?
In MongoDB, data files are stored by default in the /data/db directory on Unix-like systems and \data\db on Windows. This default setting may not be suitable for all applications particularly large-scale ones or if the default drive lacks sufficient space. In this article, we will learn about How to
3 min read
How to Copy a Collection From One Database to Another in MongoDB?
Effective data management is crucial for MongoDB-dependent applications. As databases grow, the need to transfer collections between databases arises. This can be for creating development or testing environments, migrating data, or archiving historical information. MongoDB provides built-in capabili
6 min read