Open In App

Creating an Atlas Cluster from a Terraform Template in MongoDB

Last Updated : 04 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Atlas Terraform file using the template

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads