This topic describes how to create a Server Load Balancer (SLB) instance in a VPC by using Terraform.

Prerequisites

Before you begin, ensure that you have completed the following operations:

Procedure

  1. Create a VPC and a VSwitch. In this example, a VPC and a vSwitch are created in Hangzhou Zone B (cn-hangzhou-b).
    1. Create the terraform.tf file, enter the following content, and save the file to the current working directory.
      resource "alicloud_vpc" "main" {
        name       = "alicloud"
        # CIDR block of the VPC
        cidr_block = "10.1.0.0/21"
      }
      
      resource "alicloud_vswitch" "main" {
        vpc_id            = alicloud_vpc.main.id
        # CIDR block of the VSwitch
        cidr_block        = "10.1.0.0/24"
        # Zone
        availability_zone = "cn-hangzhou-b"
        # Dependent resource
        depends_on = [alicloud_vpc.main]
      }
    2. Run the terraform apply command to create resources.
    3. Run the terraform show command to view the created VPC and VSwitch.
  2. Create an SLB instance and add a listener in the instance. In this example, a subscription SLB instance is created, and a TCP listener is added.
    1. In terraform.tf, add the following content:
      resource "alicloud_slb" "instance" {
        name                 = "slb_test"
        vswitch_id           = alicloud_vswitch.main.id
        internet_charge_type = "PayByTraffic"
      }
      
      resource "alicloud_slb_listener" "listener" {
        load_balancer_id = alicloud_slb.instance.id
        backend_port     = "2111"
        frontend_port    = "21"
        protocol         = "tcp"
        bandwidth        = "5"
      }
    2. Run the terraform apply command to create the SLB instance and add the listener. If log entries similar to the following ones are displayed, the SLB instance is created and the listener is added.
      alicloud_slb.instance: Creating...
      alicloud_slb.instance: Creation complete after 3s [id=lb-bp1li4zjp52xnzh2849hw]
      alicloud_slb_listener.listener: Creating...
      alicloud_slb_listener.listener: Creation complete after 1s [id=lb-bp1li4zjp52xnzh2849hw:tcp:21]
      
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
    3. Run the terraform show command to view the created SLB instance.