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:- Prepare an Alibaba Cloud account and an AccessKey pair (AccessKey ID and AccessKey secret) to use Terraform. You can go to the Security Management page of the Alibaba Cloud console to create or view your AccessKey pair.
- Install and configure Terraform. For more information, see Install and configure Terraform in the local PC and Use Terraform in Cloud Shell.
Procedure
Create a VPC and a VSwitch. In this example, a VPC and a vSwitch are created in Hangzhou Zone B (cn-hangzhou-b).
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" }
Run the terraform apply command to create resources.
Run the terraform show command to view the created VPC and VSwitch.
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.
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" }
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.
Run the terraform show command to view the created SLB instance.