cli.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import logging
  2. import sys
  3. import os
  4. import pprint
  5. from ansible.parsing.dataloader import DataLoader
  6. from ansible.inventory.manager import InventoryManager
  7. import subprocess
  8. pp = pprint.PrettyPrinter()
  9. logger = logging.getLogger(__name__)
  10. DEFAULT_HOST_FILE = 'hosts'
  11. DEFAULT_PLAYBOOK = 'playbook.yml'
  12. DEFAULT_ANSIBLE_DIR = 'lab/ansible'
  13. def get_inventory() -> dict:
  14. host_file = os.path.join(DEFAULT_ANSIBLE_DIR, DEFAULT_HOST_FILE)
  15. loader = DataLoader()
  16. inventory = InventoryManager(loader=loader, sources=host_file)
  17. x = {}
  18. ignore = ('all', 'ungrouped')
  19. x.update(inventory.groups['all'].serialize()['vars'])
  20. group_dict = inventory.get_groups_dict()
  21. for group in inventory.groups:
  22. if group in ignore:
  23. continue
  24. x.update({
  25. group: group_dict[group]
  26. })
  27. return x
  28. def roles() -> list:
  29. sorted_roles = sorted(list(get_inventory().keys()))
  30. if sys.stdin and sys.stdin.isatty():
  31. for role in sorted_roles:
  32. print(role)
  33. return sorted_roles
  34. def update(roles):
  35. if len(roles) == 1:
  36. roles = roles[0]
  37. else:
  38. roles = ",".join(roles)
  39. cmd = "ansible-playbook"
  40. limit = f"--limit={roles}"
  41. call_list = [cmd, DEFAULT_PLAYBOOK, "-i", DEFAULT_HOST_FILE, limit]
  42. print(call_list)
  43. if sys.stdin and sys.stdin.isatty():
  44. subprocess.run(call_list, cwd=DEFAULT_ANSIBLE_DIR)
  45. def newjail(jail_name) -> None:
  46. if len(jail_name) == 1:
  47. jail_name = jail_name[0]
  48. else:
  49. print('Requires a single new jail name')
  50. return
  51. call_list = ["ansible", "rhea", "-m", "ansible.builtin.shell", "-a", f'"/usr/local/bin/newjail {jail_name}"', "--become", "-K"]
  52. print(call_list)
  53. if sys.stdin and sys.stdin.isatty():
  54. subprocess.run(call_list, cwd=DEFAULT_ANSIBLE_DIR)
  55. def main():
  56. del sys.argv[0]
  57. if len(sys.argv) > 0:
  58. func = sys.argv.pop(0)
  59. args = sys.argv
  60. if args:
  61. return eval(func)(args)
  62. else:
  63. return eval(func)()
  64. if __name__ == '__main__':
  65. main()