Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Implantando o MongoDB Atlas com o Terraform com o Azure

Karen Zhang7 min read • Published Jun 18, 2024 • Updated Jun 18, 2024
Facebook Icontwitter iconlinkedin icon
Classifique este artigo
star-empty
star-empty
star-empty
star-empty
star-empty
MongoDB Atlas is a fully managed cloud database. It handles the tricky parts of setting up, managing, and fixing your MongoDB databases on any major cloud platform (like AWS, Azure, or GCP). It's the easiest way to get started, run, and grow your MongoDB databases in the cloud.
Terraform is an open-source infrastructure as code (IaC) tool used to manage and provision infrastructure across various platforms, including cloud providers and on-premise data centers. Terraform automates your infrastructure's creation, modification, and destruction, ensuring consistency and repeatability. Terraform has a MongoDB Atlas provider that interacts with the resources supported by MongoDB Atlas.
In this tutorial, we’ll guide you through setting up MongoDB Atlas on the Azure platform and utilizing Terraform for deployment. The source code used in this article can be found in the Repositório do GitHub.

Pré-requisitos

Antes de começarmos, você precisará configurar as seguintes contas/ferramentas:

Configuração do ambiente

Para configurar o ambiente, primeiro geraremos a chave de acesso da API do MongoDB Atlas e, em seguida, configuraremos um método de cobrança.

Gere chaves de acesso Ă  API do MongoDB Atlas

After establishing an account on MongoDB Atlas and logging in, the next step is to generate an API key to verify the Terraform MongoDB Atlas Provider. To do this, select the access manager for the organization and create the access key. Follow the documentation to learn more about creating an API key.
Capture where to create an API key(screenshot from the Atlas UI representing the Organization Access Manager section)
Capture where to create an API key (screenshot from the Atlas UI representing the Organization Access Manager section)
Give your API key a clear name that reflects its purpose, like “Terraform Deployment API Key.” Next, we’ll choose the permissions needed for your Terraform tasks. Both Organization Owner and Organization Project Creator roles allow for enough access to complete this, but the Organization Project Creator role should be chosen following the principle of least privilege. To learn more about the user roles, follow the Organization Roles and Project Roles.
Capture for generating an API key* (screenshot from the Atlas UI representing creating API key section)
Captura para gerar uma chave de API* (captura de tela da UI do Atlas representando a criação da seção de chave de API)
Copie sua chave privada e sua chave pública e, em seguida, configure as variáveis de ambiente:
1export MONGODB_ATLAS_PUBLIC_KEY="<insert your public key here>"
2export MONGODB_ATLAS_PRIVATE_KEY="<insert your private key here>"
Capture for adding current IP to Access List Entry (screenshot from the Atlas UI representing adding access list entry section)
Em seguida, adicionaremos uma entrada de lista de acesso de chave de API para garantir que as chamadas de API originadas de IPs ou intervalos CIDR possam dar acesso. Usamos nosso endereço IP atual e salvamos.

Configurar um método de cobrança

MongoDB allows a free M0 cluster tier that you do not have to pay for. However, if you want to deploy any other clusters, we will have to set up a billing method. Follow the documentation about setting up a billing method.

Criando arquivos de configuração Terraform — variable.tf, terraform.tfvars, e main.tf

