Terraform集成示例

Terraform是一个开源工具,用于安全高效地预配和管理云基础架构和资源。本文为您演示如何通过Terraform创建RDS PostgreSQL实例。

支持资源列表

支持Terraform编排和使用的RDS资源和数据源清单,请参见云数据库RDS的资源和数据源。如果您还不了解Terraform,请参见什么是Terraform

配置权限

使用Terraform,您需要一个阿里云账号和账号的访问密钥(AccessKey)。为确保您的阿里云账号及云资源使用安全,如非必要应避免直接使用阿里云主账号来访问云数据库RDS。建议您创建一个RAM用户,获取该用户的AccessKey,并向其授予相应权限。

  1. 创建RAM用户:

    1. 访问RAM用户列表,单击创建用户

    2. 设置登录名称rds-test-operator,选择访问方式OpenAPI 调用访问

    3. 单击确定,创建RAM用户并保存AccessKey ID与AccessKey Secret信息。

  2. 完成授权:

    1. 访问RAM用户列表,单击目标RAM用户操作列的添加权限

    2. 在文本框中搜索AliyunRDS,选择AliyunRDSFullAccess(具有RDS的完全控制权限)。

    3. 在文本框中搜索VPC,选择AliyunVPCFullAccess(具有VPC的完全控制权限)。

      说明

      本示例中在创建RDS实例时,会同时创建VPC和交换机。您也可以按需选择权限策略或进行自定义策略,更多信息请参见创建自定义权限策略

    4. 单击确认新增授权,完成授权操作。

操作步骤

安装Terraform

  • 使用阿里云Cloud Shell。阿里云Cloud Shell是一款帮助您运维的免费产品,预装了Terraform的组件,并配置好身份凭证(credentials)。因此您可直接在Cloud Shell中运行Terraform的命令。详情请参见在Cloud Shell中使用Terraform

  • 在本地安装和配置Terraform,请参见在本地安装和配置Terraform

    安装完成后,您可以打开命令行终端,输入terraform version,若返回版本信息表示已成功安装。

编写模板

Terraform通过命令实现对Terraform模板中所定义的资源进行创建、修改、查看和删除。

  1. 创建执行目录并进入。

    说明

    需要为每个Terraform项目创建一个独立的执行目录。

    • Linux或macOS:

      sudo mkdir /usr/local/terraform
      cd /usr/local/rds_terraform

      重要

      如果您使用的非root权限用户,则还需要为rds_terraform目录授权,使用sudo chown -R <当前用户名>:<用户所属组名> /usr/local/terraform命令,将rds_terraform文件夹的owner修改为当前用户。

    • Windows:以D盘下创建rds_terraform文件夹为例,进入rds_terraform文件夹。

  2. 在执行目录下,创建Terraform模板(terraform.tf)文件。

    • Linux或macOS:

      touch terraform.tf
    • Windows:手动创建terraform.tf文件。

  3. 以查询RDS PostgreSQL可用区信息为例,编辑terraform.tf文件,补充如下信息。

    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 = "cn-hangzhou-j"
      depends_on = [alicloud_vpc.main]
    }
    
    resource "alicloud_db_instance" "instance" {
      engine           = "PostgreSQL"
      engine_version   = "13.0"
      instance_type    = "pg.n2.2c.2m"
      instance_storage = "30"
      instance_charge_type = "Postpaid"
      vswitch_id       = alicloud_vswitch.main.id
    }

运行模板

