def __init__( self, backend_parameters, config ): self.lockfile = '/tmp/.ansible-inventory_file_backend.lock' self.__lock = SimpleFlock('/tmp/.ansible-inventory_file_backend_main.lock', timeout=3) self.json_path = os.path.expanduser( backend_parameters['path'].strip('"\'') ) if not os.path.isabs( self.json_path ): self.json_path = os.path.join( config.config_home, self.json_path )
def __init__(self, backend_parameters, config): self.lockfile = '/tmp/.ansible-inventory_file_backend.lock' self.__lock = SimpleFlock( '/tmp/.ansible-inventory_file_backend_main.lock', timeout=3) self.json_path = os.path.expanduser( backend_parameters['path'].strip('"\'')) if not os.path.isabs(self.json_path): self.json_path = os.path.join(config.config_home, self.json_path) if 'pretty' in backend_parameters and backend_parameters[ 'pretty'].lower() in ("true", "1", "yes", "on"): self.pretty = True else: self.pretty = False
def load_inventory(self): "Returns a dictionary with the inventory contents as required by Inventory class" if os.path.exists( self.json_path ): with SimpleFlock( self.lockfile, timeout=3 ): with open( self.json_path ) as inv_file: return json.loads( inv_file.read() ) else: return {}
class AnsibleInventory_FileBackend(AnsibleInventory_Backend): "Backend class for ansible-inventory that uses a json file for storage" def __init__(self, backend_parameters, config): self.lockfile = '/tmp/.ansible-inventory_file_backend.lock' self.__lock = SimpleFlock( '/tmp/.ansible-inventory_file_backend_main.lock', timeout=3) self.json_path = os.path.expanduser( backend_parameters['path'].strip('"\'')) if not os.path.isabs(self.json_path): self.json_path = os.path.join(config.config_home, self.json_path) if 'pretty' in backend_parameters and backend_parameters[ 'pretty'].lower() in ("true", "1", "yes", "on"): self.pretty = True else: self.pretty = False def load_inventory(self): "Returns a dictionary with the inventory contents as required by Inventory class" if os.path.exists(self.json_path): with SimpleFlock(self.lockfile, timeout=3): with open(self.json_path) as inv_file: return json.loads(inv_file.read()) else: return {} def save_inventory(self, inventory): "Saves the inventory from a dictionary with the inventory contents from the Inventory class" with SimpleFlock(self.lockfile, timeout=3): with open(self.json_path, 'w') as inv_file: if self.pretty: inv_file.write( json.dumps(inventory, sort_keys=True, indent=4)) else: inv_file.write(json.dumps(inventory)) def lock(self): "Locks the backend for reading and writting" self.__lock.__enter__() def unlock(self): "Unlocks the backend" self.__lock.__exit__()
def save_inventory(self, inventory): "Saves the inventory from a dictionary with the inventory contents from the Inventory class" with SimpleFlock(self.lockfile, timeout=3): with open(self.json_path, 'w') as inv_file: if self.pretty: inv_file.write( json.dumps(inventory, sort_keys=True, indent=4)) else: inv_file.write(json.dumps(inventory))