We are now going to create a variables.tf file for declaring Terraform variables, a terraform.tfvars file for defining variable values and secrets, and a main.tf for the main Terraform configuration. In Terraform, these configuration files (variables.tf, terraform.tfvars, and main.tf) are typically created within the root directory of your Terraform project. You can find the source code in the RepositĂłrio do GitHub.
Primeiro, definimos os provedores MongoDB Atlas e Azure em main.tf:
1# Define the MongoDB Atlas and Azure Providers
2terraform {
3 required_providers {
4 mongodbatlas = {
5 source = "mongodb/mongodbatlas"
6 version = "=1.16.0"
7 }
8 azurerm = {
9 source = "hashicorp/azurerm"
10 version = "=3.0.0"
11 }
12 }
13}
14Then, we start defining all the variables our configuration will use in the variables.tf file.
O bloco de código abaixo define as variáveis utilizadas. As variáveis incluem identificadores para o projeto e o ambiente, o tamanho dos recursos de computação alocados, a plataforma de nuvem a ser usada (AWS, GCP, Azure), a região específica dentro dessa plataforma, a versão desejada do MongoDB e o(s) endereço(s) IP permissão para acessar o cluster de banco de dados.
1# Atlas Organization ID
2variable "atlas_org_id" {
3 type = string
4 description = "Atlas Organization ID"
5}
6# Atlas Project Name
7variable "atlas_project_name" {
8 type = string
9 description = "Atlas Project Name"
10}
11# Atlas Project Environment
12 variable "environment" {
13 type = string
14 description = "The environment to be built"
15 }
16# Cluster Instance Size Name
17variable "cluster_instance_size_name" {
18 type = string
19 description = "Cluster instance size name"
20}
21# Cloud Provider to Host Atlas Cluster
22variable "cloud_provider" {
23 type = string
24 description = "AWS or GCP or Azure"
25}
26# Atlas Region
27variable "atlas_region" {
28 type = string
29 description = "Atlas region where resources will be created"
30}
31# MongoDB Version
32variable "mongodb_version" {
33 type = string
34 description = "MongoDB Version"
35}
36# IP Address Access
37variable "ip_address" {
38 type = string
39 description = "IP address used to access Atlas cluster"
40}
In the terraform.tfvars file, we specify the use of MongoDB version 7.0, a M10-sized cluster in the US_EAST_2 region on Azure. If you are outside North America, you can refer to the regions supported following the documentation for Microsoft Azure.
Observe que o Atlas oferece suporte a regiões e zonas de disponibilidade específicas do Azure, e algumas regiões não oferecem suporte a clusters gratuitos (M0) e clusters compartilhados (M2/M5).
1atlas_org_id = "<UPDATE WITH YOUR ORG ID>"
2atlas_project_name = "yourProjectName"
3environment = "dev"
4cluster_instance_size_name = "M10"
5cloud_provider = "Azure"
6atlas_region = "US_EAST_2"
7mongodb_version = "7.0"
8ip_address = "<UPDATE WITH YOUR IP>"

Configurando um projeto do MongoDB Atlas

To create a project using Terraform, we will need the MongoDB Atlas Organization ID with at least the Organization Project Creator role. To get this information, we can go to Settings on the left-hand side menu bar in the UI, and we can find Organization Settings with the Organization ID. Please refer to the documentation on Organizations for further reference.
So next, in our main.tffile, we will use the mongodbatlas_project resource from Terraform MongoDB Atlas Provider to create our project. We add this to main.tf:
1# Create a Project
2resource "mongodbatlas_project" "atlas-project" {
3 org_id = var.atlas_org_id
4 name = var.atlas_project_name
5}

Criando um usuário, senha e lista de acesso IP do MongoDB Atlas

We must add a corresponding database user to our MongoDB Atlas project. Refer to the documentation for available user roles in case you want to customize the user’s Role-Based Access Control.
The code block below creates a database user with a random password, and to review the password, you will need to put the terraform output -json user_password command in your terminal.
1# Create a Database User
2resource "mongodbatlas_database_user" "db-user" {
3 username = "user-1"
4 password = random_password.db-user-password.result
5 project_id = mongodbatlas_project.atlas-project.id
6 auth_database_name = "admin"
7 roles {
8 role_name = "readWrite"
9 database_name = "${var.atlas_project_name}-db"
10 }
11}
12# Create a Database Password
13resource "random_password" "db-user-password" {
14 length = 16
15 special = true
16 override_special = "_%@"
17}
18Next, we need to create the IP access list.
19
20# Create Database IP Access List
21resource "mongodbatlas_project_ip_access_list" "ip" {
22 project_id = mongodbatlas_project.atlas-project.id
23 ip_address = var.ip_address
24}
25We will need to put the IP address that we are connecting to the MongoDB Atlas cluster into the terraform.tfvars file.

Provisionando o cluster do MongoDB Atlas

We will now use the mongodbatlas_cluster resource to create a MongoDB Atlas cluster. The resource lets you create, edit, and delete clusters.
1resource "mongodbatlas_cluster" "test" {
2 project_id = mongodbatlas_project.atlas-project.id
3 name = "${var.atlas_project_name}-${var.environment}-cluster"
4 cluster_type = "REPLICASET"
5 replication_specs {
6 num_shards = 1
7 regions_config {
8 region_name = var.atlas_region
9 electable_nodes = 3
10 priority = 7
11 read_only_nodes = 0
12 }
13 }
14 cloud_backup = true
15 auto_scaling_disk_gb_enabled = true
16 mongo_db_major_version = "7.0"
17 # Provider Settings "block"
18 provider_name = var.cloud_provider
19 provider_disk_type_name = "P6"
20 provider_instance_size_name = var.cluster_instance_size_name
21}
O bloco de código mostrado acima especifica um cluster chamado “test” com um tipo de implantação de conjunto de réplicas, ideal para aplicativos que exigem alta disponibilidade e redundância de dados.
O cluster é configurado com um único fragmento e está configurado para escalar automaticamente seu armazenamento em disco conforme necessário. A convenção de nomenclatura para o cluster incorpora variáveis que permitem a personalização específica do ambiente, como ${var.atlas_project_name}-${var.environment}-cluster.
A configuração também especifica um conjunto de réplicas com três nós eletivos em uma região configurável, garantindo que o nó primário possa ser efetivamente eleito. A versão principal do MongoDB está definida como "7.0," alinhando o cluster com a versão estável mais recente.

