cli.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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({group: group_dict[group]})
  25. return x
  26. def roles() -> list:
  27. sorted_roles = sorted(list(get_inventory().keys()))
  28. if sys.stdin and sys.stdin.isatty():
  29. for role in sorted_roles:
  30. print(role)
  31. return sorted_roles
  32. def update(roles):
  33. if len(roles) == 1:
  34. roles = roles[0]
  35. else:
  36. roles = ",".join(roles)
  37. cmd = "ansible-playbook"
  38. limit = f"--limit={roles}"
  39. call_list = [cmd, DEFAULT_PLAYBOOK, "-i", DEFAULT_HOST_FILE, limit]
  40. print(call_list)
  41. if sys.stdin and sys.stdin.isatty():
  42. subprocess.run(call_list, cwd=DEFAULT_ANSIBLE_DIR)
  43. def newjail(jail_name) -> None:
  44. if len(jail_name) == 1:
  45. jail_name = jail_name[0]
  46. else:
  47. print("Requires a single new jail name")
  48. return
  49. call_list = [
  50. "ansible",
  51. "rhea",
  52. "-m",
  53. "ansible.builtin.shell",
  54. "-a",
  55. f'"newjail {jail_name}"',
  56. "--become",
  57. "-K",
  58. ]
  59. print(call_list)
  60. if sys.stdin and sys.stdin.isatty():
  61. subprocess.run(call_list, cwd=DEFAULT_ANSIBLE_DIR)
  62. def main():
  63. del sys.argv[0]
  64. if len(sys.argv) > 0:
  65. func = sys.argv.pop(0)
  66. args = sys.argv
  67. if args:
  68. return eval(func)(args)
  69. else:
  70. return eval(func)()
  71. if __name__ == "__main__":
  72. main()