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.

197 lines
7.2 KiB

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