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.

339 lines
12 KiB

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