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.

290 lines
12 KiB

4 years ago
  1. #!/home/alpcentaur/ProjektA/PrototypeWebApp/venv/bin/python3.5
  2. # Copyright (c) 2011 Joel Barciauskas http://joel.barciausk.as/
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a
  5. # copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish, dis-
  8. # tribute, sublicense, and/or sell copies of the Software, and to permit
  9. # persons to whom the Software is furnished to do so, subject to the fol-
  10. # lowing conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  17. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  18. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. #
  22. # Auto Scaling Groups Tool
  23. #
  24. VERSION="0.1"
  25. usage = """%prog [options] [command]
  26. Commands:
  27. list|ls List all Auto Scaling Groups
  28. list-lc|ls-lc List all Launch Configurations
  29. delete <name> Delete ASG <name>
  30. delete-lc <name> Delete Launch Configuration <name>
  31. get <name> Get details of ASG <name>
  32. create <name> Create an ASG
  33. create-lc <name> Create a Launch Configuration
  34. update <name> <prop> <value> Update a property of an ASG
  35. update-image <asg-name> <lc-name> Update image ID for ASG by creating a new LC
  36. migrate-instances <name> Shut down current instances one by one and wait for ASG to start up a new instance with the current AMI (useful in conjunction with update-image)
  37. Examples:
  38. 1) Create launch configuration
  39. bin/asadmin create-lc my-lc-1 -i ami-1234abcd -t c1.xlarge -k my-key -s web-group -m
  40. 2) Create auto scaling group in us-east-1a and us-east-1c with a load balancer and min size of 2 and max size of 6
  41. bin/asadmin create my-asg -z us-east-1a -z us-east-1c -l my-lc-1 -b my-lb -H ELB -p 180 -x 2 -X 6
  42. """
  43. def get_group(autoscale, name):
  44. g = autoscale.get_all_groups(names=[name])
  45. if len(g) < 1:
  46. print "No auto scaling groups by the name of %s found" % name
  47. return sys.exit(1)
  48. return g[0]
  49. def get_lc(autoscale, name):
  50. l = autoscale.get_all_launch_configurations(names=[name])
  51. if len(l) < 1:
  52. print "No launch configurations by the name of %s found" % name
  53. sys.exit(1)
  54. return l[0]
  55. def list(autoscale):
  56. """List all ASGs"""
  57. print "%-20s %s" % ("Name", "LC Name")
  58. print "-"*80
  59. groups = autoscale.get_all_groups()
  60. for g in groups:
  61. print "%-20s %s" % (g.name, g.launch_config_name)
  62. def list_lc(autoscale):
  63. """List all LCs"""
  64. print "%-30s %-20s %s" % ("Name", "Image ID", "Instance Type")
  65. print "-"*80
  66. for l in autoscale.get_all_launch_configurations():
  67. print "%-30s %-20s %s" % (l.name, l.image_id, l.instance_type)
  68. def get(autoscale, name):
  69. """Get details about ASG <name>"""
  70. g = get_group(autoscale, name)
  71. print "="*80
  72. print "%-30s %s" % ('Name:', g.name)
  73. print "%-30s %s" % ('Launch configuration:', g.launch_config_name)
  74. print "%-30s %s" % ('Minimum size:', g.min_size)
  75. print "%-30s %s" % ('Maximum size:', g.max_size)
  76. print "%-30s %s" % ('Desired capacity:', g.desired_capacity)
  77. print "%-30s %s" % ('Load balancers:', ','.join(g.load_balancers))
  78. print
  79. print "Instances"
  80. print "---------"
  81. print "%-20s %-20s %-20s %s" % ("ID", "Status", "Health", "AZ")
  82. for i in g.instances:
  83. print "%-20s %-20s %-20s %s" % \
  84. (i.instance_id, i.lifecycle_state, i.health_status, i.availability_zone)
  85. print
  86. def create(autoscale, name, zones, lc_name, load_balancers, hc_type, hc_period,
  87. min_size, max_size, cooldown, capacity):
  88. """Create an ASG named <name>"""
  89. g = AutoScalingGroup(name=name, launch_config=lc_name,
  90. availability_zones=zones, load_balancers=load_balancers,
  91. default_cooldown=cooldown, health_check_type=hc_type,
  92. health_check_period=hc_period, desired_capacity=capacity,
  93. min_size=min_size, max_size=max_size)
  94. g = autoscale.create_auto_scaling_group(g)
  95. return list(autoscale)
  96. def create_lc(autoscale, name, image_id, instance_type, key_name,
  97. security_groups, instance_monitoring):
  98. l = LaunchConfiguration(name=name, image_id=image_id,
  99. instance_type=instance_type,key_name=key_name,
  100. security_groups=security_groups,
  101. instance_monitoring=instance_monitoring)
  102. l = autoscale.create_launch_configuration(l)
  103. return list_lc(autoscale)
  104. def update(autoscale, name, prop, value):
  105. g = get_group(autoscale, name)
  106. setattr(g, prop, value)
  107. g.update()
  108. return get(autoscale, name)
  109. def delete(autoscale, name, force_delete=False):
  110. """Delete this ASG"""
  111. g = get_group(autoscale, name)
  112. autoscale.delete_auto_scaling_group(g.name, force_delete)
  113. print "Auto scaling group %s deleted" % name
  114. return list(autoscale)
  115. def delete_lc(autoscale, name):
  116. """Delete this LC"""
  117. l = get_lc(autoscale, name)
  118. autoscale.delete_launch_configuration(name)
  119. print "Launch configuration %s deleted" % name
  120. return list_lc(autoscale)
  121. def update_image(autoscale, name, lc_name, image_id, is_migrate_instances=False):
  122. """ Get the current launch config,
  123. Update its name and image id
  124. Re-create it as a new launch config
  125. Update the ASG with the new LC
  126. Delete the old LC """
  127. g = get_group(autoscale, name)
  128. l = get_lc(autoscale, g.launch_config_name)
  129. old_lc_name = l.name
  130. l.name = lc_name
  131. l.image_id = image_id
  132. autoscale.create_launch_configuration(l)
  133. g.launch_config_name = l.name
  134. g.update()
  135. if(is_migrate_instances):
  136. migrate_instances(autoscale, name)
  137. else:
  138. return get(autoscale, name)
  139. def migrate_instances(autoscale, name):
  140. """ Shut down instances of the old image type one by one
  141. and let the ASG start up instances with the new image """
  142. g = get_group(autoscale, name)
  143. old_instances = g.instances
  144. ec2 = boto.connect_ec2()
  145. for old_instance in old_instances:
  146. print "Terminating instance " + old_instance.instance_id
  147. ec2.terminate_instances([old_instance.instance_id])
  148. while True:
  149. g = get_group(autoscale, name)
  150. new_instances = g.instances
  151. for new_instance in new_instances:
  152. hasOldInstance = False
  153. instancesReady = True
  154. if(old_instance.instance_id == new_instance.instance_id):
  155. hasOldInstance = True
  156. print "Waiting for old instance to shut down..."
  157. break
  158. elif(new_instance.lifecycle_state != 'InService'):
  159. instancesReady = False
  160. print "Waiting for instances to be ready...."
  161. break
  162. if(not hasOldInstance and instancesReady):
  163. break
  164. else:
  165. time.sleep(20)
  166. return get(autoscale, name)
  167. if __name__ == "__main__":
  168. try:
  169. import readline
  170. except ImportError:
  171. pass
  172. import boto
  173. import sys
  174. import time
  175. from optparse import OptionParser
  176. from boto.mashups.iobject import IObject
  177. from boto.ec2.autoscale import AutoScalingGroup
  178. from boto.ec2.autoscale import LaunchConfiguration
  179. parser = OptionParser(version=VERSION, usage=usage)
  180. """ Create launch config options """
  181. parser.add_option("-i", "--image-id",
  182. help="Image (AMI) ID", action="store",
  183. type="string", default=None, dest="image_id")
  184. parser.add_option("-t", "--instance-type",
  185. help="EC2 Instance Type (e.g., m1.large, c1.xlarge), default is m1.large",
  186. action="store", type="string", default="m1.large", dest="instance_type")
  187. parser.add_option("-k", "--key-name",
  188. help="EC2 Key Name",
  189. action="store", type="string", dest="key_name")
  190. parser.add_option("-s", "--security-group",
  191. help="EC2 Security Group",
  192. action="append", default=[], dest="security_groups")
  193. parser.add_option("-m", "--monitoring",
  194. help="Enable instance monitoring",
  195. action="store_true", default=False, dest="instance_monitoring")
  196. """ Create auto scaling group options """
  197. parser.add_option("-z", "--zone", help="Add availability zone", action="append", default=[], dest="zones")
  198. parser.add_option("-l", "--lc-name",
  199. help="Launch configuration name",
  200. action="store", default=None, type="string", dest="lc_name")
  201. parser.add_option("-b", "--load-balancer",
  202. help="Load balancer name",
  203. action="append", default=[], dest="load_balancers")
  204. parser.add_option("-H", "--health-check-type",
  205. help="Health check type (EC2 or ELB)",
  206. action="store", default="EC2", type="string", dest="hc_type")
  207. parser.add_option("-p", "--health-check-period",
  208. help="Health check period in seconds (default 300s)",
  209. action="store", default=300, type="int", dest="hc_period")
  210. parser.add_option("-X", "--max-size",
  211. help="Max size of ASG (default 10)",
  212. action="store", default=10, type="int", dest="max_size")
  213. parser.add_option("-x", "--min-size",
  214. help="Min size of ASG (default 2)",
  215. action="store", default=2, type="int", dest="min_size")
  216. parser.add_option("-c", "--cooldown",
  217. help="Cooldown time after a scaling activity in seconds (default 300s)",
  218. action="store", default=300, type="int", dest="cooldown")
  219. parser.add_option("-C", "--desired-capacity",
  220. help="Desired capacity of the ASG",
  221. action="store", default=None, type="int", dest="capacity")
  222. parser.add_option("-f", "--force",
  223. help="Force delete ASG",
  224. action="store_true", default=False, dest="force")
  225. parser.add_option("-y", "--migrate-instances",
  226. help="Automatically migrate instances to new image when running update-image",
  227. action="store_true", default=False, dest="migrate_instances")
  228. (options, args) = parser.parse_args()
  229. if len(args) < 1:
  230. parser.print_help()
  231. sys.exit(1)
  232. autoscale = boto.connect_autoscale()
  233. print "%s" % (autoscale.region.endpoint)
  234. command = args[0].lower()
  235. if command in ("ls", "list"):
  236. list(autoscale)
  237. elif command in ("ls-lc", "list-lc"):
  238. list_lc(autoscale)
  239. elif command == "get":
  240. get(autoscale, args[1])
  241. elif command == "create":
  242. create(autoscale, args[1], options.zones, options.lc_name,
  243. options.load_balancers, options.hc_type,
  244. options.hc_period, options.min_size, options.max_size,
  245. options.cooldown, options.capacity)
  246. elif command == "create-lc":
  247. create_lc(autoscale, args[1], options.image_id, options.instance_type,
  248. options.key_name, options.security_groups,
  249. options.instance_monitoring)
  250. elif command == "update":
  251. update(autoscale, args[1], args[2], args[3])
  252. elif command == "delete":
  253. delete(autoscale, args[1], options.force)
  254. elif command == "delete-lc":
  255. delete_lc(autoscale, args[1])
  256. elif command == "update-image":
  257. update_image(autoscale, args[1], args[2],
  258. options.image_id, options.migrate_instances)
  259. elif command == "migrate-instances":
  260. migrate_instances(autoscale, args[1])