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.

378 lines
13 KiB

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