全部產品
Search
文件中心

ApsaraDB RDS:通過Terraform查詢RDS PostgreSQL執行個體相關配置

更新時間:Oct 22, 2025

本文介紹如何使用Terraform查詢RDS PostgreSQL執行個體的相關配置。

說明

本教程所含範例程式碼支援一鍵運行,您可以直接運行代碼。一鍵運行

前提條件

  • 已建立RDS PostgreSQL執行個體,詳情請參見建立RDS PostgreSQL執行個體

  • 執行個體狀態為運行中,您可以通過如下兩種方式查看:

    • 參見查詢執行個體詳情查看參數status,如果取值為Running則表示執行個體狀態為運行中。

    • 前往RDS管理主控台,切換到目標地區,找到指定執行個體後,查看執行個體狀態。

  • 由於阿里雲帳號(主帳號)具有資源的所有許可權,一旦發生泄露將面臨重大風險。建議您使用RAM使用者,並為該RAM使用者建立AccessKey,具體操作方式請參見建立RAM使用者建立AccessKey

  • 通過RAM授權,RAM使用者可以有效地管理其雲資源存取權限,適應多使用者協同工作的需求,並且能夠按需為使用者指派最小許可權,避免許可權過大導致的安全性漏洞。具體操作方式請參見為RAM使用者授權

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "vpc:DescribeVpcAttribute",
                    "vpc:DescribeRouteTableList",
                    "vpc:DescribeVSwitchAttributes",
                    "vpc:DeleteVpc",
                    "vpc:DeleteVSwitch",
                    "vpc:CreateVpc",
                    "vpc:CreateVSwitch"
                ],
                "Resource": "*"
            },
            {
                "Action": "rds:*",
                "Resource": "*",
                "Effect": "Allow"
            },
            {
                "Action": "dbs:*",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "hdm:*",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "dms:LoginDatabase",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Effect": "Allow",
                "Action": "ram:CreateServiceLinkedRole",
                "Resource": "*",
                "Condition": {
                    "StringEquals": {
                        "ram:ServiceName": [
                            "backupencryption.rds.aliyuncs.com"
                        ]
                    }
                }
            },
            {
                "Effect": "Allow",
                "Action": "bss:ModifyAgreementRecord",
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "bss:DescribeOrderList",
                    "bss:DescribeOrderDetail",
                    "bss:PayOrder",
                    "bss:CancelOrder"
                ],
                "Resource": "*"
            }
        ]
    }
  • 準備Terraform運行環境,您可以選擇以下任一方式來使用Terraform。

    • 在Terraform Explorer中使用Terraform:阿里雲提供了Terraform的線上運行環境,您無需安裝Terraform,登入後即可線上使用和體驗Terraform。適用於零成本、快速、便捷地體驗和調試Terraform的情境。

    • Cloud Shell:阿里雲Cloud Shell中預裝了Terraform的組件,並已配置好身份憑證,您可直接在Cloud Shell中運行Terraform的命令。適用於低成本、快速、便捷地訪問和使用Terraform的情境。

    • 在本地安裝和配置Terraform:適用於網路連接較差或需要自訂開發環境的情境。

使用的資源

說明

本教程樣本包含的部分資源會產生一定費用,請在不需要時及時進行釋放或退訂。

查詢可用性區域資源

