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来设置 ...
随机推荐
- nginx服务无法停止(Windows)
本人一般停止nginx服务都是通过Windows自带的任务管理器来强制结束nginx进程实现的,如图 2.但是 这次我通过同样的方法来结束nginx服务,发现nginx的进程无法结束 3.首先我要 ...
- vue学习笔记2:藕断丝连的 v-show 和 v-if
一.知识点 vue指令 v-show v-if 二.代码案例 v-show <div v-show="isShow">动态显示或隐藏</div> <! ...
- angular 构建可以动态挂载的配置服务
angular 构建可以动态挂载的配置服务 Intro 在 angular 中可以指定 environment 来区分不同环境下的配置,然而 environment 中的配置会在打包时是固定的,想要像 ...
- maven报错:Return code is: 501 , ReasonPhrase:HTTPS Required
今天把一个去年没做完的项目翻出来做时,发现maven无法正常导入依赖.检查了一遍项目配置,没发现有什么问题.而且依赖在本地仓库存在. 随后发现报错:Failed to transfer file:** ...
- [bzoj4443] [loj#2006] [洛谷P4251] [Scoi2015]小凸玩矩阵
Description 小凸和小方是好朋友,小方给小凸一个 \(N \times M\)( \(N \leq M\) )的矩阵 \(A\) ,要求小秃从其中选出 \(N\) 个数,其中任意两个数字不能 ...
- latex之在windows环境下能够在latex中使用中文
今天要把前段时间的实验用英语先记录下来,自己就想根据原来会议的模版弄一个简易的页面(英语),突然想到之前用英文模板时是不能输入中文的,于是想着怎么在latex中输入中文,折腾了许久,终于成功了,现在分 ...
- MEF sample
博客里介绍ntier 基于这个框架有一个叫WAF的示例项目. 看 waf(WPF Application Framework)里面这样有句 不是很懂, This page might help you ...
- ip 地址库 这个 准么 呢
- RainbowPlan-Alpha版本发布2
博客介绍 这个作业属于哪个课程 https://edu.cnblogs.com/campus/xnsy/GeographicInformationScience/ 这个作业要求在哪里 https:// ...
- 异想家Win7系统安装的软件与配置
C盘推荐一个硬盘,256G以上,安装好驱动,激活Win7,备份一次系统(纯净)! 1.Mac.Linux时间同步(双系统时配置): 开始->运行->CMD,打开命令行程序(以管理员方式打开 ...