本文整理汇总了Python中ansible.inventory.Inventory方法的典型用法代码示例。如果您正苦于以下问题:Python inventory.Inventory方法的具体用法?Python inventory.Inventory怎么用?Python inventory.Inventory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.inventory
的用法示例。
在下文中一共展示了inventory.Inventory方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_play_prereqs_2
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def get_play_prereqs_2(self, options):
loader = DataLoader()
if self.vault_pass:
loader.set_vault_password(self.vault_pass)
variable_manager = VariableManager()
variable_manager.extra_vars = self.extra_vars
variable_manager.options_vars = {'ansible_version': self.version_info(ansible_version)}
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=options.inventory)
variable_manager.set_inventory(inventory)
# let inventory know which playbooks are using so it can know the
# basedirs
inventory.set_playbook_basedir(os.path.dirname(self.playbook_file))
return loader, inventory, variable_manager
示例2: __init__
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def __init__(self, host_list, module_name, args, private_key_file="/root/.ssh/id_rsa", forks=5, extra_vars=None):
super(AnsibleAdhcTask, self).__init__(host_list, private_key_file, forks, extra_vars)
self.call_back = result_collector.CallbackModule()
# create inventory and pass to var manager
inventory = Inventory(loader=self.loader,
variable_manager=self.variable_manager,
host_list=host_list)
self.variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name="Ansible Play",
hosts='all',
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=args))]
)
self.play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
示例3: adduser
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def adduser(ips, users):
inventory ="""
{% for i in hosts -%}
{{ i }}
{% endfor %}
"""
inventory_template = jinja2.Template(inventory)
rendered_inventory = inventory_template.render({'hosts': ips})
hosts = NamedTemporaryFile(delete=False,suffix='tmp',dir='/tmp/ansible/')
hosts.write(rendered_inventory)
hosts.close()
inventory = Inventory(hosts.name)
stats = callbacks.AggregateStats()
playbook_cb =callbacks.PlaybookCallbacks()
runner_cb =callbacks.PlaybookRunnerCallbacks(stats)
vars={}
vars['users'] = users
results = PlayBook(playbook='user.yaml',callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars)
res = results.run()
logs = []
logs.append("finish playbook\n")
logs.append(str(res))
return logs
示例4: __init__
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def __init__(self, resource):
"""
resource的数据格式是一个列表字典,比如
{
"group1": {
"hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...],
"vars": {"var1": value1, "var2": value2, ...}
}
}
如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如
[{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...]
"""
self.resource = resource
self.inventory = Inventory(host_list=[])
self.gen_inventory()
示例5: Playbook
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def Playbook():
vars={}
inventory = Inventory(hostfile)
stats = callbacks.AggregateStats()
playbook_cb =callbacks.PlaybookCallbacks()
runner_cb =callbacks.PlaybookRunnerCallbacks(stats)
hosts=request.args.get('ip')
task=request.args.get('playbook')
vars['hosts'] = hosts
play=task + '.yml'
results = PlayBook(playbook=play,callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars)
res = results.run()
return json.dumps(res,indent=4)
示例6: initialize_inventory
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def initialize_inventory(self):
log.debug("HostManagerV2.initialize_inventory()")
self.options['loader'] = DataLoader()
self.options['variable_manager'] = VariableManager()
self.options['inventory_manager'] = Inventory(loader=self.options['loader'],
variable_manager=self.options['variable_manager'],
host_list=self.options['inventory'])
self.options['variable_manager'].set_inventory(self.options['inventory_manager'])
示例7: initialize_inventory
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def initialize_inventory(self):
self.options['inventory_manager'] = Inventory(self.options['inventory'])
# self.options['inventory_manager'].subset(self.pattern)
示例8: get_inventory
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def get_inventory(inventory_path=None, vault_password_path=None):
if inventory_path is None:
try:
inventory_path = os.path.expanduser(
config.get('inventory', 'path'))
except ConfigParser.NoSectionError:
inventory_path = 'inventory'
vault_password = get_vault_password(vault_password_path)
return Inventory(inventory_path, vault_password=vault_password)
# Filesystem Tools
示例9: __init__
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def __init__(self, playbook, inventory, run_data=None, verbosity=0, tags=None, skip_tags=None):
self.run_data = run_data or {}
self.options = Options()
self.options.verbosity = verbosity
self.options.connection = 'local' # Need a connection type "smart" or "ssh"
self.options.become = True
self.options.become_method = 'sudo'
self.options.become_user = 'root'
self.options.tags = tags or []
self.options.skip_tags = skip_tags or []
# Set global verbosity
self.display = Display()
self.display.verbosity = self.options.verbosity
# Executor appears to have it's own
# verbosity object/setting as well
playbook_executor.verbosity = self.options.verbosity
# Become Pass Needed if not logging in as user root
passwords = {}
# Gets data from YAML/JSON files
self.loader = DataLoader()
self.loader.set_vault_password(os.environ.get('VAULT_PASS',''))
# All the variables from all the various places
self.variable_manager = VariableManager()
self.variable_manager.extra_vars = self.run_data
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=inventory)
self.variable_manager.set_inventory(self.inventory)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
示例10: execute_action
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def execute_action(self, action, args):
"""
Execute the requested operation
"""
C.DEFAULT_ROLES_PATH = [os.path.join(ROLESDIR, str(action))]
i3xfce.loggers.ROOTLOGGER.debug("Executing the %s action", action)
# Get the real user behind the sudo
username = os.getenv("SUDO_USER")
if username is None:
i3xfce.loggers.ROOTLOGGER.debug("Unable to get SUDO_USER environment variable. This means i3-xfce has not been \
started using sudo")
raise Exception("This program must be ran using sudo ")
i3xfce.loggers.ROOTLOGGER.debug("Creating the option tuple")
options_tuple = namedtuple('Options', ['connection', 'forks', 'module_path', 'become_user', 'become',
'become_method', 'check', 'verbosity'])
try:
# initialize needed objects
variable_manager = VariableManager()
variable_manager.extra_vars = dict(action=str(action),
remote_user=username)
loader = DataLoader()
i3xfce.loggers.ROOTLOGGER.debug("Creating option to count number of tasks to execute")
options = options_tuple(connection=None, module_path=None, forks=1, become_user=None,
become=None, become_method=None, verbosity=0, check=True)
tasks_count_callback = TaskCountCallback()
# create inventory and pass to var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=None)
variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name="Ansible Play",
hosts='localhost',
gather_facts='no',
ignore_errors="yes",
roles=args.parts
)
CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, tasks_count_callback)
i3xfce.loggers.ROOTLOGGER.debug("%i tasks are going to be executed", tasks_count_callback.get_total_tasks_num())
play_source["ignore_errors"] = "no"
options = options_tuple(connection=None, module_path=None, forks=1, become_user=None, become=None,
become_method=None, verbosity=0, check=args.dryrun)
self._results_callback = PlaybookExecutionCallback(tasks_count_callback.get_total_tasks_num(),
tasks_count_callback.get_task_name_max_len())
CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, self._results_callback)
self._results_callback.get_progress_bar().stop()
self._results_callback.get_progress_bar().join()
if self._results_callback.get_task_failed() is True:
raise TaskExecutionException("")
except TaskExecutionException as exc:
raise
except Exception as exc:
raise TaskExecutionException(str(exc))
示例11: run_module
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def run_module(self, module_name='ping', module_args=None, hosts="all",
inventory_file=None, **kwargs):
if not module_args:
check_raw = module_name in ('command', 'win_command', 'shell',
'win_shell', 'script', 'raw')
module_args = parse_kv(constants.DEFAULT_MODULE_ARGS, check_raw)
conn_pass = None
if 'conn_pass' in kwargs:
conn_pass = kwargs['conn_pass']
become_pass = None
if 'become_pass' in kwargs:
become_pass = kwargs['become_pass']
passwords = {'conn_pass': conn_pass, 'become_pass': become_pass}
options = self._build_opt_dict(inventory_file, **kwargs)
variable_manager = vars.VariableManager()
loader = dataloader.DataLoader()
variable_manager.extra_vars = options.extra_vars
ansible_inv = inventory.Inventory(loader=loader,
variable_manager=variable_manager,
host_list=options.inventory)
variable_manager.set_inventory(ansible_inv)
ansible_inv.subset(options.subset)
play_ds = self._play_ds(hosts, module_name, module_args)
play_obj = play.Play().load(play_ds, variable_manager=variable_manager,
loader=loader)
try:
tqm = task_queue_manager.TaskQueueManager(
inventory=ansible_inv,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback='minimal',
run_additional_callbacks=True
)
# There is no public API for adding callbacks, hence we use a
# private property to add callbacks
tqm._callback_plugins.extend(self._callbacks)
result = tqm.run(play_obj)
finally:
if tqm:
tqm.cleanup()
if loader:
loader.cleanup_all_tmp_files()
stats = tqm._stats
result = self._process_stats(stats)
return result
示例12: __init__
# 需要导入模块: from ansible import inventory [as 别名]
# 或者: from ansible.inventory import Inventory [as 别名]
def __init__(self, playbook, hosts='hosts', options={}, passwords={}, vault_pass=None):
# Set options
self.options = Options()
for k, v in options.iteritems():
setattr(self.options, k, v)
# Set global verbosity
self.display = display
self.display.verbosity = self.options.verbosity
# Executor has its own verbosity setting
playbook_executor.verbosity = self.options.verbosity
# Gets data from YAML/JSON files
self.loader = DataLoader()
# Set vault password
if vault_pass is not None:
self.loader.set_vault_password(vault_pass)
elif 'VAULT_PASS' in os.environ:
self.loader.set_vault_password(os.environ['VAULT_PASS'])
# All the variables from all the various places
self.variable_manager = VariableManager()
if self.options.python_interpreter is not None:
self.variable_manager.extra_vars = {
'ansible_python_interpreter': self.options.python_interpreter
}
# Set inventory, using most of above objects
self.inventory = Inventory( loader=self.loader,
variable_manager=self.variable_manager,
host_list=hosts)
if len(self.inventory.list_hosts()) == 0:
# Empty inventory
self.display.error("Provided hosts list is empty.")
sys.exit(1)
self.inventory.subset(self.options.subset)
if len(self.inventory.list_hosts()) == 0:
# Invalid limit
self.display.error("Specified limit does not match any hosts.")
sys.exit(1)
self.variable_manager.set_inventory(self.inventory)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)