本樣本示範如何查詢RDS PostgreSQL執行個體的可用性區域資源。

  1. 建立一個工作目錄,並在該工作目錄中建立名為main.tf的設定檔,然後將以下代碼複製到main.tf中。

    • 建立前置資源。

      variable "region" {
        default = "cn-heyuan"
      }
      
      provider "alicloud" {
        region = var.region
      }
      
      variable "zone_id" {
        default = "cn-heyuan-b"
      }
      
      variable "instance_type" {
        default = "pg.n2.2c.2m"
      }
      
      # 建立VPC
      resource "alicloud_vpc" "main" {
        vpc_name   = "alicloud"
        cidr_block = "172.16.0.0/16"
      }
      
      # 建立交換器
      resource "alicloud_vswitch" "main" {
        vpc_id     = alicloud_vpc.main.id
        cidr_block = "172.16.192.0/20"
        zone_id    = var.zone_id
      }
      
      # 建立RDS PostgreSQL執行個體
      resource "alicloud_db_instance" "instance" {
        engine               = "PostgreSQL"
        engine_version       = "13.0"
        instance_type        = var.instance_type
        instance_storage     = "30"
        instance_charge_type = "Postpaid"
        vswitch_id           = alicloud_vswitch.main.id
      }
    • main.tf檔案中增加data "alicloud_db_zones" "queryzones" {}配置項。

      ...
      data "alicloud_db_zones" "queryzones" {
        instance_charge_type     = "PostPaid"
        engine                   = "PostgreSQL"
        db_instance_storage_type = "cloud_essd"
      }
  2. 執行以下命令,初始化Terraform運行環境。

    terraform init

    返回如下資訊,表示Terraform初始化成功。

    Initializing the backend...
    
    Initializing provider plugins...
    - Checking for available provider plugins...
    - Downloading plugin for provider "alicloud" (hashicorp/alicloud) 1.90.1...
    ...
    
    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. 建立執行計畫,並預覽變更。

    terraform plan
  4. 執行以下命令,建立資源。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示運行成功。

    data.alicloud_db_zones.queryzones: Reading...
    data.alicloud_db_zones.queryzones: Read complete after 1s [id=262******]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
  5. 驗證結果。

    您可以使用以下命令查看結果:

    terraform show
    # data.alicloud_db_zones.queryzones:
    data "alicloud_db_zones" "queryzones" {
        db_instance_storage_type = "cloud_essd"
        engine                   = "PostgreSQL"
        id                       = "262******"
        ids                      = [
            "cn-heyuan-b",
        ]
        instance_charge_type     = "PostPaid"
        multi                    = false
        multi_zone               = false
        zones                    = [
            {
                id             = "cn-hangzhou-b"
                multi_zone_ids = []
            },
        ]
    }

