ansible_utils.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import os
  2. from pathlib import Path
  3. from benedict import benedict
  4. from rich.pretty import pprint
  5. from ansible_runner import Runner, RunnerConfig
  6. GLOBAL_CACHE = {}
  7. def run_playbook(playbook_path, data_dir, quiet=False, **kwargs):
  8. ANSIBLE_TMP_DIR = str(Path(data_dir) / "tmp" / "ansible")
  9. os.environ['ANSIBLE_INVENTORY_UNPARSED_WARNING'] = 'False'
  10. os.environ['ANSIBLE_LOCALHOST_WARNING'] = 'False'
  11. os.environ["ANSIBLE_HOME"] = ANSIBLE_TMP_DIR
  12. # os.environ["ANSIBLE_COLLECTIONS_PATH"] = str(Path(data_dir).parent / 'archivebox')
  13. os.environ["ANSIBLE_ROLES_PATH"] = (
  14. '/Volumes/NVME/Users/squash/Code/archiveboxes/archivebox7/archivebox/builtin_plugins/ansible/roles'
  15. )
  16. rc = RunnerConfig(
  17. private_data_dir=ANSIBLE_TMP_DIR,
  18. playbook=str(playbook_path),
  19. rotate_artifacts=50000,
  20. host_pattern="localhost",
  21. extravars={
  22. "DATA_DIR": str(data_dir),
  23. **kwargs,
  24. },
  25. quiet=quiet,
  26. )
  27. rc.prepare()
  28. r = Runner(config=rc)
  29. r.set_fact_cache('localhost', GLOBAL_CACHE)
  30. r.run()
  31. last_run_facts = r.get_fact_cache('localhost')
  32. GLOBAL_CACHE.update(filtered_facts(last_run_facts))
  33. return benedict({
  34. key: val
  35. for key, val in last_run_facts.items()
  36. if not (key.startswith('ansible_') or key in ('gather_subset', 'module_setup'))
  37. })
  38. def filtered_facts(facts):
  39. return benedict({
  40. key: val
  41. for key, val in facts.items()
  42. if not (key.startswith('ansible_') or key in ('gather_subset', 'module_setup'))
  43. })
  44. def print_globals():
  45. pprint(filtered_facts(GLOBAL_CACHE), expand_all=True)
  46. # YTDLP_OUTPUT = run_playbook('extract.yml', {'url': 'https://www.youtube.com/watch?v=cK4REjqGc9w&t=27s'})
  47. # pprint(YTDLP_OUTPUT)