ansibleutil.py 1.8 KB

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