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来设置 ...
随机推荐
- Epplus Excel 导入 MSSQL 数据库
效果: 下载EXE 源码
- 函数组合的 N 种模式
随着以函数即服务(Function as a Service)为代表的无服务器计算(Serverless)的广泛使用,很多用户遇到了涉及多个函数的场景,需要组合多个函数来共同完成一个业务目标,这正是微 ...
- hdu 6567 Cotree 树的重心
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6567 #include<iostream> #include<algorithm&g ...
- 使用Robot Framework框架远程操作UNIX系统
bot Framework是一个强大的自动化测试框架,依靠社区力量编写的Test Library为它提供了非常强的扩展性.下面我将介绍的就是如何使用第三方提供的扩展测试库(Test Library)来 ...
- Jenkins-正则表达式提取Cookie
场景描述:用户登录查询数据:登录时响应头返回Cookie,将Cookie使用正则表达式提取出来,在下一个请求“查询数据”时,在请求头中使用此Cookie 1.添加“登录”http请求 2.在后置处理器 ...
- Scrapy的基本使用
爬取:http://quotes.toscrape.com 单页面 # -*- coding: utf-8 -*- import scrapy class QuoteSpider(scrapy.Spi ...
- auth.User.groups: (fields.E304) Reverse accessor for 'User.groups'
创建表,运行下面命令,出错 makemigrations 原因:继承auth_user 解决方案 在settings.py文件添加 AUTH_USER_MODEL = "app名称.类名&q ...
- [bzoj4568] [loj#2013] [Scoi2016] 幸运数字
Description \(A\) 国共有 \(n\) 座城市,这些城市由 \(n-1\) 条道路相连,使得任意两座城市可以互达,且路径唯一.每座城市都有一个幸运数字,以纪念碑的形式矗立在这座城市的正 ...
- 第二阶段冲刺个人任务——two
今日任务: 优化作业查询结果,按学号排列. 昨日成果: 修改注册界面.
- 「雅礼集训 2017 Day2」棋盘游戏
祝各位圣诞后快乐(逃) 题目传送门 分析: 首先棋盘上的路径构成的图是一张二分图 那么对于一个二分图,先求出最大匹配,先手如果走到关键匹配点,只要后手顺着匹配边走,由于不再会出现增广路径,所以走到最后 ...