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.

211 lines
7.6 KiB

  1. import boto3
  2. from botocore.exceptions import ClientError
  3. ################################################################################################
  4. #
  5. # Configuration Parameters
  6. #
  7. ################################################################################################
  8. region = 'eu-central-1'
  9. availabilityZone = 'eu-central-1b'
  10. vpc_id = 'vpc-eedd4187'
  11. imageId = 'ami-0cc293023f983ed53'
  12. instanceType = 't3.nano'
  13. keyName = 'srieger-pub'
  14. # if you only have one VPC, vpc_id can be retrieved using:
  15. #
  16. # response = ec2Client.describe_vpcs()
  17. # vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  18. ################################################################################################
  19. #
  20. # boto3 code
  21. #
  22. ################################################################################################
  23. client = boto3.setup_default_session(region_name=region)
  24. ec2Client = boto3.client("ec2")
  25. ec2Resource = boto3.resource('ec2')
  26. subnet_id = ec2Client.describe_subnets(
  27. Filters=[
  28. {
  29. 'Name': 'availability-zone', 'Values': [availabilityZone]
  30. }
  31. ])['Subnets'][0]['SubnetId']
  32. print("Deleting old instance...")
  33. print("------------------------------------")
  34. response = ec2Client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['tug-of-war']}])
  35. print(response)
  36. reservations = response['Reservations']
  37. for reservation in reservations:
  38. for instance in reservation['Instances']:
  39. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  40. response = ec2Client.terminate_instances(InstanceIds=[instance['InstanceId']])
  41. print(response)
  42. instanceToTerminate = ec2Resource.Instance(instance['InstanceId'])
  43. instanceToTerminate.wait_until_terminated()
  44. print("Delete old security group...")
  45. print("------------------------------------")
  46. try:
  47. response = ec2Client.delete_security_group(GroupName='tug-of-war')
  48. except ClientError as e:
  49. print(e)
  50. print("Create security group...")
  51. print("------------------------------------")
  52. try:
  53. response = ec2Client.create_security_group(GroupName='tug-of-war',
  54. Description='tug-of-war',
  55. VpcId=vpc_id)
  56. security_group_id = response['GroupId']
  57. print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
  58. data = ec2Client.authorize_security_group_ingress(
  59. GroupId=security_group_id,
  60. IpPermissions=[
  61. {'IpProtocol': 'tcp',
  62. 'FromPort': 3306,
  63. 'ToPort': 3306,
  64. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  65. {'IpProtocol': 'tcp',
  66. 'FromPort': 22,
  67. 'ToPort': 22,
  68. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  69. {'IpProtocol': 'tcp',
  70. 'FromPort': 80,
  71. 'ToPort': 80,
  72. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  73. {'IpProtocol': 'tcp',
  74. 'FromPort': 443,
  75. 'ToPort': 443,
  76. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
  77. ])
  78. print('Ingress Successfully Set %s' % data)
  79. except ClientError as e:
  80. print(e)
  81. userDataDB = ('#!/bin/bash\n'
  82. '#!/bin/bash\n'
  83. '# extra repo for RedHat rpms\n'
  84. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  85. '# essential tools\n'
  86. 'yum install -y joe htop git\n'
  87. '# mysql\n'
  88. 'yum install -y mariadb mariadb-server\n'
  89. '\n'
  90. 'service mariadb start\n'
  91. '\n'
  92. 'echo "create database cloud_tug_of_war" | mysql -u root\n'
  93. '\n'
  94. 'echo "create table clouds ( cloud_id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, value INT, max_value INT, PRIMARY KEY (cloud_id))" | mysql -u root cloud_tug_of_war\n'
  95. '\n'
  96. 'echo "CREATE USER \'cloud_tug_of_war\'@\'%\' IDENTIFIED BY \'cloudpass\';" | mysql -u root\n'
  97. 'echo "GRANT ALL PRIVILEGES ON cloud_tug_of_war.* TO \'cloud_tug_of_war\'@\'%\';" | mysql -u root\n'
  98. 'echo "FLUSH PRIVILEGES" | mysql -u root\n'
  99. )
  100. # convert user-data from script with: cat install-mysql | sed "s/^/'/; s/$/\\\n'/"
  101. print("Running new DB instance...")
  102. print("------------------------------------")
  103. response = ec2Client.run_instances(
  104. ImageId=imageId,
  105. InstanceType=instanceType,
  106. Placement={'AvailabilityZone': availabilityZone, },
  107. KeyName=keyName,
  108. MinCount=1,
  109. MaxCount=1,
  110. UserData=userDataDB,
  111. SecurityGroupIds=[
  112. security_group_id,
  113. ],
  114. TagSpecifications=[
  115. {
  116. 'ResourceType': 'instance',
  117. 'Tags': [
  118. {'Key': 'Name', 'Value': 'tug-of-war-db1'},
  119. {'Key': 'tug-of-war', 'Value': 'db'}
  120. ],
  121. }
  122. ],
  123. )
  124. instanceIdDB = response['Instances'][0]['InstanceId']
  125. privateIpDB = response['Instances'][0]['PrivateIpAddress']
  126. # privateIpDB = response['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId']
  127. instance = ec2Resource.Instance(instanceIdDB)
  128. instance.wait_until_running()
  129. print(instanceIdDB)
  130. userDataWebServer = ('#!/bin/bash\n'
  131. '# extra repo for RedHat rpms\n'
  132. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  133. '# essential tools\n'
  134. 'yum install -y joe htop git\n'
  135. '# mysql\n'
  136. 'yum install -y httpd php php-mysql\n'
  137. '\n'
  138. 'service httpd start\n'
  139. 'service httpd start\n'
  140. '\n'
  141. # 'wget http://mmnet.informatik.hs-fulda.de/cloudcomp/tug-of-war-in-the-clouds.tar.gz\n'
  142. # 'cp tug-of-war-in-the-clouds.tar.gz /var/www/html/\n'
  143. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  144. 'cd /var/www/html\n'
  145. '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'
  146. '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'
  147. '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'
  148. '\n'
  149. '# change hostname of db connection\n'
  150. 'sed -i s/localhost/' + privateIpDB + '/g /var/www/html/config.php\n'
  151. )
  152. for i in range(1, 3):
  153. print("Running new Web Server instance...")
  154. print("------------------------------------")
  155. response = ec2Client.run_instances(
  156. ImageId=imageId,
  157. InstanceType=instanceType,
  158. Placement={'AvailabilityZone': availabilityZone, },
  159. KeyName=keyName,
  160. MinCount=1,
  161. MaxCount=1,
  162. UserData=userDataWebServer,
  163. SecurityGroupIds=[
  164. security_group_id,
  165. ],
  166. TagSpecifications=[
  167. {
  168. 'ResourceType': 'instance',
  169. 'Tags': [
  170. {'Key': 'Name', 'Value': 'tug-of-war-webserver' + str(i)},
  171. {'Key': 'tug-of-war', 'Value': 'webserver'}
  172. ],
  173. }
  174. ],
  175. )
  176. instanceIdWeb = response['Instances'][0]['InstanceId']
  177. instance = ec2Resource.Instance(instanceIdWeb)
  178. instance.wait_until_running()
  179. instance.load()
  180. print("tug-of-war-in-the-clouds can be accessed at: " + instance.public_ip_address)