Easy Steps to Configure MongoDB Atlas with Terraform and Terraform Cloud

We'll walk through the process of creating MongoDB Atlas resources using Terraform and Terraform Cloud. Terraform is an open-source infrastructure as code (IaC) tool that allows you to provision and manage cloud resources in a declarative way. MongoDB Atlas is a fully-managed cloud database service provided by MongoDB. By combining Terraform and Terraform Cloud, we can streamline the process of provisioning and managing our MongoDB Atlas resources.
If you prefer French, you can watch the video version here
Step 1: Set up Terraform Cloud
Sign up for a Terraform Cloud account (https://app.terraform.io/signup/account)
Create a new organization

Create a terraform Projects

Create a new workspace: you need to choose the best option for your use case (just read each option description), here we will choose CLI-Driven Workflow

Step 2: Set up MongoDB Atlas
Sign up for a Terraform Cloud account (https://account.mongodb.com/account/login
-


In the MongoDB Atlas Organization, on "Settings" section, copy Organization ID

In Organization "Access Manager" section, create API Key With Public and Private key

Provide the required permission to the API Key

Allow your IP CIDR to access MongoDB Atlas
your-ip/32
Copy and save API Public and Private Key Information, we will use it on Terraform Cloud.

Step 3: Integrate MongoGB Atlas with Terraform Cloud
Configure variables and environment variables in Terraform Cloud, with your MongoDB Atlas credentials (API key, Organization ID, etc.)

Step 4: Configure Terraform for MongoDB Atlas
Install Terraform on your local machine (https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
Add the MongoDB Atlas provider to your Terraform configuration file (e.g.,
main.tf)# main.tf provider "mongodbatlas" { public_key = var.mongoDB_Atlas_Public_Key private_key = var.mongoDB_Atlas_Private_Key } # variable.tf variable "mongoDb_Atlas_Public_Key" { description = "Public Key to add on Terraform Cloud" } variable "mongoDb_Atlas_Private_Key" { description = "Private Key to add on Terraform Cloud" }In terraform cloud namespace click on "Overview" and copy the terraform code

Update main.tf and add terraform cloud namespace, with the code copied
# main.tf terraform { cloud { organization = "devsahamerlin" workspaces { name = "mongodb-atlas" } } }Add MongoDB Atlas Version
terraform { cloud { organization = "devsahamerlin" workspaces { name = "mongodb-atlas" } } required_providers { mongodbatlas = { source = "mongodb/mongodbatlas", version = "1.8.0" } } }Your Complete main.tf in this step will look like this
# main.tf terraform { cloud { organization = "devsahamerlin" workspaces { name = "mongodb-atlas" } } required_providers { mongodbatlas = { source = "mongodb/mongodbatlas", version = "1.8.0" } } } provider "mongodbatlas" { public_key = var.mongoDb_Atlas_Public_Key private_key = var.mongoDb_Atlas_Private_Key } variable "mongoDb_Atlas_Public_Key" { description = "Public Key to add on Terraform Cloud" } variable "mongoDb_Atlas_Private_Key" { description = "Private Key to add on Terraform Cloud" }Run
terraform loginto connect to terraform cloudterraform login
Initialize a new Terraform configuration by running
terraform init
Step 5: Define MongoDB Atlas Resources
Use the Terraform MongoDB Atlas provider to define the resources you want to create (e.g., projects, clusters, database users, etc.)
Write the resource definitions in your Terraform configuration
main.tffile(s)resource "mongodbatlas_project" "project" { name = "meanstack" org_id = var.mongogb_atlas_org_id is_collect_database_specifics_statistics_enabled = true is_data_explorer_enabled = true is_performance_advisor_enabled = true is_realtime_performance_panel_enabled = true is_schema_advisor_enabled = true }We add new variables
mongogb_atlas_org_id, let's update terraform cloud variable
Step 4: Plan and Apply the Changes
Terraform provides two crucial commands for managing infrastructure changes: plan and apply. Your terraform main.tf file should look like this now:
# main.tf
terraform {
cloud {
organization = "devsahamerlin"
workspaces {
name = "mongodb-atlas"
}
}
required_providers {
mongodbatlas = {
source = "mongodb/mongodbatlas",
version = "1.8.0"
}
}
}
provider "mongodbatlas" {
public_key = var.mongoDb_Atlas_Public_Key
private_key = var.mongoDb_Atlas_Private_Key
}
variable "mongoDb_Atlas_Public_Key" {
description = "Public Key to add on Terraform Cloud"
}
variable "mongoDb_Atlas_Private_Key" {
description = "Private Key to add on Terraform Cloud"
}
variable "mongogb_atlas_org_id" {
description = "MongoDB Atlas organization ID"
}
resource "mongodbatlas_project" "project" {
name = "meanstack"
org_id = var.mongogb_atlas_org_id
is_collect_database_specifics_statistics_enabled = true
is_data_explorer_enabled = true
is_performance_advisor_enabled = true
is_realtime_performance_panel_enabled = true
is_schema_advisor_enabled = true
}
Run
terraform planto preview the changes Terraform will makeThis command analyzes your Terraform configuration files and compares them to the existing infrastructure (if any) managed by Terraform. It then generates a detailed plan outlining the actions Terraform will take to achieve the desired state defined in your configuration. The plan will typically show:
Resources to be created
Resources to be modified (attributes changing)
Resources to be destroyed (if present)
Review the plan output and ensure everything looks correct

Run
terraform applyto create the MongoDB Atlas resourcesOnce you've reviewed and approved the plan generated by
terraform plan, you can use theapplycommand to execute the planned actions. This will create, modify, or destroy resources as outlined in the plan.Important points about
apply:Irreversible changes: Applying the plan makes permanent changes to your infrastructure. Make sure you understand the plan and have backups before proceeding.
Confirmation prompt: By default,
applywill prompt you for confirmation before making any changes.

if you get error while applying , make sure your IP address is added to Error: error creating Project: POSThttps://cloud.mongodb.com/api/atlas/v1.0/groups: 403 (request "IP_ADDRESS_NOT_ON_ACCESS_LIST") IP address your_ip is not allowed to access this resource.
Verify that your ressource is avaible on MongoDB Atlas

Step 5: Destroy MongoDB Atlas Resources
After you've finished working with the MongoDB Atlas resources created using Terraform, you can destroy them to avoid incurring unnecessary costs. Here's how:
Run
terraform plan -destroyto see which resources will be destroyedReview the plan output to ensure you're destroying the correct resources
Run
terraform destroyto destroy all the MongoDB Atlas resources you createdTerraform will prompt you to confirm the destruction of resources
Type "yes" and press Enter to confirm
It's important to note that the terraform destroy command will permanently delete all the resources defined in your Terraform configuration. Make sure to back up any important data before running this command.

You can also trigger a "Destroy" run from the user interface to destroy the resources managed by your workspace.

Congratulations !
Using Terraform and Terraform Cloud for managing MongoDB Atlas resources offers several key benefits and advantages:
Infrastructure as Code: Terraform allows you to define your MongoDB Atlas resources as code, making it easier to manage, version, and collaborate on your infrastructure configurations.
Version Control: By storing your Terraform configurations in a version control system like Git, you can track changes, revert to previous states, and collaborate with team members more effectively.
Automated Workflows: Terraform Cloud enables automated workflows for provisioning and managing your MongoDB Atlas resources. You can trigger runs based on various events, such as code changes or scheduled intervals, streamlining the deployment process.
Collaboration and Governance: Terraform Cloud provides features for team collaboration, including access controls, policy enforcement, and centralized management of Terraform configurations and state files.
Consistency and Reproducibility: With Terraform, you can ensure consistent and reproducible deployments of your MongoDB Atlas resources across different environments (development, staging, production), reducing the risk of configuration drift.
Resource Lifecycle Management: Terraform not only provisions resources but also manages their lifecycle. You can easily update or destroy resources as needed, ensuring efficient resource management and cost optimization.
Multi-Cloud and Multi-Provider Support: While this blog post focuses on MongoDB Atlas, Terraform supports a wide range of cloud providers and services, making it a versatile tool for managing your entire infrastructure.
By leveraging Terraform and Terraform Cloud for managing MongoDB Atlas resources, you can benefit from a streamlined, version-controlled, and collaborative approach to infrastructure provisioning and management. This not only improves efficiency and consistency but also enables better governance, compliance, and cost optimization for your MongoDB Atlas deployments.







