美文网首页
Ansible2.0 python Api

Ansible2.0 python Api

作者: shu_ke | 来源:发表于2018-06-22 15:58 被阅读216次

Ansible2.0 python Api

Python 3.6.2 ansible 2.4.3.0

官方示例
注意: 默认官方示例中Ansbile的连接参数使用的是local,执行命令操作是在本地

示例修改后调用Ansible的模块执行远端命令:

#!/usr/bin/env python  
# -*- coding: UTF-8 -*-


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

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='smart', module_path=['/Users/zhao/anaconda3/lib/python3.6/site-packages/ansible'], forks=10, become=True, become_method='sudo', become_user='root', 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
# 此处的sources参数可以是hosts文件所在的目录,也可以是完整的文件路径,或者主机字符串,使用逗号分割
inventory = InventoryManager(loader=loader, sources='/Users/zhao/work/playbook/inventory')

# 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 = 'nginx-test',
        gather_facts = 'no',
        tasks = [
            dict(action=dict(module='shell', args='whoami'), register='shell_out'),
            dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
         ]
    )

# Create play object, playbook objects use .load instead of init or new methods,
# this will also automatically create the task objects from the info provided in play_source
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)

执行结果如下:

{
    "ngx-brazil-test01br-t001.gru1.wecash.net": {
        "changed": true,
        "end": "2018-06-20 10:59:36.486658",
        "stdout": "root",
        "cmd": "whoami",
        "rc": 0,
        "start": "2018-06-20 10:59:36.484856",
        "stderr": "",
        "delta": "0:00:00.001802",
        "invocation": {
            "module_args": {
                "warn": true,
                "executable": null,
                "_uses_shell": true,
                "_raw_params": "whoami",
                "removes": null,
                "creates": null,
                "chdir": null,
                "stdin": null
            }
        },
        "_ansible_parsed": true,
        "stdout_lines": [
            "root"
        ],
        "stderr_lines": [],
        "_ansible_no_log": false
    }
}
{
    "ngx-brazil-test01br-t001.gru1.wecash.net": {
        "msg": "root",
        "_ansible_verbose_always": true,
        "_ansible_no_log": false,
        "changed": false
    }
}

相关文章

网友评论

      本文标题:Ansible2.0 python Api

      本文链接:https://www.haomeiwen.com/subject/jwwkyftx.html