python3 ansible api 命令和playbook
一、api代码
# coding: utf-8
import os
import sys
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase #存放yml的目录
YML_DIR = '' class ansible_Runner(object):
"""
This is a General object for parallel execute modules.
""" def __init__(self, resource, *args, **kwargs):
self.resource = resource
self.inventory = None
self.variable_manager = None
self.loader = None
self.options = None
self.passwords = None
self.callback = None
self.__initializeData()
self.results_raw = {} def __initializeData(self):
"""
初始化ansible配置
"""
Options = namedtuple('Options',
['listtags', 'listtasks', 'listhosts', 'syntax', 'connection', 'module_path', 'forks',
'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check', 'diff']) self.loader = DataLoader()
self.options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh',
module_path=None, forks=100, remote_user='root', private_key_file=None,
ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None,
become=True, become_method='sudo', become_user='root', verbosity=None, check=False,
diff=False)
self.passwords = dict(vault_pass='secret')
self.inventory = InventoryManager(loader=self.loader, sources=self.resource)
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory) def run(self, host_list, module_name, module_args, ):
"""
run module from andible ad-hoc.
module_name: ansible module_name
module_args: ansible module args
"""
play_source = dict(
name="Ansible Ad-hoc Command",
hosts=host_list,
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=module_args))]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None
self.callback = ResultsCollector()
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback='default',
)
tqm._stdout_callback = self.callback
result = tqm.run(play)
# print self.callback
finally:
if tqm is not None:
tqm.cleanup() def run_playbook(self, playbook_name):
try:
self.callback = ResultsCollector()
playbook_file = [YML_DIR + playbook_name]
print(playbook_file)
# template_file = BASE_DIR + "roles/"+ role_name + "/templates"
if not os.path.exists(playbook_name):
print('%s 路径不存在 ' % playbook_file)
sys.exit()
executor = PlaybookExecutor(
playbooks=playbook_file, inventory=self.inventory, variable_manager=self.variable_manager,
loader=self.loader,options=self.options, passwords=self.passwords
)
executor._tqm._stdout_callback = self.callback
executor.run()
except Exception as e:
print("Failure in run_playbook:%s"%e)
pass def get_result(self):
self.results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
for host, result in self.callback.host_ok.items():
self.results_raw['success'][host] = result._result for host, result in self.callback.host_failed.items():
self.results_raw['failed'][host] = result._result for host, result in self.callback.host_unreachable.items():
self.results_raw['unreachable'][host] = result._result['msg'] return self.results_raw class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {} def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs):
self.host_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result
二、使用演示
1、执行模块与命令
[root@adminan]#cat test.py
from Ansible import *
ansible = ansible_Runner('/etc/ansible/hosts')
ansible.run('all', 'shell', "ping baidu.com -c 2 >/tmp/ping.txt")
print(ansible.get_result()) [root@adminan]#python3 test.py
{'success': {'10.0.0.141': {'changed': True, 'end': '2019-08-30 14:28:30.924988', 'stdout': '', 'cmd': 'ping baidu.com -c 2 >/tmp/ping.txt', 'rc': , 'start': '2019-08-30 14:28:29.835961', 'stderr': '', 'delta': '0:00:01.089027', 'invocation': {'module_args': {'creates': None, 'executable': None, '_uses_shell': True, '_raw_params': 'ping baidu.com -c 2 >/tmp/ping.txt', 'removes': None, 'argv': None, 'warn': True, 'chdir': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': [], 'stderr_lines': [], '_ansible_no_log': False}}, 'failed': {}, 'unreachable': {}} [root@adminan]#cat /tmp/ping.txt
PING baidu.com (220.181.38.148) () bytes of data.
bytes from 220.181.38.148 (220.181.38.148): icmp_seq= ttl= time=43.9 ms
bytes from 220.181.38.148 (220.181.38.148): icmp_seq= ttl= time=44.4 ms --- baidu.com ping statistics ---
packets transmitted, received, % packet loss, time 1001ms
rtt min/avg/max/mdev = 43.914/44.166/44.419/0.328 ms
2、playbook使用
[root@adminan]#cat test.yaml
- hosts: all
tasks:
- name: "test"
command: touch /tmp/test.txt [root@adminan]#cat test.py
from Ansible import *
ansible = ansible_Runner('/etc/ansible/hosts')
ansible.run_playbook("/root/an/test.yaml")
print(ansible.get_result()) [root@adminan]#python3 test.py
['/root/an/test.yaml']
{'success': {'10.0.0.141': {'changed': True, 'end': '2019-08-30 14:30:46.462422', 'stdout': '', 'cmd': ['touch', '/tmp/test.txt'], 'rc': , 'start': '2019-08-30 14:30:46.451079', 'stderr': '', 'delta': '0:00:00.011343', 'invocation': {'module_args': {'creates': None, 'executable': None, '_uses_shell': False, '_raw_params': 'touch /tmp/test.txt', 'removes': None, 'argv': None, 'warn': True, 'chdir': None, 'stdin': None}}, 'warnings': ["Consider using the file module with state=touch rather than running 'touch'. If you need to use command because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message."], '_ansible_parsed': True, 'stdout_lines': [], 'stderr_lines': [], '_ansible_no_log': False}}, 'failed': {}, 'unreachable': {}} [root@adminan]#ll /tmp/test.txt
-rw-r--r-- root root 8月 : /tmp/test.txt
python3 ansible api 命令和playbook的更多相关文章
- Python调用ansible API系列(五)综合使用
如何把动态生成资产信息.执行playbook以及自定义结果结合起来用呢? #!/usr/bin/env python # -*- coding: utf-8 -*- """ ...
- ansible Api 2.3-2.4
官网示例(python3) 说明: 在学习2.0 api的过程中遇到了一个坑,最新版的ansible(2.4)和2.3版本api引用时发生了变化,本文主要使用2.3 api进行操作,2.4只做分析 a ...
- Python调用ansible API系列(四)动态生成hosts文件
方法一:通过最原始的操作文件的方式 #!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过操作文件形式动态生成ansib ...
- ansible常用命令
一.ansible常用命令 一.ansible命令的常用参数 ansible 默认提供了很多模块来供我们使用.在 Linux 中,我们可以通过 ansible-doc -l 命令查看到当前 ansib ...
- 大话Ansible Ad-Hoc命令
Ansible是一个系列文章,我会尽量以通俗易懂.诙谐幽默的总结方式给大家呈现这些枯燥的知识点,让学习变的有趣一些. Ansible系列博文直达链接:Ansible入门系列 前言 通过前面的文章,大家 ...
- ansible api 调用出现ssh交互式输入
发现在删掉 ~/.ssh/know_hosts 之后运行 ansible api 会出现以下提示 The authenticity of host '10.1.*.* (10.1.*.*)' can' ...
- ansible API(开发应用)
7. ansible API(开发应用) 官网链接
- windows下使用pycharm开发基于ansible api的python程序
Window下python安装ansible,基于ansible api开发python程序 在windows下使用pycharm开发基于ansible api的python程序时,发现ansible ...
- Python调用ansible API系列(三)带有callback的执行adhoc和playbook
在第二篇文章中虽然可以执行adhoc和playbook但是执行结果的输出并不是特别直观,虽然没有报错但是到底什么结果其实你是不知道的尤其是在执行adhoc的时候,这时候我们要利用callback来设置 ...
随机推荐
- SpringCloud-Hystrix原理
Hystrix官网的原理介绍以及使用介绍非常详细,非常建议看一遍,地址见参考文档部分. 一 Hystrix原理 1 Hystrix能做什么 通过hystrix可以解决雪崩效应问题,它提供了资源隔离.降 ...
- Openstack之七:实现基于桥接的内外网络
一.在控制端进行配置网络 #启动实例文档:https://docs.openstack.org/ocata/zh_CN/install-guide-rdo/launch-instance.html# ...
- 树上对抗搜索 - 树形dp
Alice and Bob are going on a trip. Alice is a lazy girl who wants to minimize the total travelling d ...
- Linux初始化Git环境
第一步:设置Git全局用户名和邮箱 git config --global user.name "你的用户名" git config --global user.email &qu ...
- JS 头像显示
HTML <div class="form-group"> <label class="col-sm-3 control-label"> ...
- qt中的拖拽及其使用技巧
关于qt中的拖放操作,首先可以看这篇官方文档:http://doc.qt.io/qt-5.5/dnd.html 一.QDrag 首先是创建QDrag,可以在mousePressEvent或者mouse ...
- cmd 打开文件
打开cmd Python 文件地址
- ArrayList.subList方法使用总结
ArrayList.subList方法使用总结 示例 List<String> list=new ArrayList<>(); list.add("d"); ...
- HanLP《自然语言处理入门》笔记--2.词典分词
2. 词典分词 中文分词:指的是将一段文本拆分为一系列单词的过程,这些单词顺序拼接后等于原文本. 中文分词算法大致分为基于词典规则与基于机器学习这两大派. 2.1 什么是词 在基于词典的中文分词中,词 ...
- 性能优于JDK代理,CGLib如何实现动态代理
按照代理的创建时期,代理类可以分为两种. 静态代理:由程序员创建或特定工具自动生成源代码,再对其编译.在程序运行前,代理类的.class文件就已经存在了. 动态代理:在程序运行时,运用反射机制动态创建 ...