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.

86 lines
2.4 KiB

  1. import boto3
  2. from botocore.exceptions import ClientError
  3. region = 'eu-central-1'
  4. availabilityZone = 'eu-central-1b'
  5. subnet1 = 'subnet-41422b28'
  6. subnet2 = 'subnet-5c5f6d16'
  7. subnet3 = 'subnet-6f2ea214'
  8. client = boto3.setup_default_session(region_name=region)
  9. ec2Client = boto3.client("ec2")
  10. ec2Resource = boto3.resource('ec2')
  11. response = ec2Client.describe_vpcs()
  12. vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  13. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war']}])
  14. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  15. elbv2Client = boto3.client('elbv2')
  16. response = elbv2Client.create_load_balancer(
  17. Name='tug-of-war-loadbalancer',
  18. Subnets=[
  19. subnet1,
  20. subnet2,
  21. subnet3,
  22. ],
  23. SecurityGroups=[
  24. security_group_id
  25. ]
  26. )
  27. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  28. loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
  29. response = elbv2Client.create_target_group(
  30. Name='tug-of-war-targetgroup',
  31. Port=80,
  32. Protocol='HTTP',
  33. VpcId=vpc_id,
  34. )
  35. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  36. response = elbv2Client.create_listener(
  37. DefaultActions=[
  38. {
  39. 'TargetGroupArn': targetgroup_arn,
  40. 'Type': 'forward',
  41. },
  42. ],
  43. LoadBalancerArn=loadbalancer_arn,
  44. Port=80,
  45. Protocol='HTTP',
  46. )
  47. response = elbv2Client.modify_target_group_attributes(
  48. TargetGroupArn=targetgroup_arn,
  49. Attributes=[
  50. {
  51. 'Key': 'stickiness.enabled',
  52. 'Value': 'true'
  53. },
  54. ]
  55. )
  56. print("Registering instances...")
  57. print("------------------------------------")
  58. response = ec2Client.describe_instances(Filters=[{'Name': 'tag:tug-of-war', 'Values': ['webserver']}])
  59. print(response)
  60. reservations = response['Reservations']
  61. for reservation in reservations:
  62. for instance in reservation['Instances']:
  63. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  64. response = elbv2Client.register_targets(
  65. TargetGroupArn=targetgroup_arn,
  66. Targets=[
  67. {
  68. 'Id': instance['InstanceId'],
  69. },
  70. ],
  71. )
  72. print('Load Balancer should be reachable at: ' + loadbalancer_dns)