Definindo saĂ­das do Terraform

You can display information from your Terraform setup directly onto the terminal when running Terraform commands. This feature is particularly handy for obtaining values that are only determined after the resources have been created, such as a randomly generated database user password or the connection string needed for your Atlas cluster. The following code is in your main.tf file and will ensure that these values are shown on the terminal once Terraform has finished executing.
1output "cluster_name" {
2 value = mongodbatlas_cluster.test.name
3 description = "Name of the MongoDB Atlas cluster"
4}
5output "cluster_uri" {
6 value = "mongodb://user-1:${random_password.db-user-password.result}@${mongodbatlas_cluster.test.name}.mongodb.net:27017/?authSource=admin&replicaSet=test-replicaSet"
7 description = "Connection URI for the MongoDB Atlas cluster"
8 sensitive = true
9}
10output "project_id" {
11 value = mongodbatlas_cluster.test.project_id
12 description = "ID of the MongoDB Atlas project where the cluster resides"
13}
14Initializing Terraform
We are now ready to run terraform init. This command will initialize Terraform and download Terraform Azure and MongoDB Atlas providers.
Capture for running Terraform Init
Captura para executar o Terraform Init
A captura de tela acima mostra que o Terraform foi inicializado com sucesso.

Revise a implementação proposta do Terraform

Next, we will be using terraform plan to review the proposed changes.
Capture for running Terraform Plan
Capturar para executar o Terraform Plan
A captura de tela acima mostra que o Terraform executará as seguintes atualizações.
Capture the results of running the Terraform Plan
Capture os resultados da execução do Plano Terraform
Ele mostra que o Terraform criará os seguintes cinco recursos: incluindo mongodbotlas_cluster.test, mongodmatlas_database_user.db-user, mongodbotlas_project.atlas-project, mongodbotlas_project_ip_access_list.ip e random_password.db-user-password.

Executando para criar os recursos

Now, we will execute the terraform apply command to initiate the deployment of the infrastructure. Upon reviewing and confirming that everything appears correct, respond with “yes” to give Terraform the go-ahead to proceed with the build.
Screenshot representing terraform apply
Captura de tela representando a aplicação do terraform
Capture for running Terraform Apply
Captura para executar Terraform Apply
Pode levar cerca de 10 minutos para o cluster ser implementado. Depois que ele for implementado com sucesso, você poderá visualizá-lo na UI do Atlas. Abaixo, podemos ver que um cluster do10 M foi implantado no Azure na região 2 Leste dos EUA.
Capture for successfully deploying a cluster(screenshot from the Atlas UI representing the deployed cluster
Capture para implantar com sucesso um cluster(captura de tela da UI do Atlas representando o cluster implantado)
Parabéns! Você agora distribuiu com êxito um cluster M10 no Azure.

Limpeza com Terraform destruir

When ready to destroy the infrastructure created, we can use terraform destroy to safely tear down the infrastructure. Type “yes” to destroy all the resources deployed. Be extra careful, though, if you are trying to destroy resources in the production environment.
Capture for running Terraform Destroy
Captura para executar o Terraform Destroy

ConclusĂŁo

Neste tutorial, aprenderam como implantar um cluster do MongoDB Atlas no Azure. A integração do MongoDB Atlas com Terraform no Azure oferece uma abordagem poderosa e flexível para o gerenciamento de banco de dados na nuvem. Ao aproveitar a infraestrutura do Terraform como recursos de código, simplificamos o processo de implantação do MongoDB Atlas, garantindo que nossa infraestrutura seja reproduzível e facilmente gerenciável.

Facebook Icontwitter iconlinkedin icon
Classifique este artigo
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Como usar os módulos de incorporações e reclassificação do Cohere com o MongoDB Atlas


Aug 14, 2024 | 10 min read
Tutorial

Como melhorar os aplicativos LLM com a recuperação de documentos principais usando MongoDB e LangChain


Feb 11, 2025 | 15 min read
Tutorial

MongoDB Charts Embedding SDK with React


Sep 09, 2024 | 5 min read
Tutorial

Como desenvolver um aplicativo web com funções sem servidor da Netlify e MongoDB


Jan 13, 2025 | 6 min read