通过Terraform管理负载均衡服务
CodeSample小助手
2020-01-09
简介:
本文介绍如何使用Terraform创建一个负载均衡实例,并为其添加监听器。
操作步骤
- 创建一个预付费的负载均衡实例。
- 创建terraform.tf文件,输入以下内容,并保存在当前的执行目录中。
说明 需要为每个Terraform项目创建一个独立的执行目录。在初始化配置之前至少需要有1个.tf文件。
resource "alicloud_slb" "instance" {
name = "slb_worder"
internet_charge_type = "PayByTraffic"
internet = "true"
}
- 运行terraform apply开始创建。出现类似下面的日志,说明创建成功。
alicloud_slb.instance: Creating...
address: "" => "<computed>"
instance_charge_type: "" => "PostPaid"
internet: "" => "true"
internet_charge_type: "" => "PayByTraffic"
name: "" => "slb_worder"
alicloud_slb.instance: Creation complete after 3s (ID: lb-bp1mq8qmsxl96pw61ruja)
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
- 运行terraform show查看已创建的负载均衡实例。
- 添加监听。以下示例添加了tcp、udp和http三种协议的监听
- 创建listener.tf文件,输入以下内容,并保存在当前的执行目录中。
说明 在该目录下所有*.tf 文件都会被terraform自动加载。因此,用户可以按照实际用途将配置信息写入不同的文件中。
resource "alicloud_slb_listener" "tcp" {
load_balancer_id = alicloud_slb.instance.id
backend_port = "22"
frontend_port = "22"
protocol = "tcp"
bandwidth = "10"
health_check_type = "tcp"
persistence_timeout = 3600
healthy_threshold = 8
unhealthy_threshold = 8
health_check_timeout = 8
health_check_interval = 5
health_check_http_code = "http_2xx"
health_check_connect_port = 20
health_check_uri = "/console"
established_timeout = 600
}
resource "alicloud_slb_listener" "udp" {
load_balancer_id = alicloud_slb.instance.id
backend_port = 2001
frontend_port = 2001
protocol = "udp"
bandwidth = 10
persistence_timeout = 3600
healthy_threshold = 8
unhealthy_threshold = 8
health_check_timeout = 8
health_check_interval = 4
health_check_connect_port = 20
}
resource "alicloud_slb_listener" "http" {
load_balancer_id = alicloud_slb.instance.id
backend_port = 80
frontend_port = 80
protocol = "http"
sticky_session = "on"
sticky_session_type = "insert"
cookie = "testslblistenercookie"
cookie_timeout = 86400
health_check = "on"
health_check_uri = "/cons"
health_check_connect_port = 20
healthy_threshold = 8
unhealthy_threshold = 8
health_check_timeout = 8
health_check_interval = 5
health_check_http_code = "http_2xx,http_3xx"
bandwidth = 10
request_timeout = 80
idle_timeout = 30
}
- 运行terraform apply开始创建。出现类似下面的日志,说明创建成功。
alicloud_slb_listener.tcp: Creation complete after 5s (ID: lb-bp1mq8qmsxl96pw61ruja:22)
alicloud_slb_listener.http: Creation complete after 5s (ID: lb-bp1mq8qmsxl96pw61ruja:80)
alicloud_slb_listener.udp: Creation complete after 5s (ID: lb-bp1mq8qmsxl96pw61ruja:2001)
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
- 运行terraform show查看已创建的监听。