class AnsibleEnvironment(): _cache = {} def __init__(self): ansible_basedir = os.path.join( os.environ.get("PROJECT_ENVIRONMENT_FILES_PATH"), "ansible") loader = CustomLoader() loader.set_basedir(ansible_basedir) var_manager = VariableManager() # load the inventory, set the basic playbook directory self._inventory = Inventory(loader=loader, variable_manager=var_manager) self._inventory.set_playbook_basedir(ansible_basedir) group = self._inventory.get_group("all") # make sure we load all magic variables on top of the global variables self._vars = combine_vars( self._inventory.get_group_vars(group, return_results=True), var_manager._get_magic_variables(loader, False, None, None, False, False)) self._vars['groups'] = self._inventory.get_group_dict() self._vars['env'] = os.environ hostvars = {} for host in self._inventory.get_hosts(): hostvars[host.name] = host.get_vars() self._vars['hostvars'] = hostvars # create the template renderer self._templar = Templar(loader=loader, variables=self._vars) # setup some easy variables that we use a lot self._vars['control_ip'] = self.get_var( "hostvars[groups['control'][0]]['ansible_host']") self._vars['edge_ip'] = self.get_var( "hostvars[groups['edge'][0]]['ansible_host']") self._vars['monitor_ip'] = self.get_var( "hostvars[groups['monitor'][0]]['ansible_host']") def get_var(self, name, cache=True): if name not in self._cache or not cache: try: self._cache[name] = self._templar.template("{{%s}}" % name) except AnsibleUndefinedVariable: self._cache[name] = None return self._cache.get(name) def set_var(self, name, value): self._vars[name] = value def template(self, *templates): return '\n'.join([self._templar.template(tpl) for tpl in templates])
def _main(): global tab_size parser = argparse.ArgumentParser( description="Convert the Ansible inventory from INI to yML format", ) parser.add_argument("-i", dest="inventory_file", help="Inform the Ansible Vault Password", required=True) parser.add_argument( "-d", dest="dest_inventory_path", help= "Destination to save the inventory files (Default will be on $PWD)", required=False) parser.add_argument( "-g", dest="group", help="Filter by specific GROUP", ) parser.add_argument( "-p", dest="vault_password", help="Inform the Ansible Vault Password or file with password", ) parser.add_argument( "-t", dest="tab_size", type=int, help="Number of tab spaces", default=4, ) args = parser.parse_args() tab_size = args.tab_size try: # Ansible: initialize needed objects variable_manager = VariableManager() loader = DataLoader() if args.vault_password: if os.path.isfile(args.vault_password): with open(args.vault_password, "r") as f: args.vault_password = f.readlines()[0].rstrip() f.close() print("** Passing Vault Password: '******'") % (args.vault_password) loader.set_vault_password(args.vault_password) # Ansible: Load inventory inventory = Inventory( loader=loader, variable_manager=variable_manager, host_list=args.inventory_file, ) except Exception as e: print("** ERROR: Missing the '--vault-password'??\n %s\n") % str(e) sys.exit(-1) try: groups = {} if args.group: _group = inventory.get_group(args.group) if not _group: print("** ERROR: No such group '%s' in inventory file '%s', exiting.") % \ (args.group, args.inventory_file) sys.exit(-1) groups[args.group] = _group else: groups = inventory.get_groups() for group in groups: if group == "all": continue # start the file output = "" output += "###################################################################################################\n" output += ("# Converted from '%s[%s]'\n") % (args.inventory_file, group) output += "###################################################################################################\n" output += ("%s:\n") % group group_ref = inventory.get_group(group) # children or hosts? if group_ref.child_groups: output += ident_as_usual(1, "children") for group_name in sorted(group_ref.child_groups): output += ident_as_usual(2, group_name.get_name()) else: group_ips = group_ref.hosts if not group_ips: continue output += "" output += ident_as_usual(1, "hosts") for group_ip in sorted(group_ips): if filter_vars(group_ip): continue output += ident_as_usual(2, group_ip.get_name()) _ip_host_vars = inventory.get_host_vars( group_ip, return_results=True) # group_vars/$group _ip_vars = inventory.get_vars( to_native(group_ip)) # host key1=var1 group_ip_vars = dict(_ip_host_vars.items() + _ip_vars.items()) if not group_ip_vars: continue for k, v in group_ip_vars.items(): if filter_vars(k): continue output += ident_as_the_key(3, k, v) # group_vars/$service output += "\n" output += ident_as_usual(1, "vars") group_vars = inventory.get_group_vars(group_ref, return_results=True) if group_vars: for k, v in sorted(group_vars.items()): if filter_vars(k): continue output += ident_as_the_key(2, k, v) output += "\n" output += ("# End for %s\n") % group if not args.dest_inventory_path: print(output) else: dest = args.dest_inventory_path + "/" + group + ".yml" print("Generating " + dest) try: dest_dir = os.path.dirname(dest) os.makedirs(dest_dir) except OSError as e: if e.errno != errno.EEXIST: raise f = file(dest, "w+") f.write(output) f.close() # Should save the 'group_vars/all' ? src = "group_vars/all" if args.dest_inventory_path and os.path.isfile(src): dest = args.dest_inventory_path + "/" + src print("Copying '%s' to '%s'") % (src, dest) try: dest_dir = os.path.dirname(dest) os.makedirs(dest_dir) except OSError as e: if e.errno != errno.EEXIST: raise shutil.copyfile(src, dest) except Exception as e: print("** ERROR: %s\n") % str(e) traceback.print_exc()