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.

206 lines
7.2 KiB

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