/ ansible / callback_plugins / vault_cache.py
vault_cache.py
 1  import os
 2  
 3  from ansible.plugins.callback import CallbackBase
 4  from ansible.utils.display import Display
 5  
 6  display = Display()
 7  
 8  class CallbackModule(CallbackBase):
 9      CALLBACK_VERSION = 2.0
10      CALLBACK_TYPE = 'aggregate'
11      CALLBACK_NAME = 'cache_cleanup'
12  
13      def __init__(self):
14          super(CallbackModule, self).__init__()
15          self.cache_dir = "./ansible/files/cache/vault"
16          self.cache_file = f"{self.cache_dir}/{os.getpid()}.cache"
17          self._create_cache_dir()
18  
19      def _create_cache_dir(self):
20          """Creates the cache dir if it doesn't exist."""
21          try:
22              if not os.path.exists(self.cache_dir):
23                  os.makedirs(self.cache_dir)
24                  display.v(f"Created cache directory: {self.cache_dir}")
25          except Exception as e:
26              display.error(f"Failed to create cache dir: {e}")
27  
28      def v2_playbook_on_stats(self, stats):
29          """Called when the playbook ends, deletes all files in the cache directory."""
30          try:
31              if os.path.exists(self.cache_dir):
32                  for filename in os.listdir(self.cache_dir):
33                      file_path = os.path.join(self.cache_dir, filename)
34                      try:
35                          os.remove(file_path)
36                          display.v(f"Deleted cache file: {file_path}")
37                      except Exception as e:
38                          display.error(f"Failed to delete {file_path}: {e}")
39          except Exception as e:
40              display.error(f"Failed to clean up cache directory: {e}")