All Products
Search
Document Center

Terraform:Create an SLB instance in a VPC

Last Updated:Jan 19, 2024

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

Prerequisites

Before you begin, make sure 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.

      provider "alicloud" {
        region = "cn-hangzhou"
      }
      
      resource "alicloud_vpc" "main" {
        vpc_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
        zone_id = "cn-hangzhou-b"
      }
    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_load_balancer" "instance" {
        load_balancer_name   = "slb_worder"
        load_balancer_spec   = "slb.s3.small"
        internet_charge_type = "PayByTraffic"
        address_type         = "internet"
        vswitch_id           = alicloud_vswitch.main.id
      }
      
      resource "alicloud_slb_listener" "listener" {
        load_balancer_id = alicloud_slb_load_balancer.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_load_balancer.instance: Creating...
      alicloud_slb_load_balancer.instance: Still creating... [10s elapsed]
      alicloud_slb_load_balancer.instance: Creation complete after 10s [id=lb-bp13b3e2m9l8wjwh3y8px]
      alicloud_slb_listener.listener: Creating...
      alicloud_slb_listener.listener: Creation complete after 3s [id=lb-bp13b3e2m9l8wjwh3y8px:tcp:21]
      ......
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
    3. Run the terraform show command to view the created SLB instance.