Todos os produtos
Search
Central de documentação

ApsaraDB for MongoDB:Integrar o ApsaraDB for MongoDB usando o Terraform

Última atualização: Sep 06, 2026

Este tópico descreve como usar o Terraform para criar uma instância do ApsaraDB for MongoDB.

Nota

Você pode executar o código de exemplo deste tópico com poucos cliques.

Para obter mais informações sobre o Terraform, consulte What is Terraform?. Para saber mais sobre os tipos de recurso do MongoDB compatíveis com o Terraform, consulte Integration overview ou o Alibaba Cloud Provider.

Arquitetura de recursos

image.png

O modelo cria uma VPC e um vSwitch em uma região especificada e, em seguida, cria uma instância de conjunto de réplicas do MongoDB.

Pré-requisitos

  • Uma conta Alibaba Cloud tem permissões totais sobre todos os recursos pertencentes a ela. Se as credenciais dessa conta forem expostas, poderão surgir riscos de segurança. Recomendamos que você utilize um usuário do Resource Access Management (RAM) e crie um par de AccessKey para esse usuário. Para mais detalhes, consulte Create a RAM user e Create an AccessKey pair.

  • As permissões AliyunMongoDBFullAccess e AliyunMongoDBFullAccess foram concedidas ao usuário RAM. A permissão AliyunMongoDBFullAccess serve para gerenciar o ApsaraDB for MongoDB, enquanto a outra AliyunMongoDBFullAccess é destinada ao gerenciamento das virtual private clouds (VPCs). O código de exemplo abaixo mostra como conceder essas duas permissões ao usuário RAM. Para mais informações, consulte Grant permissions to a RAM user

    {
        "Version": "1",
        "Statement": [
            {
                "Action": "dds:*",
                "Resource": "*",
                "Effect": "Allow"
            },
            {
                "Action": [
                    "vpc:DescribeVpcs",
                    "vpc:DescribeVSwitches",
                    "vpc:CreateVpc",
                    "vpc:DeleteVpc",
                    "vpc:ModifyVpcAttribute",
                    "vpc:CreateVSwitch",
                    "vpc:DeleteVSwitch",
                    "vpc:ModifyVSwitchAttribute"
                ],
                "Resource": "*",
                "Effect": "Allow"
            },
            {
                "Action": "hdm:*",
                "Resource": "acs:dds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "dms:LoginDatabase",
                "Resource": "acs:dds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "ram:CreateServiceLinkedRole",
                "Resource": "*",
                "Effect": "Allow",
                "Condition": {
                    "StringEquals": {
                        "ram:ServiceName": "mongodb.aliyuncs.com"
                    }
                }
            }
        ]
    }
    
  • Prepare o ambiente de execução do Terraform utilizando um dos métodos a seguir:

    • Use o Terraform no Terraform Explorer: a Alibaba Cloud oferece o Terraform Explorer, um ambiente de execução online para o Terraform. Basta fazer login no Terraform Explorer para começar a usar, sem necessidade de instalação local. Essa opção é ideal para quem deseja testar e depurar o Terraform de forma rápida, prática e sem custos adicionais.

    • Use Terraform in Cloud Shell: o Terraform já vem pré-instalado no Cloud Shell, com as credenciais de identidade configuradas. Assim, é possível executar comandos do Terraform diretamente no Cloud Shell. Esse método atende bem a cenários que exigem uso e depuração ágeis, com baixo custo.

    • Install and configure Terraform on your on-premises machine: recomendado para situações em que a conexão de rede é instável ou quando se faz necessário um ambiente de desenvolvimento personalizado.

Importante

É obrigatório instalar o Terraform na versão 0.12.28 ou superior. Execute o comando terraform --version para verificar a versão instalada.

Nota

Este exemplo gera cobrança por determinados recursos. Cancele a assinatura desses recursos assim que deixar de precisar deles.

Recursos necessários

