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.

305 lines
10 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" or instance['State']['Name'] == "pending":
  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. except ClientError as e:
  70. print(e)
  71. time.sleep(5)
  72. try:
  73. response = elbv2Client.describe_target_groups(Names=['tug-of-war-asg-targetgroup'])
  74. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  75. response = elbv2Client.delete_target_group(TargetGroupArn=targetgroup_arn)
  76. except ClientError as e:
  77. print(e)
  78. print("Delete old security group...")
  79. print("------------------------------------")
  80. try:
  81. response = ec2Client.delete_security_group(GroupName='tug-of-war-asg')
  82. except ClientError as e:
  83. print(e)
  84. print("Create security group...")
  85. print("------------------------------------")
  86. try:
  87. response = ec2Client.create_security_group(GroupName='tug-of-war-asg',
  88. Description='tug-of-war-asg',
  89. VpcId=vpc_id)
  90. security_group_id = response['GroupId']
  91. print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
  92. data = ec2Client.authorize_security_group_ingress(
  93. GroupId=security_group_id,
  94. IpPermissions=[
  95. {'IpProtocol': 'tcp',
  96. 'FromPort': 3306,
  97. 'ToPort': 3306,
  98. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  99. {'IpProtocol': 'tcp',
  100. 'FromPort': 22,
  101. 'ToPort': 22,
  102. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  103. {'IpProtocol': 'tcp',
  104. 'FromPort': 80,
  105. 'ToPort': 80,
  106. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  107. {'IpProtocol': 'tcp',
  108. 'FromPort': 443,
  109. 'ToPort': 443,
  110. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
  111. ])
  112. print('Ingress Successfully Set %s' % data)
  113. except ClientError as e:
  114. print(e)
  115. print("Running new DB instance...")
  116. print("------------------------------------")
  117. response = ec2Client.run_instances(
  118. ImageId=imageId,
  119. InstanceType=instanceType,
  120. Placement={'AvailabilityZone': availabilityZone, },
  121. KeyName=keyName,
  122. MinCount=1,
  123. MaxCount=1,
  124. UserData=userDataDB,
  125. SecurityGroupIds=[
  126. security_group_id,
  127. ],
  128. TagSpecifications=[
  129. {
  130. 'ResourceType': 'instance',
  131. 'Tags': [
  132. {'Key': 'Name', 'Value': 'tug-of-war-asg-db1'},
  133. {'Key': 'tug-of-war-asg', 'Value': 'db'}
  134. ],
  135. }
  136. ],
  137. )
  138. instanceIdDB = response['Instances'][0]['InstanceId']
  139. privateIpDB = response['Instances'][0]['PrivateIpAddress']
  140. # privateIpDB = response['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId']
  141. instance = ec2Resource.Instance(instanceIdDB)
  142. instance.wait_until_running()
  143. print(instanceIdDB)
  144. userDataWebServer = ('#!/bin/bash\n'
  145. '# extra repo for RedHat rpms\n'
  146. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  147. '# essential tools\n'
  148. 'yum install -y joe htop git\n'
  149. '# mysql\n'
  150. 'yum install -y httpd php php-mysql\n'
  151. '\n'
  152. 'service httpd start\n'
  153. 'service httpd start\n'
  154. '\n'
  155. # 'wget http://mmnet.informatik.hs-fulda.de/cloudcomp/tug-of-war-in-the-clouds.tar.gz\n'
  156. # 'cp tug-of-war-in-the-clouds.tar.gz /var/www/html/\n'
  157. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  158. 'cd /var/www/html\n'
  159. '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'
  160. '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'
  161. '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'
  162. '\n'
  163. '# change hostname of db connection\n'
  164. 'sed -i s/localhost/' + privateIpDB + '/g /var/www/html/config.php\n'
  165. )
  166. print("Creating launch configuration...")
  167. print("------------------------------------")
  168. response = asClient.create_launch_configuration(
  169. #IamInstanceProfile='my-iam-role',
  170. ImageId=imageId,
  171. InstanceType=instanceType,
  172. LaunchConfigurationName='tug-of-war-asg-launchconfig',
  173. UserData=userDataWebServer,
  174. KeyName=keyName,
  175. SecurityGroups=[
  176. security_group_id,
  177. ],
  178. )
  179. elbv2Client = boto3.client('elbv2')
  180. print("Creating load balancer...")
  181. print("------------------------------------")
  182. response = elbv2Client.create_load_balancer(
  183. Name='tug-of-war-asg-loadbalancer',
  184. Subnets=[
  185. subnet1,
  186. subnet2,
  187. subnet3,
  188. ],
  189. SecurityGroups=[
  190. security_group_id
  191. ]
  192. )
  193. loadbalancer_arn = response.get('LoadBalancers', [{}])[0].get('LoadBalancerArn', '')
  194. loadbalancer_dns = response.get('LoadBalancers', [{}])[0].get('DNSName', '')
  195. print("Creating target group...")
  196. print("------------------------------------")
  197. response = elbv2Client.create_target_group(
  198. Name='tug-of-war-asg-targetgroup',
  199. Port=80,
  200. Protocol='HTTP',
  201. VpcId=vpc_id,
  202. )
  203. targetgroup_arn = response.get('TargetGroups', [{}])[0].get('TargetGroupArn', '')
  204. print("Creating listener...")
  205. print("------------------------------------")
  206. response = elbv2Client.create_listener(
  207. DefaultActions=[
  208. {
  209. 'TargetGroupArn': targetgroup_arn,
  210. 'Type': 'forward',
  211. },
  212. ],
  213. LoadBalancerArn=loadbalancer_arn,
  214. Port=80,
  215. Protocol='HTTP',
  216. )
  217. response = elbv2Client.modify_target_group_attributes(
  218. TargetGroupArn=targetgroup_arn,
  219. Attributes=[
  220. {
  221. 'Key': 'stickiness.enabled',
  222. 'Value': 'true'
  223. },
  224. ]
  225. )
  226. print("Creating auto scaling group...")
  227. print("------------------------------------")
  228. response = asClient.create_auto_scaling_group(
  229. AutoScalingGroupName='tug-of-war-asg-autoscalinggroup',
  230. LaunchConfigurationName='tug-of-war-asg-launchconfig',
  231. MaxSize=3,
  232. MinSize=1,
  233. HealthCheckGracePeriod=120,
  234. HealthCheckType='ELB',
  235. TargetGroupARNs=[
  236. targetgroup_arn,
  237. ],
  238. VPCZoneIdentifier=subnet1 + ', ' + ', ' + subnet2 + ', ' + subnet3,
  239. Tags=[
  240. {'Key': 'Name', 'Value': 'tug-of-war-asg-webserver', 'PropagateAtLaunch': True},
  241. {'Key': 'tug-of-war', 'Value': 'webserver', 'PropagateAtLaunch': True}
  242. ],
  243. )
  244. print('app/tug-of-war-asg-loadbalancer/'+str(loadbalancer_arn).split('/')[2]+'/targetgroup/tug-of-war-asg-targetgroup/'+str(targetgroup_arn).split('/')[1]+'target-group-id')
  245. response = asClient.put_scaling_policy(
  246. AutoScalingGroupName='tug-of-war-asg-autoscalinggroup',
  247. PolicyName='tug-of-war-asg-scalingpolicy',
  248. PolicyType='TargetTrackingScaling',
  249. EstimatedInstanceWarmup=30,
  250. TargetTrackingConfiguration={
  251. 'PredefinedMetricSpecification': {
  252. 'PredefinedMetricType': 'ALBRequestCountPerTarget',
  253. 'ResourceLabel': 'app/tug-of-war-asg-loadbalancer/'+str(loadbalancer_arn).split('/')[2]+'/targetgroup/tug-of-war-asg-targetgroup/'+str(targetgroup_arn).split('/')[1]+'target-group-id'
  254. },
  255. 'TargetValue': 5.0,
  256. }
  257. )