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.

151 lines
4.6 KiB

  1. import boto3
  2. ################################################################################################
  3. #
  4. # Configuration Parameters
  5. #
  6. ################################################################################################
  7. # place your credentials in ~/.aws/credentials, as mentioned in AWS Educate Classroom,
  8. # Account Details, AWC CLI -> Show (Copy and paste the following into ~/.aws/credentials)
  9. # changed to use us-east, to be able to use AWS Educate Classroom
  10. region = 'us-east-1'
  11. availabilityZone1 = 'us-east-1a'
  12. availabilityZone2 = 'us-east-1b'
  13. availabilityZone3 = 'us-east-1c'
  14. # region = 'eu-central-1'
  15. # availabilityZone = 'eu-central-1b'
  16. # AMI ID of Amazon Linux 2 image 64-bit x86 in us-east-1 (can be retrieved, e.g., at
  17. # https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#LaunchInstanceWizard:)
  18. imageId = 'ami-0d5eff06f840b45e9'
  19. # for eu-central-1, AMI ID of Amazon Linux 2 would be:
  20. # imageId = 'ami-0cc293023f983ed53'
  21. # potentially change instanceType to t2.micro for "free tier" if using a regular account
  22. # for production, t3.nano seams better
  23. # as of SoSe 2022 t2.nano seams to be a bit too low on memory, mariadb first start can fail
  24. # due to innodb cache out of memory, therefore t2.micro or swap in t2.nano currently recommended
  25. # instanceType = 't2.nano'
  26. instanceType = 't2.micro'
  27. # keyName = 'srieger-pub'
  28. keyName = 'vockey'
  29. ################################################################################################
  30. #
  31. # boto3 code
  32. #
  33. ################################################################################################
  34. client = boto3.setup_default_session(region_name=region)
  35. ec2Client = boto3.client("ec2")
  36. ec2Resource = boto3.resource('ec2')
  37. # if you only have one VPC, vpc_id can be retrieved using:
  38. response = ec2Client.describe_vpcs()
  39. vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  40. # if you have more than one VPC, vpc_id should be specified, and code
  41. # top retrieve VPC id below needs to be commented out
  42. # vpc_id = 'vpc-eedd4187'
  43. subnet_id1 = ec2Client.describe_subnets(
  44. Filters=[
  45. {
  46. 'Name': 'availability-zone', 'Values': [availabilityZone1]
  47. }
  48. ])['Subnets'][0]['SubnetId']
  49. subnet_id2 = ec2Client.describe_subnets(
  50. Filters=[
  51. {
  52. 'Name': 'availability-zone', 'Values': [availabilityZone2]
  53. }
  54. ])['Subnets'][0]['SubnetId']
  55. subnet_id3 = ec2Client.describe_subnets(
  56. Filters=[
  57. {
  58. 'Name': 'availability-zone', 'Values': [availabilityZone3]
  59. }
  60. ])['Subnets'][0]['SubnetId']
  61. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war']}])
  62. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  63. elbv2Client = boto3.client('elbv2')
  64. response = elbv2Client.create_load_balancer(
  65. Name='tug-of-war-loadbalancer',
  66. Subnets=[
  67. subnet_id1,
  68. subnet_id2,
  69. subnet_id3
  70. ],
  71. SecurityGroups=[
  72. security_group_id
  73. ]
  74. )
  75. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  76. loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
  77. response = elbv2Client.create_target_group(
  78. Name='tug-of-war-targetgroup',
  79. Port=80,
  80. Protocol='HTTP',
  81. VpcId=vpc_id,
  82. )
  83. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  84. response = elbv2Client.create_listener(
  85. DefaultActions=[
  86. {
  87. 'TargetGroupArn': targetgroup_arn,
  88. 'Type': 'forward',
  89. },
  90. ],
  91. LoadBalancerArn=loadbalancer_arn,
  92. Port=80,
  93. Protocol='HTTP',
  94. )
  95. response = elbv2Client.modify_target_group_attributes(
  96. TargetGroupArn=targetgroup_arn,
  97. Attributes=[
  98. {
  99. 'Key': 'stickiness.enabled',
  100. 'Value': 'true'
  101. },
  102. ]
  103. )
  104. print("Registering instances...")
  105. print("------------------------------------")
  106. response = ec2Client.describe_instances(Filters=[{'Name': 'tag:tug-of-war', 'Values': ['webserver']}])
  107. print(response)
  108. reservations = response['Reservations']
  109. for reservation in reservations:
  110. for instance in reservation['Instances']:
  111. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  112. response = elbv2Client.register_targets(
  113. TargetGroupArn=targetgroup_arn,
  114. Targets=[
  115. {
  116. 'Id': instance['InstanceId'],
  117. },
  118. ],
  119. )
  120. print('Waiting for Load Balancer to become available...')
  121. waiter = elbv2Client.get_waiter('load_balancer_available')
  122. waiter.wait(LoadBalancerArns=[loadbalancer_arn])
  123. print('Load Balancer should be reachable at: http://' + loadbalancer_dns)