elbadmin 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/env python
  2. # Copyright (c) 2009 Chris Moyer http://coredumped.org/
  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. # Elastic Load Balancer Tool
  23. #
  24. VERSION = "0.2"
  25. usage = """%prog [options] [command]
  26. Commands:
  27. list|ls List all Elastic Load Balancers
  28. delete <name> Delete ELB <name>
  29. get <name> Get all instances associated with <name>
  30. create <name> Create an ELB; -z and -l are required
  31. add <name> <instances> Add <instances> in ELB <name>
  32. remove|rm <name> <instances> Remove <instances> from ELB <name>
  33. reap <name> Remove terminated instances from ELB <name>
  34. enable|en <name> <zone> Enable Zone <zone> for ELB <name>
  35. disable <name> <zone> Disable Zone <zone> for ELB <name>
  36. addl <name> Add listeners (specified by -l) to the ELB
  37. <name>
  38. rml <name> <port> Remove Listener(s) specified by the port on
  39. the ELB <name>
  40. """
  41. def find_elb(elb, name):
  42. try:
  43. elbs = elb.get_all_load_balancers(name)
  44. except boto.exception.BotoServerError as se:
  45. if se.code == 'LoadBalancerNotFound':
  46. elbs = []
  47. else:
  48. raise
  49. if len(elbs) < 1:
  50. print "No load balancer by the name of %s found" % name
  51. return None
  52. elif len(elbs) > 1:
  53. print "More than one elb matches %s?" % name
  54. return None
  55. # Should not happen
  56. if name not in elbs[0].name:
  57. print "No load balancer by the name of %s found" % name
  58. return None
  59. return elbs[0]
  60. def list(elb):
  61. """List all ELBs"""
  62. print "%-20s %s" % ("Name", "DNS Name")
  63. print "-" * 80
  64. for b in elb.get_all_load_balancers():
  65. print "%-20s %s" % (b.name, b.dns_name)
  66. def check_valid_region(conn, region):
  67. if conn is None:
  68. print 'Invalid region (%s)' % region
  69. sys.exit(1)
  70. def get(elb, name):
  71. """Get details about ELB <name>"""
  72. b = find_elb(elb, name)
  73. if b:
  74. print "=" * 80
  75. print "Name: %s" % b.name
  76. print "DNS Name: %s" % b.dns_name
  77. if b.canonical_hosted_zone_name:
  78. chzn = b.canonical_hosted_zone_name
  79. print "Canonical hosted zone name: %s" % chzn
  80. if b.canonical_hosted_zone_name_id:
  81. chznid = b.canonical_hosted_zone_name_id
  82. print "Canonical hosted zone name id: %s" % chznid
  83. print
  84. print "Health Check: %s" % b.health_check
  85. print
  86. print "Listeners"
  87. print "---------"
  88. print "%-8s %-8s %s" % ("IN", "OUT", "PROTO")
  89. for l in b.listeners:
  90. print "%-8s %-8s %s" % (l[0], l[1], l[2])
  91. print
  92. print " Zones "
  93. print "---------"
  94. for z in b.availability_zones:
  95. print z
  96. print
  97. # Make map of all instance Id's to Name tags
  98. import boto
  99. if not options.region:
  100. ec2 = boto.connect_ec2()
  101. else:
  102. ec2 = boto.ec2.connect_to_region(options.region)
  103. check_valid_region(ec2, options.region)
  104. instance_health = b.get_instance_health()
  105. instances = [state.instance_id for state in instance_health]
  106. names = dict((k,'') for k in instances)
  107. for i in ec2.get_only_instances():
  108. if i.id in instances:
  109. names[i.id] = i.tags.get('Name', '')
  110. name_column_width = max([4] + [len(v) for k,v in names.iteritems()]) + 2
  111. print "Instances"
  112. print "---------"
  113. print "%-12s %-15s %-*s %s" % ("ID",
  114. "STATE",
  115. name_column_width, "NAME",
  116. "DESCRIPTION")
  117. for state in instance_health:
  118. print "%-12s %-15s %-*s %s" % (state.instance_id,
  119. state.state,
  120. name_column_width, names[state.instance_id],
  121. state.description)
  122. print
  123. def create(elb, name, zones, listeners):
  124. """Create an ELB named <name>"""
  125. l_list = []
  126. for l in listeners:
  127. l = l.split(",")
  128. if l[2] == 'HTTPS':
  129. l_list.append((int(l[0]), int(l[1]), l[2], l[3]))
  130. else:
  131. l_list.append((int(l[0]), int(l[1]), l[2]))
  132. b = elb.create_load_balancer(name, zones, l_list)
  133. return get(elb, name)
  134. def delete(elb, name):
  135. """Delete this ELB"""
  136. b = find_elb(elb, name)
  137. if b:
  138. b.delete()
  139. print "Load Balancer %s deleted" % name
  140. def add_instances(elb, name, instances):
  141. """Add <instance> to ELB <name>"""
  142. b = find_elb(elb, name)
  143. if b:
  144. b.register_instances(instances)
  145. return get(elb, name)
  146. def remove_instances(elb, name, instances):
  147. """Remove instance from elb <name>"""
  148. b = find_elb(elb, name)
  149. if b:
  150. b.deregister_instances(instances)
  151. return get(elb, name)
  152. def reap_instances(elb, name):
  153. """Remove terminated instances from elb <name>"""
  154. b = find_elb(elb, name)
  155. if b:
  156. for state in b.get_instance_health():
  157. if (state.state == 'OutOfService' and
  158. state.description == 'Instance is in terminated state.'):
  159. b.deregister_instances([state.instance_id])
  160. return get(elb, name)
  161. def enable_zone(elb, name, zone):
  162. """Enable <zone> for elb"""
  163. b = find_elb(elb, name)
  164. if b:
  165. b.enable_zones([zone])
  166. return get(elb, name)
  167. def disable_zone(elb, name, zone):
  168. """Disable <zone> for elb"""
  169. b = find_elb(elb, name)
  170. if b:
  171. b.disable_zones([zone])
  172. return get(elb, name)
  173. def add_listener(elb, name, listeners):
  174. """Add listeners to a given load balancer"""
  175. l_list = []
  176. for l in listeners:
  177. l = l.split(",")
  178. l_list.append((int(l[0]), int(l[1]), l[2]))
  179. b = find_elb(elb, name)
  180. if b:
  181. b.create_listeners(l_list)
  182. return get(elb, name)
  183. def rm_listener(elb, name, ports):
  184. """Remove listeners from a given load balancer"""
  185. b = find_elb(elb, name)
  186. if b:
  187. b.delete_listeners(ports)
  188. return get(elb, name)
  189. if __name__ == "__main__":
  190. try:
  191. import readline
  192. except ImportError:
  193. pass
  194. import boto
  195. import sys
  196. from optparse import OptionParser
  197. from boto.mashups.iobject import IObject
  198. parser = OptionParser(version=VERSION, usage=usage)
  199. parser.add_option("-z", "--zone",
  200. help="Operate on zone",
  201. action="append", default=[], dest="zones")
  202. parser.add_option("-l", "--listener",
  203. help="Specify Listener in,out,proto",
  204. action="append", default=[], dest="listeners")
  205. parser.add_option("-r", "--region",
  206. help="Region to connect to",
  207. action="store", dest="region")
  208. (options, args) = parser.parse_args()
  209. if len(args) < 1:
  210. parser.print_help()
  211. sys.exit(1)
  212. if not options.region:
  213. elb = boto.connect_elb()
  214. else:
  215. import boto.ec2.elb
  216. elb = boto.ec2.elb.connect_to_region(options.region)
  217. check_valid_region(elb, options.region)
  218. print "%s" % (elb.region.endpoint)
  219. command = args[0].lower()
  220. if command in ("ls", "list"):
  221. list(elb)
  222. elif command == "get":
  223. get(elb, args[1])
  224. elif command == "create":
  225. if not options.listeners:
  226. print "-l option required for command create"
  227. sys.exit(1)
  228. if not options.zones:
  229. print "-z option required for command create"
  230. sys.exit(1)
  231. create(elb, args[1], options.zones, options.listeners)
  232. elif command == "delete":
  233. delete(elb, args[1])
  234. elif command in ("add", "put"):
  235. add_instances(elb, args[1], args[2:])
  236. elif command in ("rm", "remove"):
  237. remove_instances(elb, args[1], args[2:])
  238. elif command == "reap":
  239. reap_instances(elb, args[1])
  240. elif command in ("en", "enable"):
  241. enable_zone(elb, args[1], args[2])
  242. elif command == "disable":
  243. disable_zone(elb, args[1], args[2])
  244. elif command == "addl":
  245. if not options.listeners:
  246. print "-l option required for command addl"
  247. sys.exit(1)
  248. add_listener(elb, args[1], options.listeners)
  249. elif command == "rml":
  250. if not args[2:]:
  251. print "port required"
  252. sys.exit(2)
  253. rm_listener(elb, args[1], args[2:])