前置条件

安装sdk

安装阿里云sdk核心库

1
pip install aliyun-python-sdk-core

安装阿里云负载均衡sdk

1
pip install aliyun-python-sdk-slb

ak申请

子账号权限设置为该负载均衡的管理权限。

脚本

切换到应急环境

原理:把后端生产服务器权重改为0,应急服务器的权重改为100。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#/usr/bin/python
#coding=utf-8
from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import SetBackendServersRequest
import os


AccessKeyId = '' # AccessKeyID
AccessKeySecret = '' # AccessKeySecret
Endpoint = '' # 地区,例如cn-hangzhou

client = client.AcsClient(AccessKeyId, AccessKeySecret, Endpoint)
# ECS实例id
ecs_a = "" # ECS实例id,应急服务器
ecs_b = "" # ECS实例id,正常服务器
ecs_c = "" # ECS实例id,正常服务器

# SLB示例id
slb_id = ""

# 把备用机权重设置成100,其余的权重设置为0
req_parm1 = "BackendServers"
req_parm2 = [{"ServerId": ecs_a, "Weight": 100}, {
"ServerId": ecs_b, "Weight": 0}, {"ServerId": ecs_c, "Weight": 0}]

for i in range(len(req_parm2)):
request = SetBackendServersRequest.SetBackendServersRequest()
request.set_accept_format('json')
request.add_query_param('LoadBalancerId', slb_id)
request.add_query_param(req_parm1, req_parm2) # 设置权重
response = client.do_action_with_exception(request)
print(response) # 输出结果

切换到正常生产环境

原理:把后端生产服务器权重改为100,应急服务器的权重改为0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#/usr/bin/python
#coding=utf-8
from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import SetBackendServersRequest
import os


AccessKeyId = '' # AccessKeyID
AccessKeySecret = '' # AccessKeySecret
Endpoint = '' # 地区,例如cn-hangzhou

client = client.AcsClient(AccessKeyId, AccessKeySecret, Endpoint)
# ECS实例id
ecs_a = "" # ECS实例id,应急服务器
ecs_b = "" # ECS实例id,正常服务器
ecs_C = "" # ECS实例id,正常服务器

# SLB示例id
slb_id = ""

# 把备用机权重设置成100,其余的权重设置为0
req_parm1 = "BackendServers"
req_parm2 = [{"ServerId": ecs_a, "Weight": 0}, {
"ServerId": ecs_b, "Weight": 100}, {"ServerId": ecs_C, "Weight": 100}]

for i in range(len(req_parm2)):
request = SetBackendServersRequest.SetBackendServersRequest()
request.set_accept_format('json')
request.add_query_param('LoadBalancerId', slb_id)
request.add_query_param(req_parm1, req_parm2) # 设置权重
response = client.do_action_with_exception(request)
print(response) # 输出结果