ansibleutil.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # vim: expandtab:tabstop=4:shiftwidth=4
  2. import subprocess
  3. import sys
  4. import os
  5. import json
  6. import re
  7. class AnsibleUtil(object):
  8. def __init__(self):
  9. self.file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)))
  10. self.multi_ec2_path = os.path.realpath(os.path.join(self.file_path, '..','inventory','multi_ec2.py'))
  11. def get_inventory(self,args=[]):
  12. cmd = [self.multi_ec2_path]
  13. if args:
  14. cmd.extend(args)
  15. env = os.environ
  16. p = subprocess.Popen(cmd, stderr=subprocess.PIPE,
  17. stdout=subprocess.PIPE, env=env)
  18. out,err = p.communicate()
  19. if p.returncode != 0:
  20. raise RuntimeError(err)
  21. return json.loads(out.strip())
  22. def get_environments(self):
  23. pattern = re.compile(r'^tag_environment_(.*)')
  24. envs = []
  25. inv = self.get_inventory()
  26. for key in inv.keys():
  27. m = pattern.match(key)
  28. if m:
  29. envs.append(m.group(1))
  30. return envs
  31. def get_security_groups(self):
  32. pattern = re.compile(r'^security_group_(.*)')
  33. groups = []
  34. inv = self.get_inventory()
  35. for key in inv.keys():
  36. m = pattern.match(key)
  37. if m:
  38. groups.append(m.group(1))
  39. return groups
  40. def build_host_dict(self, args=[]):
  41. inv = self.get_inventory(args)
  42. inst_by_env = {}
  43. for dns, host in inv['_meta']['hostvars'].items():
  44. if host['ec2_tag_environment'] not in inst_by_env:
  45. inst_by_env[host['ec2_tag_environment']] = {}
  46. host_id = "%s:%s" % (host['ec2_tag_Name'],host['ec2_id'])
  47. inst_by_env[host['ec2_tag_environment']][host_id] = host
  48. return inst_by_env
  49. def get_hostnames(self, args=[]):
  50. inv = self.get_inventory(args)
  51. import collections
  52. hostnames = collections.defaultdict(list)
  53. for dns, host in inv['_meta']['hostvars'].items():
  54. hostnames['ec2_tag_Name'].append(host['ec2_id'])
  55. return hostnames
  56. def get_host_ids(self, args=[]):
  57. inv = self.get_inventory(args)
  58. ids = {}
  59. for dns, host in inv['_meta']['hostvars'].items():
  60. ids['ec2_id'] = host
  61. return ids