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

时间:2019-05-04 22:40:19

标签: python ansible

我刚开始使用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
    }
}


2 个答案:

答案 0 :(得分:1)

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

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

但是,您明确使用了local连接插件:

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)

在进行了此更改以及适用于我的环境的清单后,您提供的代码将按预期工作。

答案 1 :(得分:-1)