import boto3
AWS_REGION = 'YOUR_AWS_REGION'
SERVICE_NAME = 'YOUR_SERVICE_NAME'
DOMAIN_NAME = 'YOUR_DOMAIN_NAME'
PATH_PATTERN = 'YOUR_PATH_PATTERN'
LB_NAME = 'YOUR_LB_NAME'
def create_alb_rule(elbv2, listener_arn, condition_field, condition_value, priority_number, target_group_arn):
elbv2.create_rule(
ListenerArn=listener_arn,
Conditions=[{'Field': condition_field, 'Values': [condition_value]}],
Priority=priority_number,
Actions=[{'Type': 'forward', 'TargetGroupArn': target_group_arn}]
)
def create_alb_target_group(elbv2, service_name, alb_vpc_id):
response = elbv2.create_target_group(
Name=service_name,
Protocol='HTTP',
Port=80,
TargetType='ip',
VpcId=alb_vpc_id,
HealthCheckPath='/ping'
)
target_group_arn = response['TargetGroups'][0]['TargetGroupArn']
elbv2.modify_target_group_attributes(
TargetGroupArn=target_group_arn,
Attributes=[{'Key': 'load_balancing.algorithm.type', 'Value': 'least_outstanding_requests'}]
)
return target_group_arn
def create_alb():
elbv2 = boto3.client('elbv2', region_name=AWS_REGION)
lb_info = elbv2.describe_load_balancers(Names=[LB_NAME])['LoadBalancers'][0]
alb_vpc_id = lb_info['VpcId']
target_groups = elbv2.describe_target_groups()
target_sum = len([tg for tg in target_groups['TargetGroups'] if tg['TargetGroupName'].startswith(SERVICE_NAME)])
rules = elbv2.describe_rules(listener_arn=lb_info['LoadBalancerArn'])
priorities = [int(rule['Priority']) for rule in rules['Rules'] if rule['Priority'].isdigit()]
priority_number = max(priorities) + 1 if priorities else 1
if target_sum == 0:
target_group_arn = create_alb_target_group(elbv2, SERVICE_NAME, alb_vpc_id)
with open('/tmp/TGAR', 'w') as file:
file.write(target_group_arn)
if DOMAIN_NAME:
create_alb_rule(elbv2, lb_info['ListenerArn'], 'host-header', DOMAIN_NAME, priority_number, target_group_arn)
if PATH_PATTERN:
create_alb_rule(elbv2, lb_info['ListenerArn'], 'path-pattern', PATH_PATTERN, priority_number, target_group_arn)
else:
print("ALB Rule exists !!!")
def conf_alb():
elbv2 = boto3.client('elbv2', region_name=AWS_REGION)
lb_info = elbv2.describe_load_balancers(Names=[LB_NAME])['LoadBalancers'][0]
if lb_info['Protocol'] == 'HTTP':
create_alb()
elif not lb_info['Protocol']:
create_alb()
else:
print("新协议请通知运维更新")
conf_alb()
- 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.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.