ansibleutil.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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):
  12. cmd = [self.multi_ec2_path]
  13. env = {}
  14. p = subprocess.Popen(cmd, stderr=subprocess.PIPE,
  15. stdout=subprocess.PIPE, env=env)
  16. out,err = p.communicate()
  17. if p.returncode != 0:
  18. raise RuntimeError(err)
  19. with open('/tmp/ans.out','w') as fd:
  20. fd.writelines(out)
  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 get_host_address(self):
  41. pattern = re.compile(r'^tag_Name_(.*)')
  42. inv = self.get_inventory()
  43. inst_names = {}
  44. for key in inv.keys():
  45. m = pattern.match(key)
  46. if m: inst_names[m.group(1)] = inv[key]
  47. return inst_names