def add_var_to_groups(self, v_name, raw_value, g_regex): 'Adds a variable a to groups matching g_regex' self.next_from_cache() matching_groups = self.list_groups(g_regex) if not matching_groups: raise AnsibleInventory_Exception('No group matches your selection') v_value = self.__parse_var(raw_value) exist_in = [] for g in matching_groups: if isinstance(self.I[g], list): hosts = self.I[g] self.I[g] = {'hosts': hosts, 'vars': {}, 'children': []} elif isinstance(self.I[g], dict) and 'vars' not in self.I[g]: self.I[g]['vars'] = {} if v_name not in self.I[g]['vars']: self.I[g]['vars'][v_name] = v_value else: exist_in.append(g) if exist_in: str_list = '%s ' * exist_in.__len__() raise AnsibleInventory_Exception( 'Var %s already exist in these groups: ' + str_list, targets=(v_name, ) + tuple(exist_in))
def rename_group(self, g_name, new_name): 'Renames a group' if new_name in self.I: raise AnsibleInventory_Exception('Group %s already exists', new_name) if g_name not in self.I: raise AnsibleInventory_Exception('Group %s does not exist', g_name) g_data = self.I.pop(g_name) self.I[new_name] = g_data
def wrapper(self, *kargs, **kwargs): try: if self.__from_cache: self.__from_cache = False self.reload() return f(self, *kargs, **kwargs) except Exception as e: raise AnsibleInventory_Exception(e.__str__())
def change_host(self, h_name, h_host=None, h_port=None): 'Changes the host address or port of a host' self.next_from_cache() if h_name not in self.list_hosts(): raise AnsibleInventory_Exception('Host %s does not exist', h_name) if h_host: self.__set_host_host(h_name, h_host) if h_port: self.__set_host_port(h_name, h_port)
def remove_group(self, g_name, from_groups=[]): 'Removes the selected group. If from_groups is provided, the group will only removed from those groups.' if from_groups: for g in from_groups: g_child = self.__get_group_children(g) if g_name in g_child: g_child.remove(g_name) else: if g_name == 'all': raise AnsibleInventory_Exception('Group %s cannot be removed', 'all') for g in self.I: g_child = self.__get_group_children(g) if g_name in g_child: g_child.remove(g_name) if g_name in self.I: self.I.pop(g_name) else: raise AnsibleInventory_Exception('Group %s does not exist.', g_name)
def rename_host(self, h_name, new_name): 'Renames a host' self.next_from_cache() hosts = self.list_hosts() if new_name in hosts: raise AnsibleInventory_Exception('Host %s already exists', new_name) if h_name not in hosts: raise AnsibleInventory_Exception('Host %s does not exist', h_name) if h_name in self.I['_meta']['hostvars']: hvars = self.I['_meta']['hostvars'].pop(h_name) self.I['_meta']['hostvars'][new_name] = hvars for g in self.__get_host_groups(h_name): if isinstance(self.I[g], list): self.I[g].remove(h_name) self.I[g].append(new_name) elif isinstance(self.I[g], dict): self.I[g]['hosts'].remove(h_name) self.I[g]['hosts'].append(new_name)
def add_var_to_hosts(self, v_name, raw_value, h_regex): 'Adds a variable to hosts matching h_regex' self.next_from_cache() matching_hosts = self.list_hosts(h_regex) if not matching_hosts: raise AnsibleInventory_Exception('No host matches your selection') v_value = self.__parse_var(raw_value) exist_in = [] for h in matching_hosts: if h not in self.I['_meta']['hostvars']: self.I['_meta']['hostvars'][h] = {v_name: v_value} elif v_name not in self.I['_meta']['hostvars'][h]: self.I['_meta']['hostvars'][h][v_name] = v_value else: exist_in.append(h) if exist_in: str_list = '%s ' * exist_in.__len__() raise AnsibleInventory_Exception( 'Var %s already exist in these hosts: ' + str_list, targets=(v_name, ) + tuple(exist_in))
def add_group_to_groups(self, group, g_regex): 'Adds a single group to groups matching g_regex' self.next_from_cache() if group not in self.list_groups(): raise AnsibleInventory_Exception('Group %s does not exist', targets=group) self.next_from_cache() matching_groups = self.list_groups(g_regex) if not matching_groups: raise AnsibleInventory_Exception('No group matches your selection') for g in matching_groups: if isinstance(self.I[g], list): hosts = self.I[g] self.I[g] = {'hosts': hosts, 'vars': {}, 'children': []} elif isinstance(self.I[g], dict) and 'children' not in self.I[g]: self.I[g]['children'] = [] if group not in self.I[g]['children']: self.I[g]['children'].append(group)
def add_host(self, h_name, h_host=None, h_port=None): 'Adds a host' self.next_from_cache() if h_name in self.list_hosts(): raise AnsibleInventory_Exception('Host %s already exists', h_name) else: self.I['all']['hosts'].append(h_name) self.I['_meta']['hostvars'][h_name] = {} if h_host: self.__set_host_host(h_name, h_host) if h_port: self.__set_host_port(h_name, h_port)
def add_hosts_to_groups(self, h_regex, g_regex_list): 'Adds a hosts matching h_regex to groups matching g_regex from a list' self.next_from_cache() matching_hosts = self.list_hosts(h_regex) if not matching_hosts: raise AnsibleInventory_Exception('No host matches your selection') matching_groups = [] for g_regex in g_regex_list: self.next_from_cache() matching_groups += self.list_groups(g_regex) if not matching_groups: raise AnsibleInventory_Exception('No group matches your selection') for h_name in matching_hosts: for g_name in matching_groups: if isinstance(self.I[g_name], list): if h_name not in self.I[g_name]: self.I[g_name].append(h_name) elif isinstance(self.I[g_name], dict): if h_name not in self.I[g_name]['hosts']: self.I[g_name]['hosts'].append(h_name)
def wrapper(self, *args, **kwargs): try: self.backend.lock() self.reload() r = f(self, *args, **kwargs) self.save() return r except BlockingIOError: raise AnsibleInventory_Exception( "Backend temporally unavailable. Please try again.") except AnsibleInventory_Exception: raise finally: self.backend.unlock()
def __init__(self, ai_exec_file): # check if we are using a symlinked instance if os.path.islink(ai_exec_file): # We do this here and not in __main__ so we keep # the same behaviour even if this is used as a module self.config_home = os.path.join( os.path.dirname(os.path.abspath(ai_exec_file)), '.ansible') else: self.config_home = os.path.join(os.environ['HOME'], '.ansible') # define basic options self.config_file = os.path.join(self.config_home, 'ansible-inventory.cfg') self.history_file = os.path.join(self.config_home, 'ansible-inventory_history') # check configuration requirements self.__check_requirements() # read configuration self.__config = configparser.ConfigParser() self.__config.read(self.config_file) # option declarations (for clarity) self.use_colors = True self.backend = { 'class': AnsibleInventory_FileBackend, 'parameters': {} } # Parse configuration self.use_colors = self.__config['global'].getboolean('use_colors') backend_id = self.__config['global']['backend'].lower() if backend_id in self.available_backends: self.backend['class'] = self.available_backends[backend_id] self.backend['parameters'] = self.__config[backend_id + '_backend'] else: raise AnsibleInventory_Exception("No valid backend found")
def unlock( self ): raise AnsibleInventory_Exception( "backend.unlock: Not implemented" )
def save_inventory( self ): raise AnsibleInventory_Exception( "backend.save_inventory: Not implemented" )
def add_group(self, group): 'Adds a group' if group not in self.I: self.I[group] = {'hosts': [], 'vars': {}, 'children': []} else: raise AnsibleInventory_Exception('Group %s already exists', group)