Usar o Terraform para criar uma instância do ApsaraDB for MongoDB

  1. Crie um diretório de trabalho e, dentro dele, um arquivo de configuração chamado main.tf. O arquivo main.tf é o principal arquivo do Terraform e define os recursos que você deseja implantar.

    Standalone instance

    variable "region" {
      default = "cn-heyuan"
    }
    provider "alicloud" {
      region = var.region
    }
    # Declare the variable 'name'.
    variable "name" {
      default = "terraform-example-1125"
    }
    variable "engine_version" {
      default = "7.0"
    }
    variable "db_instance_class" {
      default = "mdb.shard.2x.xlarge.d"
    }
    # Query for available availability zones.
    data "alicloud_mongodb_zones" "default" {
    }
    # Use a local value to get the last available availability zone ID from the data source.
    locals {
      index   = length(data.alicloud_mongodb_zones.default.zones) - 1
      zone_id = data.alicloud_mongodb_zones.default.zones[local.index].id
    }
    # Create a VPC resource.
    resource "alicloud_vpc" "vpc1" {
      vpc_name   = var.name
      cidr_block = "172.16.0.0/12"
    }
    # Create a vSwitch in the specified availability zone within the VPC.
    resource "alicloud_vswitch" "default" {
      vswitch_name = var.name
      cidr_block   = "172.16.20.0/24"
      vpc_id       = alicloud_vpc.vpc1.id
      zone_id      = local.zone_id
    }
    # Create a standalone instance by using the VPC and vSwitch.
    resource "alicloud_mongodb_instance" "singleNode" {
      # (Required) The database version.
      engine_version      = var.engine_version
      # (Required) The instance type.
      db_instance_class   = var.db_instance_class
      # (Required) The storage capacity of the instance, in GB.
      db_instance_storage = 20
      # The network type of the instance.
      network_type        = "VPC"
      # (Optional, ForceNew) The ID of the vSwitch to which the instance is connected in the VPC.
      vswitch_id          = alicloud_vswitch.default.id
      # The ID of the VPC.
      vpc_id              = alicloud_vpc.vpc1.id
      # (Optional, ForceNew) The availability zone where the instance resides.
      zone_id             = local.zone_id
      # The name of the instance.  
      name                = var.name
      # (Optional, available from v1.199.0) The storage type of the instance.
      # storage_type        = "cloud_auto"
      # (Optional) A mapping of tags to assign to the resource.
      # tags = {
      #   Created = "TF"
      #   For     = "example"
      #   }
      # (Optional, List) The list of IP addresses that are allowed to access all databases of the instance.
      # security_ip_list    = [
            # "10.168.1.12",
            # "100.69.7.112"
      #   ]
    }

    Para mais detalhes sobre como configurar o tipo de recurso alicloud_mongodb_instance, consulte alicloud_mongodb_instance.

    Replica set instance

    variable "region" {
      default = "cn-heyuan"
    }
    provider "alicloud" {
      region = var.region
    }
    # Declare the variable 'name'.
    variable "name" {
      default = "terraform-example-1125"
    }
    variable "engine_version" {
      default = "7.0"
    }
    variable "db_instance_class" {
      default = "mdb.shard.2x.xlarge.d"
    }
    # Query for available availability zones.
    data "alicloud_mongodb_zones" "default" {
    }
    # Use a local value to get the last available availability zone ID from the data source.
    locals {
      index   = length(data.alicloud_mongodb_zones.default.zones) - 1
      zone_id = data.alicloud_mongodb_zones.default.zones[local.index].id
    }
    # Create a VPC resource.
    resource "alicloud_vpc" "vpc1" {
      vpc_name   = var.name
      cidr_block = "172.16.0.0/12"
    }
    # Create a vSwitch in the specified availability zone within the VPC.
    resource "alicloud_vswitch" "default" {
      vswitch_name = var.name
      cidr_block   = "172.16.20.0/24"
      vpc_id       = alicloud_vpc.vpc1.id
      zone_id      = local.zone_id
    }
    # Create a replica set instance by using the VPC and vSwitch.
    resource "alicloud_mongodb_instance" "default" {
      engine_version      = var.engine_version
      db_instance_class   = var.db_instance_class
      db_instance_storage = 20
      network_type        = "VPC"
      vswitch_id          = alicloud_vswitch.default.id
      vpc_id              = alicloud_vpc.vpc1.id
      security_ip_list    = ["10.168.1.12", "100.69.7.112"]
      name                = var.name
      tags = {
        Created = "TF"
        For     = "example"
      }
    }

    Para mais detalhes sobre como configurar o tipo de recurso alicloud_mongodb_instance, consulte alicloud_mongodb_instance.

    Sharded cluster instance

    variable "region" {
      default = "cn-heyuan"
    }
    provider "alicloud" {
      region = var.region
    }
    # Declare the variable 'name'.
    variable "name" {
      default = "terraform-example-1125"
    }
    # Query for available availability zones.
    data "alicloud_mongodb_zones" "default" {
    }
    # Use a local value to get the last available availability zone ID from the data source.
    locals {
      index   = length(data.alicloud_mongodb_zones.default.zones) - 1
      zone_id = data.alicloud_mongodb_zones.default.zones[local.index].id
    }
    # Create a VPC resource.
    resource "alicloud_vpc" "vpc1" {
      vpc_name   = var.name
      cidr_block = "172.16.0.0/12"
    }
    # Create a vSwitch in the specified availability zone within the VPC.
    resource "alicloud_vswitch" "default" {
      vswitch_name = var.name
      cidr_block   = "172.16.20.0/24"
      vpc_id       = alicloud_vpc.vpc1.id
      zone_id      = local.zone_id
    }
    # Create a sharded cluster instance by using the VPC and vSwitch.
    resource "alicloud_mongodb_sharding_instance" "default" {
      # (Required) The database version.
      engine_version      = "7.0"
      # (Optional, ForceNew) The vSwitch ID of the instance.
      vswitch_id          = alicloud_vswitch.default.id
      # The network type of the instance.
      network_type        = "VPC"
      # The VPC ID of the instance.
      vpc_id              = alicloud_vpc.vpc1.id
      # The name of the instance.
      name                = var.name
      # The availability zone.
      zone_id = local.zone_id
      # The mongos nodes of the instance. The number of nodes must be between 2 and 32. See mongo_list below.
      mongo_list {
        # (Required) The instance type of the mongos node.
        node_class = "mdb.shard.2x.xlarge.d"
      }
      mongo_list {
        node_class = "mdb.shard.2x.xlarge.d"
      }
      # (Required, Set) The shard nodes of the instance. You can purchase 2 to 32 shard nodes. See shard_list below.
      shard_list {
        # (Required) The instance type of the shard node.
        node_class   = "mdb.shard.2x.xlarge.d"
        #  (Required, Int) The storage space of the shard node.
        node_storage = 20
      }
      shard_list {
        node_class        = "mdb.shard.2x.xlarge.d"
        node_storage      = 20
        # The number of read-only nodes in the shard node. Default value: 0. Valid values: 0 to 5.
        readonly_replicas = 1
      }
      config_server_list {
        # The instance type of the ConfigServer node. Valid values: mdb.shard.2x.xlarge.d and dds.cs.mid.
        node_class ="mdb.shard.2x.xlarge.d"
        # The storage space of the ConfigServer node.
        node_storage = "20"
      }
      # A mapping of tags to assign to the resource.
      tags = {
        Created = "TF"
        For     = "Example"
      }
    }

    Para mais detalhes sobre como configurar o tipo de recurso alicloud_mongodb_sharding_instance, consulte alicloud_mongodb_sharding_instance.

  2. Execute o comando abaixo para inicializar o Terraform:

    terraform init

    Se a mensagem a seguir for retornada, significa que o Terraform foi inicializado com sucesso.

    Initializing the backend...
    Initializing provider plugins...
    - Finding latest version of hashicorp/alicloud...
    - Installing hashicorp/alicloud v1.234.0...
    - Installed hashicorp/alicloud v1.234.0 (signed by HashiCorp)
    Terraform has created a lock file .terraform.lock.hcl to record the provider
    selections it made above. Include this file in your version control repository
    so that Terraform can guarantee to make the same selections by default when
    you run "terraform init" in the future.
    Terraform has been successfully initialized!
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
  3. Crie um plano de execução e visualize as alterações previstas.

    terraform plan
  4. Execute o comando a seguir para criar uma instância do ApsaraDB for MongoDB.

    terraform apply

    Quando solicitado, insira yes e pressione Enter. A saída abaixo indica que a instância do ApsaraDB for MongoDB foi criada com êxito.

    Plan: 3 to add, 0 to change, 0 to destroy.
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
      Enter a value: yes
    alicloud_vpc.vpc1: Creating...
    alicloud_vpc.vpc1: Creation complete after 6s [id=vpc-f8zov2h1snsl2bm9qz***]
    alicloud_vswitch.default: Creating...
    alicloud_vswitch.default: Creation complete after 3s [id=vsw-f8zswqowidqw16ypc2***]
    alicloud_mongodb_instance.singleNode: Creating...
    alicloud_mongodb_instance.singleNode: Still creating... [10s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [20s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [30s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [40s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [50s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [1m0s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [1m10s elapsed]
    ...
    alicloud_mongodb_instance.singleNode: Still creating... [14m11s elapsed]
    alicloud_mongodb_instance.singleNode: Still creating... [14m21s elapsed]
    alicloud_mongodb_instance.singleNode: Creation complete after 14m29s [id=dds-f8z3a787aea1c***]
    Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
  5. Verifique o resultado.

    Run the terraform show command

    Execute o comando abaixo para consultar os recursos criados pelo Terraform:

    terraform show
    shell@Alicloud:~/ens/mongodb$ terraform show
    # alicloud_mongodb_instance.singleNode:
    resource "alicloud_mongodb_instance" "singleNode" {
        backup_interval                          = "-1"
        backup_period                            = [
            "Friday",
            "Monday",
            "Saturday",
            "Sunday",
            "Thursday",
            "Tuesday",
            "Wednesday",
        ]
        backup_retention_period                  = 30
        backup_retention_policy_on_cluster_deletion = 0
        backup_time                              = "07:00Z-08:00Z"
        db_instance_class                        = "mdb.shard.2x.xlarge.d"
        db_instance_storage                      = 20
        enable_backup_log                        = 1
        encrypted                                = false
        engine_version                           = "7.0"
        id                                       = "dds xxx"
        instance_charge_type                     = "PostPaid"
        log_backup_retention_period              = 30
        ...
    }
        maintain_end_time                        = "22:00Z"
        maintain_start_time                      = "18:00Z"
        name                                     = "terraform-example-1125"
        network_type                             = "VPC"
        provisioned_iops                         = 0
        readonly_replicas                        = 0
        replica_set_name                         = "mgset-84451431"
        replica_sets                             = [
            {
                connection_domain    = "xxx"
                connection_port      = "3717"
                network_type         = "VPC"
                replica_set_role     = "Primary"
                vpc_cloud_instance_id = "xxx"
                vpc_id               = "vpc-xxx"
                vswitch_id           = "vsw-xxx"
            },
        ]
        replication_factor                       = 3
        resource_group_id                        = "xxx"
        retention_period                         = 30
    }

    Log on to the ApsaraDB for MongoDB console

    Após a criação da instância, valide o sucesso da operação por meio da OpenAPI, de SDKs ou acessando o console do ApsaraDB for MongoDB. No console do ApsaraDB for MongoDB, navegue até a página Replica Set Instances. Confirme se a instância criada pelo Terraform apresenta o status Running e se suas configurações correspondem ao definido: zona de disponibilidade em China (Heyuan), classe de instância mdb.shard.2x.xlarge.d, armazenamento de 20 GB, versão 7.0, tipo de rede VPC, método de faturamento pay-as-you-go e arquitetura three-node.

Liberar recursos

Caso não precise mais dos recursos mencionados acima, criados ou gerenciados via Terraform, execute o comando seguinte para liberá-los. Para mais informações sobre o comando terraform destroy, consulte Common commands.

terraform destroy

Código de exemplo

Nota

Você pode executar o código de exemplo deste tópico com poucos cliques.

Código de exemplo

variable "region" {
  default = "cn-heyuan"
}
provider "alicloud" {
  region = var.region
}
# Declare the variable 'name'.
variable "name" {
  default = "terraform-example-1125"
}
variable "engine_version" {
  default = "7.0"
}
variable "db_instance_class" {
  default = "mdb.shard.2x.xlarge.d"
}
# Query for available availability zones.
data "alicloud_mongodb_zones" "default" {
}
# Use a local value to get the last available availability zone ID from the data source.
locals {
  index   = length(data.alicloud_mongodb_zones.default.zones) - 1
  zone_id = data.alicloud_mongodb_zones.default.zones[local.index].id
}
# Create a VPC resource.
resource "alicloud_vpc" "vpc1" {
  vpc_name   = var.name
  cidr_block = "172.16.0.0/12"
}
# Create a vSwitch in the specified availability zone within the VPC.
resource "alicloud_vswitch" "default" {
  vswitch_name = var.name
  cidr_block   = "172.16.20.0/24"
  vpc_id       = alicloud_vpc.vpc1.id
  zone_id      = local.zone_id
}
# Create a standalone instance by using the VPC and vSwitch.
resource "alicloud_mongodb_instance" "singleNode" {
  # (Required) The database version.
  engine_version      = var.engine_version
  # (Required) The instance type.
  db_instance_class   = var.db_instance_class
  # (Required) The storage capacity of the instance, in GB.
  db_instance_storage = 20
  # The network type of the instance.
  network_type        = "VPC"
  # (Optional, ForceNew) The ID of the vSwitch to which the instance is connected in the VPC.
  vswitch_id          = alicloud_vswitch.default.id
  # The ID of the VPC.
  vpc_id              = alicloud_vpc.vpc1.id
  # (Optional, ForceNew) The availability zone where the instance resides.
  zone_id             = local.zone_id
  # The name of the instance.  
  name                = var.name
  # (Optional) A mapping of tags to assign to the resource.
  tags = {
    Created = "TF"
    For     = "example"
    }
  # (Optional, List) The list of IP addresses that are allowed to access all databases of the instance.
  security_ip_list    = [
         "10.168.1.12",
         "100.69.7.112"
     ]
  # (Optional, available from v1.199.0) The storage type of the instance.
  # storage_type        = "cloud_auto"   
}
# Create a sharded cluster instance by using the VPC and vSwitch.
resource "alicloud_mongodb_sharding_instance" "default" {
  # (Required) The database version.
  engine_version      = "7.0"
  # (Optional, ForceNew) The vSwitch ID of the instance.
  vswitch_id          = alicloud_vswitch.default.id
  # The network type of the instance.
  network_type        = "VPC"
  # The VPC ID of the instance.
  vpc_id              = alicloud_vpc.vpc1.id
  # The name of the instance.
  name                = var.name
  # The availability zone.
  zone_id = local.zone_id
  # The mongos nodes of the instance. The number of nodes must be between 2 and 32. See mongo_list below.
  mongo_list {
    # (Required) The instance type of the mongos node.
    node_class = "mdb.shard.2x.xlarge.d"
  }
  mongo_list {
    node_class = "mdb.shard.2x.xlarge.d"
  }
  # (Required, Set) The shard nodes of the instance. You can purchase 2 to 32 shard nodes. See shard_list below.
  shard_list {
    # (Required) The instance type of the shard node.
    node_class   = "mdb.shard.2x.xlarge.d"
    #  (Required, Int) The storage space of the shard node.
    node_storage = 20
  }
  shard_list {
    node_class        = "mdb.shard.2x.xlarge.d"
    node_storage      = 20
    # The number of read-only nodes in the shard node. Default value: 0. Valid values: 0 to 5.
    readonly_replicas = 1
  }
  config_server_list {
    # The instance type of the ConfigServer node. Valid values: mdb.shard.2x.xlarge.d and dds.cs.mid.
    node_class ="mdb.shard.2x.xlarge.d"
    # The storage space of the ConfigServer node.
    node_storage = "20"
  }
  # A mapping of tags to assign to the resource.
  tags = {
    Created = "TF"
    For     = "Example"
  }
}

Para visualizar outros códigos de exemplo, acesse o GitHub.