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.

149 lines
5.7 KiB

  1. import time
  2. import boto3
  3. from botocore.exceptions import ClientError
  4. ################################################################################################
  5. #
  6. # Configuration Parameters
  7. #
  8. ################################################################################################
  9. # place your credentials in ~/.aws/credentials, as mentioned in AWS Educate Classroom,
  10. # Account Details, AWC CLI -> Show (Copy and paste the following into ~/.aws/credentials)
  11. # changed to use us-east, to be able to use AWS Educate Classroom
  12. region = 'us-east-1'
  13. availabilityZone = 'us-east-1b'
  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. elbv2Client = boto3.client('elbv2')
  34. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war']}])
  35. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  36. print("Getting DB IP...")
  37. print("------------------------------------")
  38. response = ec2Client.describe_instances(Filters=[{'Name': 'tag:tug-of-war', 'Values': ['db']}])
  39. print(response)
  40. reservations = response['Reservations']
  41. for reservation in reservations:
  42. for instance in reservation['Instances']:
  43. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  44. instanceDB = ec2Resource.Instance(instance['InstanceId'])
  45. privateIpDB = instanceDB.private_ip_address
  46. userDataWebServer = ('#!/bin/bash\n'
  47. '# extra repo for RedHat rpms\n'
  48. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  49. '# essential tools\n'
  50. 'yum install -y joe htop git\n'
  51. '# mysql\n'
  52. 'yum install -y httpd php php-mysql\n'
  53. '\n'
  54. 'service httpd start\n'
  55. '\n'
  56. # 'wget http://mmnet.informatik.hs-fulda.de/cloudcomp/tug-of-war-in-the-clouds.tar.gz\n'
  57. # 'cp tug-of-war-in-the-clouds.tar.gz /var/www/html/\n'
  58. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  59. 'cd /var/www/html\n'
  60. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/index.php\n'
  61. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/cloud.php\n'
  62. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/config.php\n'
  63. '\n'
  64. '# change hostname of db connection\n'
  65. 'sed -i s/localhost/' + privateIpDB + '/g /var/www/html/config.php\n'
  66. )
  67. for i in range(3, 4):
  68. print("Running new Web Server instance...")
  69. print("------------------------------------")
  70. response = ec2Client.run_instances(
  71. ImageId=imageId,
  72. InstanceType=instanceType,
  73. Placement={'AvailabilityZone': availabilityZone, },
  74. KeyName=keyName,
  75. MinCount=1,
  76. MaxCount=1,
  77. UserData=userDataWebServer,
  78. SecurityGroupIds=[
  79. security_group_id,
  80. ],
  81. TagSpecifications=[
  82. {
  83. 'ResourceType': 'instance',
  84. 'Tags': [
  85. {'Key': 'Name', 'Value': 'tug-of-war-webserver' + str(i)},
  86. {'Key': 'tug-of-war', 'Value': 'webserver'}
  87. ],
  88. }
  89. ],
  90. )
  91. instanceIdWeb = response['Instances'][0]['InstanceId']
  92. instance = ec2Resource.Instance(instanceIdWeb)
  93. instance.wait_until_running()
  94. instance.load()
  95. # sometimes even after reloading instance details, public IP cannot be retrieved using current boto3 version and
  96. # AWS Educate accounts, try for 10 secs, and ask user to get it from AWS console otherwise
  97. timeout = 10
  98. while instance.public_ip_address is None and timeout > 0:
  99. print("Waiting for public IP to become available...")
  100. instance.load()
  101. time.sleep(1)
  102. timeout -= 1
  103. if instance.public_ip_address is not None:
  104. print("tug-of-war-in-the-clouds can be accessed at: " + instance.public_ip_address)
  105. else:
  106. print("Could not get public IP using boto3, this is likely an AWS Educate problem. You can however lookup the "
  107. "public ip from the AWS management console.")
  108. try:
  109. response = elbv2Client.describe_target_groups(Names=['tug-of-war-targetgroup'])
  110. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  111. except ClientError as e:
  112. print(e)
  113. print("Registering instance...")
  114. print("------------------------------------")
  115. response = elbv2Client.register_targets(
  116. TargetGroupArn=targetgroup_arn,
  117. Targets=[
  118. {
  119. 'Id': instanceIdWeb,
  120. },
  121. ],
  122. )