ansible支持python版本_Python3 调用 Ansible2.x API

本文介绍了如何使用 Python3 调用 Ansible2.x API,包括安装、示例代码解析及二次开发指导。通过示例展示了如何执行 Ad-hoc 命令和 playbook,并提供了自定义回调插件以获取更详细的执行结果。
摘要由CSDN通过智能技术生成

一、安装方式

建议使用 pip3 install ansible 的方式安装,便于导入模块

这种安装方式,配置文件不会在 /etc 下产生。将会在下面的路径下: ``` /usr/local/lib/python3.7/site-packages/ansible/galaxy/data/container/tests

```

二、 先从官方示例入手注意:下面的所以开发,都是以 2.8 版本为例的。2.7 和 2.8 版本有一些差异: 2.7 使用了 Python 标准库里的 命名元组来初始化选项,而 2.8 是 Ansible 自己封装了一个 ImmutableDict ,之后需要和 context 结合使用的。两者不能互相兼容。 点击 2.7 官方示例

#!/usr/bin/env python3

import json

import shutil

from ansible.module_utils.common.collections import ImmutableDict

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

from ansible import context

import ansible.constants as C

class ResultCallback(CallbackBase):

"""A sample callback plugin used for performing an action as results come inIf you want to collect all results into a single object for processing atthe end of the execution, look into utilizing the ``json`` callback pluginor writing your own custom callback plugin"""

def v2_runner_on_ok(self, result, **kwargs):

"""Print a json representation of the resultThis 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 the API is constructed for CLI it expects certain options to always be set in the context object

context.CLIARGS = ImmutableDict(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='localhost,')

# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context

variable_manager = VariableManager(loader=loader, inventory=inventory)

# create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.

play_source = dict(

name = "Ansible Play",

hosts = 'localhost',

gather_facts = 'no',

tasks = [

dict(action=dict(module='shell', args='ls'), 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,

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 structures we use to communicate with them

if tqm is not None:

tqm.cleanup()

# Remove ansible tmpdir

shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

下面是把官方的示例分解开了

1. 首先是需要导入的模块

import json

import shutil

from ansible.module_utils.common.collections import ImmutableDict

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

from ansible import context

import ansible.constants as C

核心类介绍

| 导入类完整路径 | 功能用途 | | ------------------------------------------------------------ | ------------------------------------------------------- | | from ansible.module_utils.common.collections import ImmutableDict | 用于添加选项。比如: 指定远程用户remote_user=None | | from ansible.parsing.dataloader import Dat

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值