Terraform integration example

更新时间:
复制 MD 格式

Terraform is an open source tool that safely and efficiently provisions and manages cloud infrastructure and resources. This topic shows you how to use Terraform to create an ApsaraDB RDS for PostgreSQL instance.

Supported resources

For a list of ApsaraDB RDS resources and data sources that you can use with Terraform, see ApsaraDB RDS resources and data sources. If you are new to Terraform, see Introduction to Terraform.

Configure permissions

To use Terraform, you need an Alibaba Cloud account and an AccessKey pair. For security purposes, we recommend that you do not use your main Alibaba Cloud account to access ApsaraDB RDS. Instead, create a Resource Access Management (RAM) user, obtain the AccessKey pair for the RAM user, and grant the required permissions to the RAM user.

  1. Create a RAM user:

    1. Go to the RAM User List page and click Create User.

    2. Set Login Name to rds-test-operator and select Use permanent AccessKey for access for Access Mode.

    3. Click OK to create the RAM user and then save the AccessKey ID and AccessKey secret.

  2. Grant permissions:

    1. Go to the RAM User List page. In the Actions column for the target RAM user, click Add Permissions.

    2. In the text box, search for AliyunRDS and select AliyunRDSFullAccess. This policy grants full control over RDS.

    3. In the text box, search for VPC and select AliyunVPCFullAccess. This policy grants full control over VPC.

      Note

      In this example, a VPC and a vSwitch are created with the RDS instance. You can also select other permission policies or create custom policies as needed. For more information, see Create a custom permission policy.

    4. Click OK to add the permissions.

Procedure

Install Terraform

  • You can use Alibaba Cloud Cloud Shell. Cloud Shell is a free product that helps you with operations and maintenance (O&M). It comes pre-installed with Terraform components and is configured with identity credentials. You can run Terraform commands directly in Cloud Shell. For more information, see Cloud Shell.

  • To install and configure Terraform locally, see Install and configure Terraform locally.

    After the installation is complete, open a command-line terminal and enter terraform version. If the version information is returned, Terraform is successfully installed.

Write a template

Terraform uses commands to create, modify, view, and delete the resources defined in a Terraform template.

  1. Create and navigate to an execution directory.

    Note

    Create a separate execution directory for each Terraform project.

    • Linux or macOS:

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

      Important

      If you are not the root user, you must also grant permissions on the rds_terraform directory to the current user. To do this, run the sudo chown -R <current_username>:<user_group_name> /usr/local/terraform command to change the owner of the rds_terraform folder to the current user.

    • Windows: For example, create the rds_terraform folder on the D drive and navigate to the rds_terraform folder.

  2. In the execution directory, create a Terraform template file named terraform.tf.

    • Linux or macOS:

      touch terraform.tf
    • Windows: Manually create the terraform.tf file.

  3. For example, to query zone information for RDS for PostgreSQL, you can edit the terraform.tf file and add the following information.

    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
    }

Run the template

This example shows how to use a local installation of Terraform on a Windows operating system. The commands may vary depending on the operating system.

  1. Navigate to the D:\rds_terraform directory and initialize the modules, which include providers and other templates.

    terraform init

    Response

    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. Validate the template syntax.

    terraform validate

    Response:

    Success! The configuration is valid.
  3. Preview the template.

    terraform plan

    Response

    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. Apply the template configuration.

    terraform apply

    After the following configuration information appears, confirm the configuration and enter yes to start the creation process.

    Response

    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: 

    If a log similar to the following one appears, the instance was successfully created.

    Configuration log

    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. View the result.

    Go to the RDS Instances page to view the RDS instance that you created.

    image

References

For detailed examples of how to call RDS OpenAPI operations using Terraform, see Terraform.