查詢可購買的執行個體規格

  1. main.tf檔案增加如下內容。

    ...
    data "alicloud_db_instance_classes" "queryclasses" {
      instance_charge_type= "PostPaid"
      engine = "PostgreSQL"
      db_instance_storage_type = "cloud_essd"
    }
  2. 執行以下命令。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示運行成功。

    data.alicloud_db_instance_classes.queryclasses: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [10s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [20s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [30s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [40s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [50s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [1m0s elapsed]
    ...
    data.alicloud_db_instance_classes.queryclasses: Still reading... [6m50s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [7m0s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Read complete after 7m9s [id=130302****]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are
    needed.
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
  3. 驗證結果。

    您可以使用以下命令查看結果:

    terraform show
    {
                instance_class = "pg.n8.8xlarge.1"
                price          = ""
                storage_range  = {
                    "max"  = "32000"
                    "min"  = "1500"
                    "step" = "5"
                }
                zone_ids       = [
                    {
                        id           = "cn-hangzhou-k"
                        sub_zone_ids = []
                    },
                ]
    },
    {
                instance_class = "pg.n2.small.1"
                price          = ""
                storage_range  = {
                    "max"  = "32000"
                    "min"  = "1500"
                    "step" = "5"
                }
                zone_ids       = [
                    {
                        id           = "cn-hangzhou-k"
                        sub_zone_ids = []
                    },
                ]
    },
    ......

查詢地區資訊

  1. main.tf檔案增加如下內容。

    data "alicloud_regions" "query_regions" {
    }
  2. 執行以下命令。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示運行成功。

    data.alicloud_regions.query_regions: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    data.alicloud_regions.query_regions: Read complete after 1s [id=2105****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are
    needed.
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
  3. 驗證結果。

    您可以使用以下命令查看結果:

    terraform show
    # data.alicloud_regions.query_regions:
    data "alicloud_regions" "query_regions" {
        id      = "210547****"
        ids     = [
            "cn-qingdao",
            "cn-beijing",
            "cn-zhangjiakou",
            "cn-huhehaote",
            "cn-wulanchabu",
            "cn-hangzhou",
            "cn-shanghai",
            "cn-nanjing",
            "cn-shenzhen",
            "cn-heyuan",
            "cn-guangzhou",
            "cn-fuzhou",
            "cn-chengdu",
            "cn-hongkong",
            "ap-northeast-1",
            "ap-northeast-2",
            "ap-southeast-1",
            "ap-southeast-2",
            "ap-southeast-3",
            "ap-southeast-6",
            "ap-southeast-5",
            "ap-southeast-7",
            "us-east-1",
            "us-west-1",
            "eu-west-1",
            "me-east-1",
            "me-central-1",
            "eu-central-1",
        ]
        regions = [
            {
                id         = "cn-qingdao"
                local_name = "華北1(青島)"
                region_id  = "cn-qingdao"
            },
            {
                id         = "cn-beijing"
                local_name = "華北2(北京)"
                region_id  = "cn-beijing"
            },
            {
                id         = "cn-zhangjiakou"
                local_name = "華北3(張家口)"
                region_id  = "cn-zhangjiakou"
            },
            {
                id         = "cn-huhehaote"
                local_name = "華北5(呼和浩特)"
                region_id  = "cn-huhehaote"
            },
            {
                id         = "cn-wulanchabu"
                local_name = "華北6(烏蘭察布)"
                region_id  = "cn-wulanchabu"
            },
            {
                id         = "cn-hangzhou"
                local_name = "華東1(杭州)"
                region_id  = "cn-hangzhou"
            },
            {
                id         = "cn-shanghai"
                local_name = "華東2(上海)"
                region_id  = "cn-shanghai"
            },
            {
                id         = "cn-shenzhen"
                local_name = "華南1(深圳)"
                region_id  = "cn-shenzhen"
            },
            {
                id         = "cn-heyuan"
                local_name = "華南2(河源)"
                region_id  = "cn-heyuan"
            },
            {
                id         = "cn-guangzhou"
                local_name = "華南3(廣州)"
                region_id  = "cn-guangzhou"
            },
            {
                id         = "cn-chengdu"
                local_name = "西南1(成都)"
                region_id  = "cn-chengdu"
            },
            {
                id         = "cn-hongkong"
                local_name = "中國(香港)"
                region_id  = "cn-hongkong"
            },
            {
                id         = "ap-northeast-1"
                local_name = "亞太地區東北 1 (東京)"
                region_id  = "ap-northeast-1"
            },
            {
                id         = "ap-northeast-2"
                local_name = "韓國(首爾)"
                region_id  = "ap-northeast-2"
            },
            {
                id         = "ap-southeast-1"
                local_name = "亞太地區東南 1 (新加坡)"
                region_id  = "ap-southeast-1"
            },
            {
                id         = "ap-southeast-2"
                local_name = "亞太地區東南 2 (雪梨)"
                region_id  = "ap-southeast-2"
            },
            {
                id         = "ap-southeast-3"
                local_name = "亞太地區東南 3 (吉隆坡)"
                region_id  = "ap-southeast-3"
            },
            {
                id         = "ap-southeast-6"
                local_name = "菲律賓(馬尼拉)"
                region_id  = "ap-southeast-6"
            },
            {
                id         = "ap-southeast-5"
                local_name = "亞太地區東南 5 (雅加達)"
                region_id  = "ap-southeast-5"
            },
            {
                id         = "ap-southeast-7"
                local_name = "泰國(曼穀)"
                region_id  = "ap-southeast-7"
            },
            {
                id         = "us-east-1"
                local_name = "美國東部 1 (維吉尼亞)"
                region_id  = "us-east-1"
            },
            {
                id         = "us-west-1"
                local_name = "美國西部 1 (矽谷)"
                region_id  = "us-west-1"
            },
            {
                id         = "eu-west-1"
                local_name = "英國 (倫敦)"
                region_id  = "eu-west-1"
            },
            {
                id         = "me-east-1"
                local_name = "中東東部 1 (杜拜)"
                region_id  = "me-east-1"
            },
            {
                id         = "eu-central-1"
                local_name = "歐洲中部 1 (法蘭克福)"
                region_id  = "eu-central-1"
            },
        ]
    }  

查詢執行個體列表

  1. main.tf檔案增加如下內容。

    data "alicloud_db_instances" "queryinstances" {
    }
  2. 執行以下命令。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示運行成功。

    data.alicloud_db_instances.queryinstances: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    data.alicloud_db_instances.queryinstances: Read complete after 1s [id=277****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are
    needed.
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
  3. 驗證結果。

    您可以使用以下命令查看結果:

    terraform show
    # data.alicloud_db_instances.queryinstances:
    data "alicloud_db_instances" "queryinstances" {
        enable_details = false
        id             = "27790****"
        ids            = [
            "pgm-bp1zirc6i2****",
        ]
        instances      = [
            {
                acl                         = ""
                availability_zone           = "cn-hangzhou-j"
                ca_type                     = ""
                charge_type                 = "Postpaid"
                client_ca_cert              = ""
                client_ca_cert_expire_time  = ""
                client_cert_revocation_list = ""
                connection_mode             = "Standard"
                connection_string           = "pgm-****.pg.rds.aliyuncs.com"
                create_time                 = "2022-09-28T06:15:32Z"
                creator                     = ""
                db_instance_storage_type    = "cloud_essd"
                db_type                     = "Primary"
                delete_date                 = ""
                deletion_protection         = false
                description                 = ""
                encryption_key              = ""
                encryption_key_status       = ""
                engine                      = "PostgreSQL"
                engine_version              = "13.0"
                expire_time                 = ""
                guard_instance_id           = "<nil>"
                id                          = "pgm-****"
                instance_storage            = 50
                instance_type               = "pg.n2.2c.2m"
                key_usage                   = ""
                last_modify_status          = ""
                master_instance_id          = "<nil>"
                master_zone                 = ""
                material_expire_time        = ""
                modify_status_reason        = ""
                name                        = "terraformtest"
                net_type                    = "Intranet"
                origin                      = ""
                parameters                  = []
                port                        = "5432"
                readonly_instance_ids       = []
                region_id                   = "cn-hangzhou"
                replication_acl             = ""
                require_update              = ""
                require_update_item         = ""
                require_update_reason       = ""
                server_ca_url               = ""
                server_cert                 = ""
                server_key                  = ""
                ssl_create_time             = ""
                ssl_enabled                 = "off"
                ssl_expire_time             = ""
                status                      = "Running"
                temp_instance_id            = "<nil>"
                vpc_id                      = "vpc-****"
                vswitch_id                  = "vsw-****"
                zone_id_slave_a             = ""
                zone_id_slave_b             = ""
            },
        ]
        names          = [
            "terraformtest",
        ]
        page_size      = 100
        total_count    = 1
    }                     

查詢執行個體詳情

  1. main.tf檔案增加如下內容。

    • 查詢指定執行個體:

      說明

      已建立RDS PostgreSQL執行個體,詳情請參見建立RDS PostgreSQL執行個體

      執行個體狀態為運行中,您可以通過如下兩種方式查看:

      • 參見查詢執行個體詳情查看參數status,如果取值為Runing則表示執行個體狀態為運行中。

      • 前往RDS管理主控台,切換到目標地區,找到指定執行個體後,查看執行個體狀態。

      data "alicloud_db_instances" "queryinstance" {
        ids    = ["pgm-f8z04t******"]
        engine = "PostgreSQL"
      }
    • 查詢指定地區(環境變數中設定的地區)下所有執行個體:

      data "alicloud_db_instances" "queryinstance" {
        ids    = []
        engine = "PostgreSQL"
      }
  2. 執行以下命令。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示運行成功。

    data.alicloud_db_instances.queryinstance: Reading...
    data.alicloud_db_instances.queryinstance: Read complete after 5s [id=69816****]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
  3. 驗證結果。

    您可以使用以下命令查看結果:

    terraform show
    # data.alicloud_db_instances.queryinstance:
    data "alicloud_db_instances" "queryinstance" {
        enable_details = false
        engine         = "PostgreSQL"
        id             = "277908****"
        ids            = [
            "pgm-****",
        ]
        instances      = [
            {
                acl                         = ""
                availability_zone           = "cn-hangzhou-j"
                ca_type                     = ""
                charge_type                 = "Postpaid"
                client_ca_cert              = ""
                client_ca_cert_expire_time  = ""
                client_cert_revocation_list = ""
                connection_mode             = "Standard"
                connection_string           = "pgm-****.pg.rds.aliyuncs.com"
                create_time                 = "2022-09-28T06:15:32Z"
                creator                     = ""
                db_instance_storage_type    = "cloud_essd"
                db_type                     = "Primary"
                delete_date                 = ""
                deletion_protection         = false
                description                 = ""
                encryption_key              = ""
                encryption_key_status       = ""
                engine                      = "PostgreSQL"
                engine_version              = "13.0"
                expire_time                 = ""
                guard_instance_id           = "<nil>"
                id                          = "pgm-****"
                instance_storage            = 50
                instance_type               = "pg.n2.2c.2m"
                key_usage                   = ""
                last_modify_status          = ""
                master_instance_id          = "<nil>"
                master_zone                 = ""
                material_expire_time        = ""
                modify_status_reason        = ""
                name                        = "terraformtest"
                net_type                    = "Intranet"
                origin                      = ""
                parameters                  = []
                port                        = "5432"
                readonly_instance_ids       = []
                region_id                   = "cn-hangzhou"
                replication_acl             = ""
                require_update              = ""
                require_update_item         = ""
                require_update_reason       = ""
                server_ca_url               = ""
                server_cert                 = ""
                server_key                  = ""
                ssl_create_time             = ""
                ssl_enabled                 = "off"
                ssl_expire_time             = ""
                status                      = "Running"
                temp_instance_id            = "<nil>"
                vpc_id                      = "vpc-****"
                vswitch_id                  = "vsw-****"
                zone_id_slave_a             = ""
                zone_id_slave_b             = ""
            },
        ]
        names          = [
            "terraformtest",
        ]
        page_size      = 100
        total_count    = 1
    }

當您不再需要上述通過Terraform建立或管理的資源時,請運行以下命令以釋放資源。關於terraform destroy的更多資訊,請參見常用命令

terraform destroy

完整樣本

說明

當前範例程式碼支援一鍵運行,您可以直接運行代碼。一鍵運行

範例程式碼

variable "region" {
  default = "cn-hangzhou"
}

provider "alicloud" {
  region = var.region
}

variable "zone_id" {
  default = "cn-hangzhou-b"
}

variable "instance_type" {
  default = "pg.n2.2c.2m"
}

# 建立VPC
resource "alicloud_vpc" "main" {
  vpc_name   = "alicloud"
  cidr_block = "172.16.0.0/16"
}

# 建立交換器
resource "alicloud_vswitch" "main" {
  vpc_id     = alicloud_vpc.main.id
  cidr_block = "172.16.192.0/20"
  zone_id    = var.zone_id
}

# 建立RDS PostgreSQL執行個體
resource "alicloud_db_instance" "instance" {
  engine               = "PostgreSQL"
  engine_version       = "13.0"
  instance_type        = var.instance_type
  instance_storage     = "30"
  instance_charge_type = "Postpaid"
  vswitch_id           = alicloud_vswitch.main.id
}

# 查詢可用性區域資源
data "alicloud_db_zones" "queryzones" {
  instance_charge_type     = "PostPaid"
  engine                   = "PostgreSQL"
  db_instance_storage_type = "cloud_essd"
}

# 詢可購買的執行個體規格
data "alicloud_db_instance_classes" "queryclasses" {
  instance_charge_type     = "PostPaid"
  engine                   = "PostgreSQL"
  db_instance_storage_type = "cloud_essd"
}

# 查詢地區資訊
data "alicloud_regions" "query_regions" {
}

# 查詢執行個體列表
data "alicloud_db_instances" "queryinstances" {
}

# 查詢指定執行個體
data "alicloud_db_instances" "queryinstance" {
  ids = [alicloud_db_instance.instance.id]
  # 查詢指定地區(環境變數中設定的地區)下所有執行個體
  # ids  = []
  engine = "PostgreSQL"
}

如果您想體驗更多完整樣本,請前往更多完整樣本中對應產品的檔案夾查看。