|
|
import boto3 from botocore.exceptions import ClientError
region = 'eu-central-1' availabilityZone = 'eu-central-1b' subnet1 = 'subnet-41422b28' subnet2 = 'subnet-5c5f6d16' subnet3 = 'subnet-6f2ea214'
client = boto3.setup_default_session(region_name=region) ec2Client = boto3.client("ec2") ec2Resource = boto3.resource('ec2')
response = ec2Client.describe_vpcs() vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war']}]) security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
elbv2Client = boto3.client('elbv2')
response = elbv2Client.create_load_balancer( Name='tug-of-war-loadbalancer', Subnets=[ subnet1, subnet2, subnet3, ], SecurityGroups=[ security_group_id ] )
loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '') loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
response = elbv2Client.create_target_group( Name='tug-of-war-targetgroup', Port=80, Protocol='HTTP', VpcId=vpc_id, )
targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
response = elbv2Client.create_listener( DefaultActions=[ { 'TargetGroupArn': targetgroup_arn, 'Type': 'forward', }, ], LoadBalancerArn=loadbalancer_arn, Port=80, Protocol='HTTP', )
response = elbv2Client.modify_target_group_attributes( TargetGroupArn=targetgroup_arn, Attributes=[ { 'Key': 'stickiness.enabled', 'Value': 'true' }, ] )
print("Registering instances...") print("------------------------------------")
response = ec2Client.describe_instances(Filters=[{'Name': 'tag:tug-of-war', 'Values': ['webserver']}]) print(response) reservations = response['Reservations'] for reservation in reservations: for instance in reservation['Instances']: if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending": response = elbv2Client.register_targets( TargetGroupArn=targetgroup_arn, Targets=[ { 'Id': instance['InstanceId'], }, ], )
print('Waiting for Load Balancer to become available...')
waiter = elbv2Client.get_waiter('load_balancer_available') waiter.wait(LoadBalancerArns=[loadbalancer_arn]) print('Load Balancer should be reachable at: ' + loadbalancer_dns)
|