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.

217 lines
7.9 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. rdsClient = boto3.client("rds")
  27. subnet_id = ec2Client.describe_subnets(
  28. Filters=[
  29. {
  30. 'Name': 'availability-zone', 'Values': [availabilityZone]
  31. }
  32. ])['Subnets'][0]['SubnetId']
  33. print("Deleting old instance...")
  34. print("------------------------------------")
  35. response = ec2Client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['tug-of-war-rds']}])
  36. print(response)
  37. reservations = response['Reservations']
  38. for reservation in reservations:
  39. for instance in reservation['Instances']:
  40. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  41. response = ec2Client.terminate_instances(InstanceIds=[instance['InstanceId']])
  42. print(response)
  43. instanceToTerminate = ec2Resource.Instance(instance['InstanceId'])
  44. instanceToTerminate.wait_until_terminated()
  45. print("Deleting old DB instance...")
  46. print("------------------------------------")
  47. try:
  48. response = rdsClient.delete_db_instance(
  49. DBInstanceIdentifier='tug-of-war-rds-db1',
  50. SkipFinalSnapshot=True,
  51. DeleteAutomatedBackups=True
  52. )
  53. except ClientError as e:
  54. print(e)
  55. waiter = rdsClient.get_waiter('db_instance_deleted')
  56. waiter.wait(DBInstanceIdentifier='tug-of-war-rds-db1')
  57. #time.sleep(5)
  58. print("Delete old security group...")
  59. print("------------------------------------")
  60. try:
  61. response = ec2Client.delete_security_group(GroupName='tug-of-war-rds')
  62. except ClientError as e:
  63. print(e)
  64. print("Create security group...")
  65. print("------------------------------------")
  66. try:
  67. response = ec2Client.create_security_group(GroupName='tug-of-war-rds',
  68. Description='tug-of-war-rds',
  69. VpcId=vpc_id)
  70. security_group_id = response['GroupId']
  71. print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
  72. data = ec2Client.authorize_security_group_ingress(
  73. GroupId=security_group_id,
  74. IpPermissions=[
  75. {'IpProtocol': 'tcp',
  76. 'FromPort': 3306,
  77. 'ToPort': 3306,
  78. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  79. {'IpProtocol': 'tcp',
  80. 'FromPort': 22,
  81. 'ToPort': 22,
  82. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  83. {'IpProtocol': 'tcp',
  84. 'FromPort': 80,
  85. 'ToPort': 80,
  86. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  87. {'IpProtocol': 'tcp',
  88. 'FromPort': 443,
  89. 'ToPort': 443,
  90. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
  91. ])
  92. print('Ingress Successfully Set %s' % data)
  93. except ClientError as e:
  94. print(e)
  95. print("Running new DB instance...")
  96. print("------------------------------------")
  97. response = rdsClient.create_db_instance(DBInstanceIdentifier="tug-of-war-rds-db1",
  98. AllocatedStorage=20,
  99. DBName='cloud_tug_of_war',
  100. # Engine='mariadb',
  101. Engine='mysql',
  102. # General purpose SSD
  103. StorageType='gp2',
  104. #StorageEncrypted=True,
  105. AutoMinorVersionUpgrade=True,
  106. # Set this to true later?
  107. MultiAZ=False,
  108. MasterUsername='cloud_tug_of_war',
  109. MasterUserPassword='cloudpass',
  110. VpcSecurityGroupIds=[security_group_id],
  111. #DBInstanceClass='db.m3.2xlarge',
  112. DBInstanceClass='db.t3.micro',
  113. Tags=[
  114. {'Key': 'Name', 'Value': 'tug-of-war-rds-db1'},
  115. {'Key': 'tug-of-war-rds', 'Value': 'db'}
  116. ],
  117. )
  118. waiter = rdsClient.get_waiter('db_instance_available')
  119. waiter.wait(DBInstanceIdentifier='tug-of-war-rds-db1')
  120. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war-rds']}])
  121. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  122. response = rdsClient.describe_db_instances(DBInstanceIdentifier='tug-of-war-rds-db1')
  123. print(response)
  124. dbEndpointAddress = response['DBInstances'][0]['Endpoint']['Address']
  125. dbEndpointPort = response['DBInstances'][0]['Endpoint']['Port']
  126. print(str(dbEndpointAddress) + ":" + str(dbEndpointPort))
  127. userDataWebServer = ('#!/bin/bash\n'
  128. '# extra repo for RedHat rpms\n'
  129. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  130. '# essential tools\n'
  131. 'yum install -y joe htop git\n'
  132. '# httpd and mysql client\n'
  133. 'yum install -y httpd mariadb\n'
  134. '# fix php5.x PDO prob PDO::__construct(): Server sent charset (255) unknown to the client.\n'
  135. '# by using Amazons Linux 2 PHP extras\n'
  136. 'amazon-linux-extras install -y php7.4\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. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  143. 'cd /var/www/html\n'
  144. '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'
  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/cloud.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/config.php\n'
  147. '\n'
  148. '# change hostname of db connection\n'
  149. 'sed -i s/localhost/' + dbEndpointAddress + '/g /var/www/html/config.php\n'
  150. '\n'
  151. '# create default table\n'
  152. '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'
  153. )
  154. for i in range(1, 2):
  155. print("Running new Web Server instance...")
  156. print("------------------------------------")
  157. response = ec2Client.run_instances(
  158. ImageId=imageId,
  159. InstanceType=instanceType,
  160. Placement={'AvailabilityZone': availabilityZone, },
  161. KeyName=keyName,
  162. MinCount=1,
  163. MaxCount=1,
  164. UserData=userDataWebServer,
  165. SecurityGroupIds=[
  166. security_group_id,
  167. ],
  168. TagSpecifications=[
  169. {
  170. 'ResourceType': 'instance',
  171. 'Tags': [
  172. {'Key': 'Name', 'Value': 'tug-of-war-rds-webserver' + str(i)},
  173. {'Key': 'tug-of-war-rds', 'Value': 'webserver'}
  174. ],
  175. }
  176. ],
  177. )
  178. instanceIdWeb = response['Instances'][0]['InstanceId']
  179. instance = ec2Resource.Instance(instanceIdWeb)
  180. instance.wait_until_running()
  181. instance.load()
  182. print("tug-of-war-in-the-clouds can be accessed at: " + instance.public_ip_address)