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来设置 ...
随机推荐
- 安装k8s和NVIDIA环境
安装环境 系统要求 CPU: 2个核心 内存: 2GB 显卡:NVIDIA系列 安装docker apt install docker.io 安装k8s 添加软件源 方便起见,将Ubuntu的软件管理 ...
- Python爬虫入门教程 33-100 电影评论数据抓取 scrapy
1. 海王评论数据爬取前分析 海王上映了,然后口碑炸了,对咱来说,多了一个可爬可分析的电影,美哉~ 摘录一个评论 零点场刚看完,温导的电影一直很不错,无论是速7,电锯惊魂还是招魂都很棒.打斗和音效方面 ...
- Spring Boot2 系列教程(十九) | @Value 和 @ConfigurationProperties 的区别
微信公众号:一个优秀的废人.如有问题,请后台留言,反正我也不会听. 前言 最近有跳槽的想法,所以故意复习了下 SpringBoot 的相关知识,复习得比较细.其中有些,我感觉是以前忽略掉的东西,比如 ...
- mysql复习1
SQL语句分为以下三种类型: DML: Data Manipulation Language 数据操纵语言,用于查询与修改数据记录,包括如下SQL语句:INSERT:添加数据到数据库中UPDATE:修 ...
- IDEA中springboot的热部署
在pom.xml文件中添加依赖 <!--添加热部署--> <dependency> <groupId>org.springframework.boot</gr ...
- NOI4.6 最小新整数——切山游戏
描述 给定一个十进制正整数n(0 < n < 1000000000),每个数位上数字均不为0.n的位数为m. 现在从m位中删除k位(0<k < m),求生成的新整数最小为多少? ...
- Java的String类常用方法
一.构造函数 String(byte[ ] bytes):通过byte数组构造字符串对象. String(char[ ] value):通过char数组构造字符串对象. String(Sting or ...
- atx测试框架实现手机应用UI自动化测试
最近工作中遇到游戏APP需要实现UI自动化测试,这个app中真的是典型的混合App,有Android原生控件,有webview控件,以及游戏操作页面.研究了Appium,发现appium实现跨应用操作 ...
- The system is running in low-graphics mode
No internet 1.Ctrl + Alt + F1 2.login 3.input the code below: sudo chown lightdm:lightdm -R /var/lib ...
- V8垃圾回收?看这篇就够了!
什么是内存管理 内存管理是控制和协调应用程序访问电脑内存的过程.这个过程是复杂的,对于我们来说,可以说相当于一个黑匣子. 当咱们的应用程序运行在某个操作系统中的时候,它访问电脑内存(RAM)来达成下列 ...