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.

321 lines
11 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. subnet1 = 'subnet-41422b28'
  10. subnet2 = 'subnet-5c5f6d16'
  11. subnet3 = 'subnet-6f2ea214'
  12. userDataDB = ('#!/bin/bash\n'
  13. '#!/bin/bash\n'
  14. '# extra repo for RedHat rpms\n'
  15. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  16. '# essential tools\n'
  17. 'yum install -y joe htop git\n'
  18. '# mysql\n'
  19. 'yum install -y mariadb mariadb-server\n'
  20. '\n'
  21. 'service mariadb start\n'
  22. '\n'
  23. 'echo "create database cloud_tug_of_war" | mysql -u root\n'
  24. '\n'
  25. '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'
  26. '\n'
  27. 'echo "CREATE USER \'cloud_tug_of_war\'@\'%\' IDENTIFIED BY \'cloudpass\';" | mysql -u root\n'
  28. 'echo "GRANT ALL PRIVILEGES ON cloud_tug_of_war.* TO \'cloud_tug_of_war\'@\'%\';" | mysql -u root\n'
  29. 'echo "FLUSH PRIVILEGES" | mysql -u root\n'
  30. )
  31. # convert with: cat install-mysql | sed "s/^/'/; s/$/\\\n'/"
  32. client = boto3.setup_default_session(region_name=region)
  33. ec2Client = boto3.client("ec2")
  34. ec2Resource = boto3.resource('ec2')
  35. response = ec2Client.describe_vpcs()
  36. vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  37. elbv2Client = boto3.client('elbv2')
  38. asClient = boto3.client('autoscaling')
  39. print("Deleting auto scaling group...")
  40. print("------------------------------------")
  41. try:
  42. response = asClient.delete_auto_scaling_group(AutoScalingGroupName='tug-of-war-asg-autoscalinggroup', ForceDelete=True)
  43. except ClientError as e:
  44. print(e)
  45. print("Deleting launch configuration...")
  46. print("------------------------------------")
  47. try:
  48. response = asClient.delete_launch_configuration(LaunchConfigurationName='tug-of-war-asg-launchconfig')
  49. except ClientError as e:
  50. print(e)
  51. print("Deleting old instances...")
  52. print("------------------------------------")
  53. response = ec2Client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['tug-of-war-asg']}])
  54. print(response)
  55. reservations = response['Reservations']
  56. for reservation in reservations:
  57. for instance in reservation['Instances']:
  58. if instance['State']['Name'] == "running":
  59. response = ec2Client.terminate_instances(InstanceIds=[instance['InstanceId']])
  60. print(response)
  61. instanceToTerminate = ec2Resource.Instance(instance['InstanceId'])
  62. instanceToTerminate.wait_until_terminated()
  63. print("Deleting load balancer and deps...")
  64. print("------------------------------------")
  65. try:
  66. response = elbv2Client.describe_load_balancers(Names=['tug-of-war-asg-loadbalancer'])
  67. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  68. response = elbv2Client.delete_load_balancer(LoadBalancerArn=loadbalancer_arn)
  69. waiter = elbv2Client.get_waiter('load_balancers_deleted')
  70. waiter.wait(LoadBalancerArns=[loadbalancer_arn])
  71. except ClientError as e:
  72. print(e)
  73. try:
  74. response = elbv2Client.describe_target_groups(Names=['tug-of-war-asg-targetgroup'])
  75. while len(response.get('TargetGroups', [{}])) > 0:
  76. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  77. try:
  78. response = elbv2Client.delete_target_group(TargetGroupArn=targetgroup_arn)
  79. except ClientError as e:
  80. print(e)
  81. response = elbv2Client.describe_target_groups(Names=['tug-of-war-asg-targetgroup'])
  82. time.sleep(5)
  83. except ClientError as e:
  84. print(e)
  85. print("Delete old security group...")
  86. print("------------------------------------")
  87. try:
  88. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war-asg']}])
  89. while len(response.get('SecurityGroups', [{}])) > 0:
  90. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  91. try:
  92. response = ec2Client.delete_security_group(GroupName='tug-of-war-asg')
  93. except ClientError as e:
  94. print(e)
  95. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war-asg']}])
  96. time.sleep(5)
  97. except ClientError as e:
  98. print(e)
  99. print("Create security group...")
  100. print("------------------------------------")
  101. try:
  102. response = ec2Client.create_security_group(GroupName='tug-of-war-asg',
  103. Description='tug-of-war-asg',
  104. VpcId=vpc_id)
  105. security_group_id = response['GroupId']
  106. print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
  107. data = ec2Client.authorize_security_group_ingress(
  108. GroupId=security_group_id,
  109. IpPermissions=[
  110. {'IpProtocol': 'tcp',
  111. 'FromPort': 3306,
  112. 'ToPort': 3306,
  113. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  114. {'IpProtocol': 'tcp',
  115. 'FromPort': 22,
  116. 'ToPort': 22,
  117. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  118. {'IpProtocol': 'tcp',
  119. 'FromPort': 80,
  120. 'ToPort': 80,
  121. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  122. {'IpProtocol': 'tcp',
  123. 'FromPort': 443,
  124. 'ToPort': 443,
  125. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
  126. ])
  127. print('Ingress Successfully Set %s' % data)
  128. except ClientError as e:
  129. print(e)
  130. print("Running new DB instance...")
  131. print("------------------------------------")
  132. response = ec2Client.run_instances(
  133. ImageId=imageId,
  134. InstanceType=instanceType,
  135. Placement={'AvailabilityZone': availabilityZone, },
  136. KeyName=keyName,
  137. MinCount=1,
  138. MaxCount=1,
  139. UserData=userDataDB,
  140. SecurityGroupIds=[
  141. security_group_id,
  142. ],
  143. TagSpecifications=[
  144. {
  145. 'ResourceType': 'instance',
  146. 'Tags': [
  147. {'Key': 'Name', 'Value': 'tug-of-war-asg-db1'},
  148. {'Key': 'tug-of-war-asg', 'Value': 'db'}
  149. ],
  150. }
  151. ],
  152. )
  153. instanceIdDB = response['Instances'][0]['InstanceId']
  154. privateIpDB = response['Instances'][0]['PrivateIpAddress']
  155. # privateIpDB = response['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId']
  156. instance = ec2Resource.Instance(instanceIdDB)
  157. instance.wait_until_running()
  158. print(instanceIdDB)
  159. userDataWebServer = ('#!/bin/bash\n'
  160. '# extra repo for RedHat rpms\n'
  161. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  162. '# essential tools\n'
  163. 'yum install -y joe htop git\n'
  164. '# mysql\n'
  165. 'yum install -y httpd php php-mysql\n'
  166. '\n'
  167. 'service httpd start\n'
  168. 'service httpd start\n'
  169. '\n'
  170. # 'wget http://mmnet.informatik.hs-fulda.de/cloudcomp/tug-of-war-in-the-clouds.tar.gz\n'
  171. # 'cp tug-of-war-in-the-clouds.tar.gz /var/www/html/\n'
  172. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  173. 'cd /var/www/html\n'
  174. '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'
  175. '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'
  176. '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'
  177. '\n'
  178. '# change hostname of db connection\n'
  179. 'sed -i s/localhost/' + privateIpDB + '/g /var/www/html/config.php\n'
  180. )
  181. print("Creating launch configuration...")
  182. print("------------------------------------")
  183. response = asClient.create_launch_configuration(
  184. #IamInstanceProfile='my-iam-role',
  185. ImageId=imageId,
  186. InstanceType=instanceType,
  187. LaunchConfigurationName='tug-of-war-asg-launchconfig',
  188. UserData=userDataWebServer,
  189. KeyName=keyName,
  190. SecurityGroups=[
  191. security_group_id,
  192. ],
  193. )
  194. elbv2Client = boto3.client('elbv2')
  195. print("Creating load balancer...")
  196. print("------------------------------------")
  197. response = elbv2Client.create_load_balancer(
  198. Name='tug-of-war-asg-loadbalancer',
  199. Subnets=[
  200. subnet1,
  201. subnet2,
  202. subnet3,
  203. ],
  204. SecurityGroups=[
  205. security_group_id
  206. ]
  207. )
  208. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  209. loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
  210. print("Creating target group...")
  211. print("------------------------------------")
  212. response = elbv2Client.create_target_group(
  213. Name='tug-of-war-asg-targetgroup',
  214. Port=80,
  215. Protocol='HTTP',
  216. VpcId=vpc_id,
  217. )
  218. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  219. print("Creating listener...")
  220. print("------------------------------------")
  221. response = elbv2Client.create_listener(
  222. DefaultActions=[
  223. {
  224. 'TargetGroupArn': targetgroup_arn,
  225. 'Type': 'forward',
  226. },
  227. ],
  228. LoadBalancerArn=loadbalancer_arn,
  229. Port=80,
  230. Protocol='HTTP',
  231. )
  232. response = elbv2Client.modify_target_group_attributes(
  233. TargetGroupArn=targetgroup_arn,
  234. Attributes=[
  235. {
  236. 'Key': 'stickiness.enabled',
  237. 'Value': 'true'
  238. },
  239. ]
  240. )
  241. print("Creating auto scaling group...")
  242. print("------------------------------------")
  243. response = asClient.create_auto_scaling_group(
  244. AutoScalingGroupName='tug-of-war-asg-autoscalinggroup',
  245. LaunchConfigurationName='tug-of-war-asg-launchconfig',
  246. MaxSize=3,
  247. MinSize=1,
  248. HealthCheckGracePeriod=120,
  249. HealthCheckType='ELB',
  250. TargetGroupARNs=[
  251. targetgroup_arn,
  252. ],
  253. VPCZoneIdentifier=subnet1 + ', ' + ', ' + subnet2 + ', ' + subnet3,
  254. Tags=[
  255. {'Key': 'Name', 'Value': 'tug-of-war-asg-webserver', 'PropagateAtLaunch': True},
  256. {'Key': 'tug-of-war', 'Value': 'webserver', 'PropagateAtLaunch': True}
  257. ],
  258. )
  259. print(loadbalancer_arn)
  260. print(targetgroup_arn)
  261. print('app/tug-of-war-asg-loadbalancer/'+str(loadbalancer_arn).split('/')[3]+'/targetgroup/tug-of-war-asg-targetgroup/'+str(targetgroup_arn).split('/')[2])
  262. response = asClient.put_scaling_policy(
  263. AutoScalingGroupName='tug-of-war-asg-autoscalinggroup',
  264. PolicyName='tug-of-war-asg-scalingpolicy',
  265. PolicyType='TargetTrackingScaling',
  266. EstimatedInstanceWarmup=30,
  267. TargetTrackingConfiguration={
  268. 'PredefinedMetricSpecification': {
  269. 'PredefinedMetricType': 'ALBRequestCountPerTarget',
  270. 'ResourceLabel': 'app/tug-of-war-asg-loadbalancer/'+str(loadbalancer_arn).split('/')[3]+'/targetgroup/tug-of-war-asg-targetgroup/'+str(targetgroup_arn).split('/')[2]
  271. },
  272. 'TargetValue': 5.0,
  273. }
  274. )