通過 Terraform 管理 RDS PostgreSQL 實例賬號
本文介紹如何使用Terraform創建、修改、查詢和刪除RDS PostgreSQL實例賬號。
本教程所含示例代碼支持一鍵運行,您可以直接運行代碼。一鍵運行
前提條件
已創建RDS PostgreSQL實例,詳情請參見創建RDS PostgreSQL實例。
實例狀態為運行中,您可以通過如下兩種方式查看:
由于阿里云賬號(主賬號)具有資源的所有權限,一旦發生泄露將面臨重大風險。建議您使用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:適用于網絡連接較差或需要自定義開發環境的場景。
使用的資源
本教程示例包含的部分資源會產生一定費用,請在不需要時及時進行釋放或退訂。
alicloud_db_account:創建賬號。
alicloud_rds_accounts:查詢賬號。
alicloud_vpc:創建專有網絡VPC。
alicloud_vswitch:創建專有網絡交換機。
alicloud_db_instance:創建RDS PostgreSQL實例。
創建賬號
以創建名為tf_account_test
的賬號為例。
創建一個工作目錄,并在該工作目錄中創建名為main.tf的配置文件,然后將以下代碼復制到main.tf中。
創建前置資源。
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 }
在main.tf文件中增加
resource "alicloud_db_account" "account" {}
配置項。... resource "alicloud_db_account" "account" { db_instance_id = alicloud_db_instance.instance.id account_name = "tf_account_test" account_password = "!Test@123456" }
執行以下命令,初始化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.
創建執行計劃,并預覽變更。
terraform plan
執行以下命令,創建資源。
terraform apply
在執行過程中,根據提示輸入
yes
并按下Enter鍵,等待命令執行完成,若出現以下信息,則表示運行成功。alicloud_db_account.account: Creating... alicloud_db_account.account: Creation complete after 6s [id=pgm-****:tf_account_test] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
驗證結果。
執行terraform show命令
您可以使用以下命令查詢賬號信息:
terraform show
# alicloud_db_account.account: resource "alicloud_db_account" "account" { account_name = "tf_account_test" account_password = (sensitive value) account_type = "Normal" db_instance_id = "pgm-****" id = "pgm-****:tf_account_test" instance_id = "pgm-****)" name = "tf_account_test" status = "Available" type = "Normal" } # alicloud_db_instance.instance: resource "alicloud_db_instance" "instance" { client_ca_enabled = 0 client_crl_enabled = 0 connection_string = "pgm-****.pg.rds.aliyuncs.com" connection_string_prefix = "pgm-****" db_instance_storage_type = "cloud_essd" db_time_zone = "Asia/Shanghai" deletion_protection = false engine = "PostgreSQL" engine_version = "13.0" force_restart = false ha_config = "Auto" id = "pgm-****" instance_charge_type = "Postpaid" instance_name = "terraformtest" instance_storage = 50 instance_type = "pg.n2.2c.2m" maintain_time = "05:00Z-06:00Z" monitoring_period = 300 period = 0 port = "5432" private_ip_address = "172.16.XX.XX" resource_group_id = "rg-****" security_group_ids = [] security_ip_mode = "normal" security_ips = [ "127.0.0.1", ] sql_collector_config_value = 30 sql_collector_status = "Disabled" storage_auto_scale = "Enable" storage_threshold = 30 storage_upper_bound = 100 target_minor_version = "rds_postgres_1300_20220730" tcp_connection_type = "SHORT" vpc_id = "vpc-****" vswitch_id = "vsw-****" zone_id = "cn-hangzhou-j" }
登錄RDS管理控制臺
登錄RDS管理控制臺查看賬號信息。
修改賬號密碼
以修改tf_account_test
賬號的密碼為Test123@rds
為例。
在上述main.tf文件的
resource "alicloud_db_account" "account"
中,修改account_password
配置項,具體配置如下。... resource "alicloud_db_account" "account" { ... account_password = "Test123@rds" }
運行
terraform apply
。出現如下配置信息后,確認配置信息并輸入yes,開始修改。
alicloud_vpc.main: Refreshing state... [id=vpc-****] alicloud_vswitch.main: Refreshing state... [id=vsw-****] alicloud_db_instance.instance: Refreshing state... [id=pgm-****] alicloud_db_account.account: Refreshing state... [id=pgm-****:tf_account_test] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # alicloud_db_account.account will be updated in-place ~ resource "alicloud_db_account" "account" { ~ account_password = (sensitive value) id = "pgm-****:tf_account_test" name = "tf_account_test" # (6 unchanged attributes hidden) } Plan: 0 to add, 1 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:
出現類似如下日志時,表示修改成功。
alicloud_db_account.account: Modifying... [id=pgm-****:tf_account_test] alicloud_db_account.account: Modifications complete after 6s [id=pgm-****:tf_account_test] Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
使用新密碼連接數據庫即可驗證修改是否生效。
查詢賬號
在上述main.tf文件中,補充如下內容。
... data "alicloud_rds_accounts" "queryaccounts" { db_instance_id = alicloud_db_instance.instance.id }
運行
terraform apply
查詢實例已創建的賬號。出現類似如下日志時,表示查詢成功。
alicloud_vpc.main: Refreshing state... [id=vpc-****] alicloud_vswitch.main: Refreshing state... [id=vsw-****] alicloud_db_instance.instance: Refreshing state... [id=pgm-****] data.alicloud_rds_accounts.queryaccounts: Reading... alicloud_db_account.account: Refreshing state... [id=pgm-****:tf_account_test] data.alicloud_rds_accounts.queryaccounts: Read complete after 1s [id=137568****] 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.
驗證結果。
您可以使用以下命令驗證結果:
terraform show
# data.alicloud_rds_accounts.queryaccounts: data "alicloud_rds_accounts" "queryaccounts" { accounts = [ { account_description = "" account_name = "tf_account_test" account_type = "Normal" database_privileges = [] id = "tf_account_test" priv_exceeded = "" status = "Available" }, ] db_instance_id = "pgm-****" id = "137568****" ids = [ "tf_account_test", ] names = [ "tf_account_test", ] }
刪除賬號
以刪除名為tf_account_test
的賬號為例。
在上述main.tf文件中,刪除
resource "alicloud_db_account" "account"
配置項的內容。例如,刪除如下信息:... resource "alicloud_db_account" "account" { db_instance_id = alicloud_db_instance.instance.id account_name = "tf_account_test" account_password = "Test123@rds" }
運行
terraform apply
。出現如下配置信息后,確認配置信息并輸入yes,開始刪除。
alicloud_db_account.account: Refreshing state... [id=pgm-****:tf_account_test] alicloud_vpc.main: Refreshing state... [id=vpc-****] alicloud_vswitch.main: Refreshing state... [id=vsw-****] alicloud_db_instance.instance: Refreshing state... [id=pgm-****] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: - destroy Terraform will perform the following actions: # alicloud_db_account.account will be destroyed # (because alicloud_db_account.account is not in configuration) - resource "alicloud_db_account" "account" { - account_name = "tf_account_test" -> null - account_password = (sensitive value) - account_type = "Normal" -> null - db_instance_id = "pgm-****" -> null - id = "pgm-****:tf_account_test" -> null - instance_id = "pgm-****" -> null - name = "tf_account_test" -> null - status = "Available" -> null - type = "Normal" -> null } Plan: 0 to add, 0 to change, 1 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:
出現類似如下日志時,表示刪除成功。
alicloud_db_account.account: Destroying... [id=pgm-****:tf_account_test] alicloud_db_account.account: Destruction complete after 6s Apply complete! Resources: 0 added, 0 changed, 1 destroyed.
驗證結果。
執行terraform show命令
您可以使用以下命令驗證結果:
terraform show
# alicloud_db_instance.instance: resource "alicloud_db_instance" "instance" { client_ca_enabled = 0 client_crl_enabled = 0 connection_string = "pgm-****.pg.rds.aliyuncs.com" connection_string_prefix = "pgm-****" db_instance_storage_type = "cloud_essd" db_time_zone = "Asia/Shanghai" deletion_protection = false engine = "PostgreSQL" engine_version = "13.0" force_restart = false ha_config = "Auto" id = "pgm-****" instance_charge_type = "Postpaid" instance_name = "terraformtest" instance_storage = 50 instance_type = "pg.n2.2c.2m" maintain_time = "05:00Z-06:00Z" monitoring_period = 300 period = 0 port = "5432" private_ip_address = "172.16.XX.XX" resource_group_id = "rg-****" security_group_ids = [] security_ip_mode = "normal" security_ips = [ "127.0.0.1", ] sql_collector_config_value = 30 sql_collector_status = "Disabled" storage_auto_scale = "Enable" storage_threshold = 30 storage_upper_bound = 100 target_minor_version = "rds_postgres_1300_20220730" tcp_connection_type = "SHORT" vpc_id = "vpc-****" vswitch_id = "vsw-****" zone_id = "cn-hangzhou-j" pg_hba_conf { address = "127.0.0.1" database = "all" method = "md5" priority_id = 1 type = "host" user = "all" } }
登錄RDS管理控制臺
登錄RDS管理控制臺查看已沒有賬號。
清理資源
當您不再需要上述通過Terraform創建或管理的資源時,請運行以下命令以釋放資源。關于terraform destroy
的更多信息,請參見Terraform常用命令。
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
# 如果不需要創建VPC和交換機,使用已有的VPC和交換機
# vswitch_id = "vsw-****"
# 創建多個配置相同的RDS PostgreSQL實例,x為需要創建的實例數量
# count = x
}
# 創建賬號
resource "alicloud_db_account" "account" {
db_instance_id = alicloud_db_instance.instance.id
account_name = "tf_account_test"
account_password = "Test123@rds"
}
# 查詢賬號
data "alicloud_rds_accounts" "queryaccounts" {
db_instance_id = alicloud_db_instance.instance.id
depends_on = [alicloud_db_account.account]
}
如果您想體驗更多完整示例,請前往更多完整示例中對應產品的文件夾查看。