ansible api 实现本地、动态加载Inventory
支持ad_hoc 执行,本地playbook执行
import shutil
import json
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager
from ansible.utils.path import unfrackpath
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible import context
from optparse import Values
from multiprocessing import cpu_count
import time
class Inventory_var:
class My_InventoryManager(InventoryManager):
def parse_sources(self, cache=False):
parsed = False
for source in self._sources:
if source:
if ',' not in source:
source = unfrackpath(source, follow=False)
parse = self.parse_source(source, cache=cache)
if parse and not parsed:
parsed = True
if parsed:
self._inventory.reconcile_inventory()
else:
if C.INVENTORY_UNPARSED_IS_FAILED:
raise AnsibleError("No inventory was parsed, please check your configuration and options.")
def __init__(self, loader,):
self.loader = loader
self.inventory = self.My_InventoryManager(loader=self.loader, sources=None)
def local_inventory(self, local_resource):
self.inventory = InventoryManager(loader=self.loader, sources=local_resource)
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)
return self
def __add_dynamic_inventory(self, hosts, groupname, ):
self.inventory.add_group(group=groupname)
for host in hosts:
ip = host.get("ip")
hostport = host.get("port")
self.inventory.add_host(host=ip, group=groupname, port=hostport)
self.inventory.add_host(host=ip, group='all', port=hostport)
def __set_variable(self, hosts,):
for host in hosts:
my_host = self.inventory.get_host(hostname=host.get("ip"))
hostname = host.get("hostname")
self.variable_manager.set_host_variable(host=my_host,varname='ansible_ssh_host',value= host.get('ip', hostname))
self.variable_manager.set_host_variable(host=my_host, varname='ansible_ssh_port', value=host.get("port"))
self.variable_manager.set_host_variable(host=my_host, varname='ansible_ssh_user', value=host.get("username"))
self.variable_manager.set_host_variable(host=my_host, varname='ansible_ssh_pass', value=host.get("password"))
self.variable_manager.set_host_variable(host=my_host, varname='ansible_ssh_private_key_file', value= host.get("ssh_key"))
for key, value in host.items():
if key not in ["hostname", "port", "username", "password"]:
self.variable_manager