gpt4 book ai didi

Python Ansible API 仅在控制节点中执行命令,不在远程节点中执行命令

转载 作者:行者123 更新时间:2023-12-01 07:55:50 25 4
gpt4 key购买 nike

我对使用 python ansible API 相当陌生,我已经使用了 Ansible API 文档中给出的示例代码。我正在尝试在多个节点上使用命令模块运行一个简单的命令“ls”,正如您可以从输出,看起来它没有完全在远程节点上执行命令,而是在我运行脚本的控制节点上执行它,请帮助我理解我在这里做错了什么。

剧本

#!/usr/bin/env python

import json
import shutil
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
import ansible.constants as C

#import pdb;pdb.set_trace()

class ResultCallback(CallbackBase):
"""A sample callback plugin used for performing an action as results come in

If you want to collect all results into a single object for processing at
the end of the execution, look into utilizing the ``json`` callback plugin
or writing your own custom callback plugin
"""
def v2_runner_on_ok(self, result, **kwargs):
"""Print a json representation of the result

This method could store the result in an instance attribute for retrieval later
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
# since API is constructed for CLI it expects certain options to always be set, named tuple 'fakes' the args parsing options object
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
options = Options(connection='local', module_path=['/to/mymodules'], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False)

# initialize needed objects
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
passwords = dict(vault_pass='secret')

# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
results_callback = ResultCallback()

# create inventory, use path to host config file as source or hosts in a comma separated string
inventory = InventoryManager(loader=loader, sources=['hosts_all'])

# variable manager takes care of merging all the different sources to give you a unifed view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)

# create datastructure that represents our play, including tasks, this is basically what our YAML loader does internally.
play_source = dict(
name = "Ansible Play",
hosts = 'navihosts',
gather_facts = 'no',
tasks = [
dict(action=dict(module='command', args='hostname'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)


play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

# Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
)
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
# we always need to cleanup child procs and the structres we use to communicate with them
if tqm is not None:
tqm.cleanup()

# Remove ansible tmpdir
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

库存文件

[navihosts]
server1.example.com
rabbitmq-2
diyvb2

输出


{
"server1.example.com": {
"_ansible_parsed": true,
"stderr_lines": [],
"changed": true,
"end": "2019-05-04 18:30:33.299643",
"_ansible_no_log": false,
"stdout": "server1.example.com",
"cmd": [
"hostname"
],
"start": "2019-05-04 18:30:33.282674",
"delta": "0:00:00.016969",
"stderr": "",
"rc": 0,
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": false,
"_raw_params": "hostname",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin": null
}
},
"stdout_lines": [
"server1.example.com"
]
}
}
{
"diyvb2": {
"_ansible_parsed": true,
"stderr_lines": [],
"changed": true,
"end": "2019-05-04 18:30:33.318774",
"_ansible_no_log": false,
"stdout": "server1.example.com",
"cmd": [
"hostname"
],
"start": "2019-05-04 18:30:33.257133",
"delta": "0:00:00.061641",
"stderr": "",
"rc": 0,
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": false,
"_raw_params": "hostname",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin": null
}
},
"stdout_lines": [
"server1.example.com"
]
}
}
{
"rabbitmq-2": {
"_ansible_parsed": true,
"stderr_lines": [],
"changed": true,
"end": "2019-05-04 18:30:33.337210",
"_ansible_no_log": false,
"stdout": "server1.example.com",
"cmd": [
"hostname"
],
"start": "2019-05-04 18:30:33.289134",
"delta": "0:00:00.048076",
"stderr": "",
"rc": 0,
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": false,
"_raw_params": "hostname",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin": null
}
},
"stdout_lines": [
"server1.example.com"
]
}
}
{
"server1.example.com": {
"msg": "server1.example.com",
"changed": false,
"_ansible_verbose_always": true,
"_ansible_no_log": false
}
}
{
"rabbitmq-2": {
"msg": "server1.example.com",
"changed": false,
"_ansible_verbose_always": true,
"_ansible_no_log": false
}
}
{
"diyvb2": {
"msg": "server1.example.com",
"changed": false,
"_ansible_verbose_always": true,
"_ansible_no_log": false
}
}


最佳答案

您正在远程主机上运行hostname命令:

dict(action=dict(module='command', args='hostname'), register='shell_out'),

但是,您明确使用本地连接插件:

options = Options(connection='local',
module_path=['/to/mymodules'],
forks=10,
become=None,
become_method=None,
become_user=None,
check=False,
diff=False)

这意味着 Ansible 将仅在本地运行所有内容,而不是连接到任何远程主机。这就是为什么在输出中您总是看到单个主机名:

    "stdout": "server1.example.com",
...
"stdout": "server1.example.com",
...
"stdout": "server1.example.com",

您可能想要设置connection='ssh':

options = Options(connection='local',
module_path=['/to/mymodules'],
forks=10,
become=None,
become_method=None,
become_user=None,
check=False,
diff=False)

通过这一更改以及适合我的环境的 list ,您提供的代码可以按预期工作。

关于Python Ansible API 仅在控制节点中执行命令,不在远程节点中执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com