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.

147 lines
4.4 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. instanceType = 't2.nano'
  24. keyName = 'srieger-pub'
  25. ################################################################################################
  26. #
  27. # boto3 code
  28. #
  29. ################################################################################################
  30. client = boto3.setup_default_session(region_name=region)
  31. ec2Client = boto3.client("ec2")
  32. ec2Resource = boto3.resource('ec2')
  33. # if you only have one VPC, vpc_id can be retrieved using:
  34. response = ec2Client.describe_vpcs()
  35. vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  36. # if you have more than one VPC, vpc_id should be specified, and code
  37. # top retrieve VPC id below needs to be commented out
  38. # vpc_id = 'vpc-eedd4187'
  39. subnet_id1 = ec2Client.describe_subnets(
  40. Filters=[
  41. {
  42. 'Name': 'availability-zone', 'Values': [availabilityZone1]
  43. }
  44. ])['Subnets'][0]['SubnetId']
  45. subnet_id2 = ec2Client.describe_subnets(
  46. Filters=[
  47. {
  48. 'Name': 'availability-zone', 'Values': [availabilityZone2]
  49. }
  50. ])['Subnets'][0]['SubnetId']
  51. subnet_id3 = ec2Client.describe_subnets(
  52. Filters=[
  53. {
  54. 'Name': 'availability-zone', 'Values': [availabilityZone3]
  55. }
  56. ])['Subnets'][0]['SubnetId']
  57. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war']}])
  58. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  59. elbv2Client = boto3.client('elbv2')
  60. response = elbv2Client.create_load_balancer(
  61. Name='tug-of-war-loadbalancer',
  62. Subnets=[
  63. subnet_id1,
  64. subnet_id2,
  65. subnet_id3
  66. ],
  67. SecurityGroups=[
  68. security_group_id
  69. ]
  70. )
  71. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  72. loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
  73. response = elbv2Client.create_target_group(
  74. Name='tug-of-war-targetgroup',
  75. Port=80,
  76. Protocol='HTTP',
  77. VpcId=vpc_id,
  78. )
  79. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  80. response = elbv2Client.create_listener(
  81. DefaultActions=[
  82. {
  83. 'TargetGroupArn': targetgroup_arn,
  84. 'Type': 'forward',
  85. },
  86. ],
  87. LoadBalancerArn=loadbalancer_arn,
  88. Port=80,
  89. Protocol='HTTP',
  90. )
  91. response = elbv2Client.modify_target_group_attributes(
  92. TargetGroupArn=targetgroup_arn,
  93. Attributes=[
  94. {
  95. 'Key': 'stickiness.enabled',
  96. 'Value': 'true'
  97. },
  98. ]
  99. )
  100. print("Registering instances...")
  101. print("------------------------------------")
  102. response = ec2Client.describe_instances(Filters=[{'Name': 'tag:tug-of-war', 'Values': ['webserver']}])
  103. print(response)
  104. reservations = response['Reservations']
  105. for reservation in reservations:
  106. for instance in reservation['Instances']:
  107. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  108. response = elbv2Client.register_targets(
  109. TargetGroupArn=targetgroup_arn,
  110. Targets=[
  111. {
  112. 'Id': instance['InstanceId'],
  113. },
  114. ],
  115. )
  116. print('Waiting for Load Balancer to become available...')
  117. waiter = elbv2Client.get_waiter('load_balancer_available')
  118. waiter.wait(LoadBalancerArns=[loadbalancer_arn])
  119. print('Load Balancer should be reachable at: ' + loadbalancer_dns)