Skip to main content

Command Palette

Search for a command to run...

Easy Steps to Configure MongoDB Atlas with Terraform and Terraform Cloud

Updated
7 min read
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

  1. Sign up for a Terraform Cloud account (https://app.terraform.io/signup/account)

  2. Create a new organization

  3. Create a terraform Projects

  4. 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

  1. Sign up for a Terraform Cloud account (https://account.mongodb.com/account/login

  2. Create a new organization

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

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

  5. Provide the required permission to the API Key

  6. Allow your IP CIDR to access MongoDB Atlas your-ip/32

  7. 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

  1. Install Terraform on your local machine (https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)

  2. 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"
     }
    
  3. In terraform cloud namespace click on "Overview" and copy the terraform code

  4. Update main.tf and add terraform cloud namespace, with the code copied

     # main.tf
     terraform {
       cloud {
         organization = "devsahamerlin"
    
         workspaces {
           name = "mongodb-atlas"
         }
       }
     }
    
  5. Add MongoDB Atlas Version

     terraform {
       cloud {
         organization = "devsahamerlin"
    
         workspaces {
           name = "mongodb-atlas"
         }
       }
       required_providers {
         mongodbatlas = {
           source  = "mongodb/mongodbatlas",
           version = "1.8.0"
         }
       }
     }
    
  6. 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"
     }
    
  7. Run terraform login to connect to terraform cloud

     terraform login
    

  8. Initialize a new Terraform configuration by running terraform init

Step 5: Define MongoDB Atlas Resources

  1. Use the Terraform MongoDB Atlas provider to define the resources you want to create (e.g., projects, clusters, database users, etc.)

  2. Write the resource definitions in your Terraform configuration main.tf file(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
}
  1. Run terraform plan to preview the changes Terraform will make

    This 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)

  2. Review the plan output and ensure everything looks correct

  3. Run terraform apply to create the MongoDB Atlas resources

    Once you've reviewed and approved the plan generated by terraform plan, you can use the apply command to execute the planned actions. This will create, modify, or destroy resources as outlined in the plan.

    Important points aboutapply:

    • 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, apply will 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.

  1. 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:

  1. Run terraform plan -destroy to see which resources will be destroyed

  2. Review the plan output to ensure you're destroying the correct resources

  3. Run terraform destroy to destroy all the MongoDB Atlas resources you created

  4. Terraform will prompt you to confirm the destruction of resources

  5. 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:

  1. 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.

  2. 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.

  3. 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.

  4. Collaboration and Governance: Terraform Cloud provides features for team collaboration, including access controls, policy enforcement, and centralized management of Terraform configurations and state files.

  5. 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.

  6. 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.

  7. 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.