You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

109 lines
3.0 KiB

import boto3
from botocore.exceptions import ClientError
################################################################################################
#
# Configuration Parameters
#
################################################################################################
region = 'eu-central-1'
availabilityZone = 'eu-central-1b'
vpc_id = 'vpc-eedd4187'
subnet1 = 'subnet-41422b28'
subnet2 = 'subnet-5c5f6d16'
subnet3 = 'subnet-6f2ea214'
# if you only have one VPC, vpc_id can be retrieved using:
#
# response = ec2Client.describe_vpcs()
# vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
################################################################################################
#
# boto3 code
#
################################################################################################
client = boto3.setup_default_session(region_name=region)
ec2Client = boto3.client("ec2")
ec2Resource = boto3.resource('ec2')
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)