本示例以Windows操作系统下使用本地安装的Terraform为例,在其他操作系统中,运行命令的具体方式可能会有所不同。

  1. 进入D:\rds_terraform目录下,初始化加载模块,包括Provider等模板。

    terraform init

    返回结果

    Initializing the backend...
    Initializing provider plugins...
    - Finding latest version of hashicorp/alicloud...
    - Installing hashicorp/alicloud v1.226.0...
    - Installed hashicorp/alicloud v1.226.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.
    
    ╷
    │ Warning: Additional provider information from registry
    │
    │ The remote registry returned warnings for registry.terraform.io/hashicorp/alicloud:
    │ - For users on Terraform 0.13 or greater, this provider has moved to aliyun/alicloud. Please update your source in required_providers.
    ╵
    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.
  2. 验证模板语法是否正确。

    terraform validate

    返回结果:

    Success! The configuration is valid.
  3. 预览模板。

    terraform plan

    返回结果

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # alicloud_db_instance.instance will be created
      + resource "alicloud_db_instance" "instance" {
          + acl                        = (known after apply)
          + auto_upgrade_minor_version = (known after apply)
          + babelfish_port             = (known after apply)
          + ca_type                    = (known after apply)
          + category                   = (known after apply)
          + connection_string          = (known after apply)
          + connection_string_prefix   = (known after apply)
          + create_time                = (known after apply)
          + db_instance_storage_type   = (known after apply)
          + db_instance_type           = (known after apply)
          + db_is_ignore_case          = (known after apply)
          + db_time_zone               = (known after apply)
          + deletion_protection        = false
          + engine                     = "PostgreSQL"
          + engine_version             = "14.0"
          + force_restart              = false
          + ha_config                  = (known after apply)
          + id                         = (known after apply)
          + instance_charge_type       = "Postpaid"
          + instance_storage           = 30
          + instance_type              = "pg.n2.2c.2m"
          + maintain_time              = (known after apply)
          + monitoring_period          = (known after apply)
          + node_id                    = (known after apply)
          + port                       = (known after apply)
          + private_ip_address         = (known after apply)
          + replication_acl            = (known after apply)
          + resource_group_id          = (known after apply)
          + role_arn                   = (known after apply)
          + security_group_id          = (known after apply)
          + security_group_ids         = (known after apply)
          + security_ip_mode           = "normal"
          + security_ips               = (known after apply)
          + server_cert                = (known after apply)
          + server_key                 = (known after apply)
          + sql_collector_config_value = 30
          + sql_collector_status       = (known after apply)
          + ssl_action                 = (known after apply)
          + ssl_connection_string      = (known after apply)
          + ssl_status                 = (known after apply)
          + status                     = (known after apply)
          + target_minor_version       = (known after apply)
          + tcp_connection_type        = (known after apply)
          + tde_status                 = (known after apply)
          + vpc_id                     = (known after apply)
          + vswitch_id                 = (known after apply)
          + zone_id                    = (known after apply)
          + zone_id_slave_a            = (known after apply)
          + zone_id_slave_b            = (known after apply)
    
          + babelfish_config (known after apply)
    
          + parameters (known after apply)
    
          + pg_hba_conf (known after apply)
        }
    
      # alicloud_vpc.main will be created
      + resource "alicloud_vpc" "main" {
          + cidr_block            = "172.16.0.0/16"
          + create_time           = (known after apply)
          + id                    = (known after apply)
          + ipv6_cidr_block       = (known after apply)
          + ipv6_cidr_blocks      = (known after apply)
          + name                  = (known after apply)
          + resource_group_id     = (known after apply)
          + route_table_id        = (known after apply)
          + router_id             = (known after apply)
          + router_table_id       = (known after apply)
          + secondary_cidr_blocks = (known after apply)
          + status                = (known after apply)
          + user_cidrs            = (known after apply)
          + vpc_name              = "alicloud"
        }
    
      # alicloud_vswitch.main will be created
      + resource "alicloud_vswitch" "main" {
          + availability_zone    = (known after apply)
          + cidr_block           = "172.16.192.0/20"
          + create_time          = (known after apply)
          + id                   = (known after apply)
          + ipv6_cidr_block      = (known after apply)
          + ipv6_cidr_block_mask = (known after apply)
          + name                 = (known after apply)
          + status               = (known after apply)
          + vpc_id               = (known after apply)
          + vswitch_name         = (known after apply)
          + zone_id              = "cn-hangzhou-j"
        }
    
      Plan: 3 to add, 0 to change, 0 to destroy.
    
    
  4. 应用模板配置。

    terraform apply

    出现如下配置信息后,确认配置信息并输入yes,开始创建。

    返回结果

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # alicloud_db_instance.instance will be created
      + resource "alicloud_db_instance" "instance" {
          + acl                        = (known after apply)
          + auto_upgrade_minor_version = (known after apply)
          + babelfish_port             = (known after apply)
          + ca_type                    = (known after apply)
          + category                   = (known after apply)
          + connection_string          = (known after apply)
          + connection_string_prefix   = (known after apply)
          + create_time                = (known after apply)
          + db_instance_storage_type   = (known after apply)
          + db_instance_type           = (known after apply)
          + db_is_ignore_case          = (known after apply)
          + db_time_zone               = (known after apply)
          + deletion_protection        = false
          + engine                     = "PostgreSQL"
          + engine_version             = "14.0"
          + force_restart              = false
          + ha_config                  = (known after apply)
          + id                         = (known after apply)
          + instance_charge_type       = "Postpaid"
          + instance_storage           = 30
          + instance_type              = "pg.n2.2c.2m"
          + maintain_time              = (known after apply)
          + monitoring_period          = (known after apply)
          + node_id                    = (known after apply)
          + port                       = (known after apply)
          + private_ip_address         = (known after apply)
          + replication_acl            = (known after apply)
          + resource_group_id          = (known after apply)
          + role_arn                   = (known after apply)
          + security_group_id          = (known after apply)
          + security_group_ids         = (known after apply)
          + security_ip_mode           = "normal"
          + security_ips               = (known after apply)
          + server_cert                = (known after apply)
          + server_key                 = (known after apply)
          + sql_collector_config_value = 30
          + sql_collector_status       = (known after apply)
          + ssl_action                 = (known after apply)
          + ssl_connection_string      = (known after apply)
          + ssl_status                 = (known after apply)
          + status                     = (known after apply)
          + target_minor_version       = (known after apply)
          + tcp_connection_type        = (known after apply)
          + tde_status                 = (known after apply)
          + vpc_id                     = (known after apply)
          + vswitch_id                 = (known after apply)
          + zone_id                    = (known after apply)
          + zone_id_slave_a            = (known after apply)
          + zone_id_slave_b            = (known after apply)
    
          + babelfish_config (known after apply)
    
          + parameters (known after apply)
    
          + pg_hba_conf (known after apply)
        }
    
      # alicloud_vpc.main will be created
      + resource "alicloud_vpc" "main" {
          + cidr_block            = "172.16.0.0/16"
          + create_time           = (known after apply)
          + id                    = (known after apply)
          + ipv6_cidr_block       = (known after apply)
          + ipv6_cidr_blocks      = (known after apply)
          + name                  = (known after apply)
          + resource_group_id     = (known after apply)
          + route_table_id        = (known after apply)
          + router_id             = (known after apply)
          + router_table_id       = (known after apply)
          + secondary_cidr_blocks = (known after apply)
          + status                = (known after apply)
          + user_cidrs            = (known after apply)
          + vpc_name              = "alicloud"
        }
    
      # alicloud_vswitch.main will be created
      + resource "alicloud_vswitch" "main" {
          + availability_zone    = (known after apply)
          + cidr_block           = "172.16.192.0/20"
          + create_time          = (known after apply)
          + id                   = (known after apply)
          + ipv6_cidr_block      = (known after apply)
          + ipv6_cidr_block_mask = (known after apply)
          + name                 = (known after apply)
          + status               = (known after apply)
          + vpc_id               = (known after apply)
          + vswitch_name         = (known after apply)
          + zone_id              = "cn-hangzhou-j"
        }
    
    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: 

    出现类似如下日志时,表示创建成功。

    配置日志

    alicloud_vpc.main: Creating...
    alicloud_vpc.main: Creation complete after 9s [id=vpc-bp1apzkp9l5gkuq0****]
    alicloud_vswitch.main: Creating...
    alicloud_vswitch.main: Creation complete after 4s [id=vsw-bp1lmhzc42h5cc0t8****]
    alicloud_db_instance.instance: Creating...
    alicloud_db_instance.instance: Still creating... [10s elapsed]
    alicloud_db_instance.instance: Still creating... [20s elapsed]
    ...
    alicloud_db_instance.instance: Still creating... [6m1s elapsed]
    alicloud_db_instance.instance: Still creating... [6m11s elapsed]
    alicloud_db_instance.instance: Creation complete after 6m20s [id=pgm-bp10ckaa2340****]
    
    Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
  5. 查看结果。

    访问RDS实例列表,查看已创建的RDS实例。

    image

相关文档

通过Terraform调用RDS OpenAPI的详细示例,请参见Terraform