ansibleutil.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 build_host_dict(self):
  41. inv = self.get_inventory()
  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. #if inst_by_env[host['ec2_tag_environment']][host['ec2_tag_Name']]:
  47. #raise Exception('Duplicate ec2_tag_Name found: %s' % host['ec2_tag_Name'])
  48. host_id = "%s:%s" % (host['ec2_tag_Name'],host['ec2_id'])
  49. inst_by_env[host['ec2_tag_environment']][host_id] = host
  50. return inst_by_env