Tüm Ürünler
Search
Belge Merkezi

ApsaraDB for MongoDB:Terraform Kullanarak ApsaraDB for MongoDB Entegrasyonu

Son Güncelleme:Oct 06, 2026

Bu konu, Terraform kullanarak bir ApsaraDB for MongoDB örneğinin nasıl oluşturulacağını açıklar.

Not

Bu konudaki örnek kodu birkaç tıklama ile çalıştırabilirsiniz.

Terraform hakkında daha fazla bilgi için bkz. Terraform Nedir? Terraform tarafından desteklenen MongoDB kaynak türleri hakkında daha fazla bilgi için bkz. Entegrasyona Genel Bakış veya Alibaba Cloud Sağlayıcısı.

Kaynak mimarisi

image.png

Şablon, belirtilen bir bölgede bir VPC ve bir vSwitch oluşturur, ardından bir MongoDB çoğaltma kümesi örneği oluşturur.

Ön Koşullar

  • Bir Alibaba Cloud hesabı, bu hesaba ait tüm kaynaklar üzerinde tam izinlere sahiptir. Alibaba Cloud hesabının kimlik bilgileri sızdırılırsa güvenlik riskleri ortaya çıkabilir. Bir RAM kullanıcısı kullanmanızı ve bu kullanıcı için bir AccessKey çifti oluşturmanızı öneririz. Daha fazla bilgi için bkz. RAM Kullanıcısı Oluşturma ve AccessKey Çifti Oluşturma.

  • AliyunMongoDBFullAccess ve AliyunVPCFullAccess izinleri RAM kullanıcısına atanır. AliyunMongoDBFullAccess izni ApsaraDB for MongoDB yönetimi için, AliyunVPCFullAccess izni ise sanal özel bulutları (VPC'ler) yönetmek için kullanılır. Aşağıdaki örnek kod, bu iki iznin RAM kullanıcısına nasıl atanacağını göstermektedir. Daha fazla bilgi için bkz. RAM Kullanıcısına İzin Atama

    {
        "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"
                    }
                }
            }
        ]
    }
    
  • Terraform çalışma zamanı ortamını aşağıdaki yöntemlerden birini kullanarak hazırlayın:

    • Terraform Explorer içinde Terraform kullanın: Alibaba Cloud, Terraform için çevrimiçi bir çalışma zamanı ortamı olan Terraform Explorer'ı sağlar. Terraform'u kurmanıza gerek kalmadan Terraform Explorer'da oturum açtıktan sonra Terraform'u kullanabilirsiniz. Bu yöntem, Terraform'u hızlı ve kolay bir şekilde, ek maliyet olmadan kullanmak ve hata ayıklamak istediğiniz senaryolar için uygundur.

    • Cloud Shell'de Terraform Kullanma : Terraform, Cloud Shell'de önceden yüklüdür ve kimlik bilgileri yapılandırılmıştır. Cloud Shell'de doğrudan Terraform komutlarını çalıştırabilirsiniz. Bu yöntem, Terraform'u hızlı ve kolay bir şekilde, düşük maliyetle kullanmak ve hata ayıklamak istediğiniz senaryolar için uygundur.

    • Yerel Makinenize Terraform Yükleme ve Yapılandırma : Bu yöntem, ağ bağlantılarının kararsız olduğu veya özel bir geliştirme ortamı gerektiği senaryolar için uygundur.

Önemli

Terraform 0.12.28 veya sonraki bir sürümü yüklemelisiniz. Terraform sürümünü sorgulamak için terraform --version komutunu çalıştırabilirsiniz.

Not

Bu örnekteki belirli kaynaklar için ücretler oluşur. Artık ihtiyaç duymadığınızda kaynakların aboneliğini iptal edin.

Gerekli kaynaklar

Terraform kullanarak bir ApsaraDB for MongoDB örneği oluşturun

  1. Bir çalışma dizini oluşturun ve bu dizinde main.tf adlı bir yapılandırma dosyası oluşturun. main.tf , Terraform'un ana dosyasıdır ve dağıtmak istediğiniz kaynakları tanımlar.

    Tek düğümlü örnek

    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"
      #   ]
    }

    alicloud_mongodb_instance kaynak türünün nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. alicloud_mongodb_instance.

    Çoğaltma kümesi örneği

    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"
      }
    }

    alicloud_mongodb_instance kaynak türünün nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. alicloud_mongodb_instance.

    Parçalı küme örneği

    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"
      }
    }

    alicloud_mongodb_sharding_instance kaynak türünün nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. alicloud_mongodb_sharding_instance.

  2. Terraform başlatmak için aşağıdaki komutu çalıştırın:

    terraform init

    Aşağıdaki bilgiler döndürülürse Terraform başarıyla başlatılmış demektir.

    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. Bir yürütme planı oluşturun ve değişiklikleri önizleyin.

    terraform plan
  4. Bir ApsaraDB for MongoDB örneği oluşturmak için aşağıdaki komutu çalıştırın.

    terraform apply

    İstendiğinde yes girin ve Enter tuşuna basın. Aşağıdaki çıktı, ApsaraDB for MongoDB örneğinin başarıyla oluşturulduğunu gösterir.

    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. Sonucu doğrulayın.

    terraform show komutunu çalıştırın

    Terraform tarafından oluşturulan kaynakları sorgulamak için aşağıdaki komutu çalıştırın:

    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
    }

    ApsaraDB for MongoDB konsolunda oturum açın

    Örnek oluşturulduktan sonra işlemi doğrulamak için OpenAPI, SDK'lar kullanabilir veya ApsaraDB for MongoDB konsolunda oturum açabilirsiniz. ApsaraDB for MongoDB konsolunda oturum açın ve Replica Set Instances sayfasına gidin. Terraform tarafından oluşturulan örneğin Running durumunda olduğunu ve yapılandırmasının ayarlarınızla eşleştiğini doğrulayın: Örnek China (Heyuan) bölgesindeki bir kullanılabilirlik alanında bulunur, örnek sınıfı mdb.shard.2x.xlarge.d, depolama alanı 20 GB, sürüm 7.0, ağ türü VPC, faturalama yöntemi kullandıkça öde ve mimari üç düğümlü şeklindedir.

Kaynakları serbest bırakma

Terraform tarafından oluşturulan veya yönetilen önceki kaynaklara artık ihtiyacınız yoksa, kaynakları serbest bırakmak için aşağıdaki komutu çalıştırın. terraform destroy komutu hakkında daha fazla bilgi için bkz. Ortak Komutlar.

terraform destroy

Örnek kod

Not

Bu konudaki örnek kodu birkaç tıklama ile çalıştırabilirsiniz.

Örnek kod

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"
  }
}

Diğer örnek kodları görüntülemek için GitHub adresini ziyaret edin.