A. linux里面ansible作用是什么
Ansible是一款简单的运维自动化工具,只需要使用ssh协议连接就可以来进行系统管理,自动化执行命令,部署等任务。
Ansible的优点
不需要安装客户端,不需要运行服务
使用python开发的一套自动执行任务的模块
playbook采用yaml配置,结构清晰
Ansible的组成结构
Ansible:核心命令工具,一次性或临时性执行的操作都由该工具执行
Ansible playbook:任务剧本(又称任务集),编排定义Ansible任务集的配置文件,由Ansible执行,格式是yaml
Inventory:Ansible管理的主机,在/etc/ansible/hosts中配置
Moles:Ansible执行命令的功能模块,Ansible2.3版本为止,共有1039个模块。还可以自定义模块。
Plugins:插件,模块功能的补充,常有连接类型插件,循环插件,变量插件,过滤插件,插件功能用的较少。
API:提供给第三方程序调用的应用程序编程接口。
B. 如何使用Ansible 2.0 API的Python运行剧本
在ansible1.9的时候,API是一个非常简单的东西。官方说“it's pretty simple”,真是又pretty又simple。
import ansible.runner
runner = ansible.runner.Runner(
mole_name='ping',
mole_args='',
pattern='web*',
forks=10
)
datastructure = runner.run()
到了ansible2.0以后,是“a bit more complicated”,Oh my,简直让人难受。
简洁和灵活是鱼和熊掌。
ansible2.0 API怎么用?
ansible2.0更贴近于ansible cli的常用命令执行方式,不同于上一版本只能发送单个命令或playbook;而更推荐用户在调用ansibleAPI的时候,将playbook的每个task拆分出来,获取每个task的结果。能够跟灵活处理在执行批量作业过程中的各种反馈。
将执行操作的队列模型,包含各类环境参数设置,归结到“ansible.executor.task_queue_manager”类中
将执行过程中的各个task的设置,或者说playbook中的编排内容,归结到“ansible.playbook.play”中
上述两个东西,几乎囊括了可以在执行过程中设置的所有参数,足够灵活,也让人抓狂,相当于需要自己写一个1.9版本中的runner。
他们的确也都是原生类,并非专用于外部调用。
ansible.executor.task_queue_manager
这是ansible的一个内部模块(ansible/executor/task_queue_manager.py)。初始化的源码如下:
class TaskQueueManager:
'''
This class handles the multiprocessing requirements of Ansible by
creating a pool of worker forks, a result handler fork, and a
manager object with shared datastructures/queues for coordinating
work between all processes.
The queue manager is responsible for loading the play strategy plugin,
which dispatches the Play's tasks to hosts.
'''
def __init__(self, inventory, variable_manager, loader, options, passwords, stdout_callback=None, run_additional_callbacks=True, run_tree=False):
self._inventory = inventory
self._variable_manager = variable_manager
self._loader = loader
self._options = options
self._stats = AggregateStats()
self.passwords = passwords
self._stdout_callback = stdout_callback
self._run_additional_callbacks = run_additional_callbacks
self._run_tree = run_tree
self._callbacks_loaded = False
self._callback_plugins = []
self._start_at_done = False
self._result_prc = None
……
创建时,需要的主要参数包括:
inventory --> 由ansible.inventory模块创建,用于导入inventory文件
variable_manager --> 由ansible.vars模块创建,用于存储各类变量信息
loader --> 由ansible.parsing.dataloader模块创建,用于数据解析
options --> 存放各类配置信息的数据字典
passwords --> 登录密码,可设置加密信息
stdout_callback --> 回调函数
ansible.playbook.play
ansible.playbook是一个原生模块,既用于CLI也用于API。从源码可以看出来:
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
ansible.playbook.play(ansible/playbook/play.py)。初始化源码的介绍如下:
__all__ = ['Play']
class Play(Base, Taggable, Become):
"""
A play is a language feature that represents a list of roles and/or
task/handler blocks to execute on a given set of hosts.
Usage:
Play.load(datastructure) -> Play
Play.something(...)
"""
最后,用task_queue_manager(play)来执行,老规矩,源码的官方解释。
def run(self, play):
'''
Iterates over the roles/tasks in a play, using the given (or default)
strategy for queueing tasks. The default is the linear strategy, which
operates like classic Ansible by keeping all hosts in lock-step with
a given task (meaning no hosts move on to the next task until all hosts
are done with the current task).
'''
一个完整的例子
# -*- coding:utf-8 -*-
# !/usr/bin/env python
#
# Author: Shawn.T
# Email: [email protected]
#
# this is the Interface package of Ansible2 API
#
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from tempfile import NamedTemporaryFile
import os
class AnsibleTask(object):
def __init__(self, targetHost):
Options = namedtuple(
'Options', [
'listtags', 'listtasks', 'listhosts', 'syntax', 'connection','mole_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'
]
)
# initialize needed objects
self.variable_manager = VariableManager()
self.options = Options(
listtags=False, listtasks=False, listhosts=False, syntax=False, connection='smart',
mole_path='/usr/lib/python2.7/site-packages/ansible/moles', 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=False, become_method=None, become_user='root',
verbosity=None, check=False
)
self.passwords = dict(vault_pass='secret')
self.loader = DataLoader()
# create inventory and pass to var manager
self.hostsFile = NamedTemporaryFile(delete=False)
self.hostsFile.write(targetHost)
self.hostsFile.close()
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.hostsFile.name)
self.variable_manager.set_inventory(self.inventory)
def ansiblePlay(self, action):
# create play with tasks
args = "ls /"
play_source = dict(
name = "Ansible Play",
hosts = 'all',
gather_facts = 'no',
tasks = [
dict(action=dict(mole='shell', args=args), register='shell_out'),
dict(action=dict(mole='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
# run it
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback='default',
)
result = tqm.run(play)
finally:
# print result
if tqm is not None:
tqm.cleanup()
os.remove(self.hostsFile.name)
self.inventory.clear_pattern_cache()
return result
写一个ansibleTask类,创建了上述的各类必要的配置信息对象,最后使用ansibleTask.ansiblePlay()函数执行。
inventory文件的动态生成
写上面的代码的过程中,碰到一个问题:inventory对象创建时需要一个实体的hosts文件,而文件需要动态生成。
生成的方法参考了这篇牛逼闪闪的文章。使用tempfile.NamedTemporaryFile这个方法来创建一个有名称的临时文件,可以选择关闭后删除或保留。上面的处理办法是:不删除,在执行完毕之后,通过os.remove(self.hostsFile.name)进行删除。
ps.经YiChenWang指出,inventory的创建参数host_list可以使列表。使用以下方式创建inventory也是可以的:
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=['xx.xx.xx.xx', 'xx.xx.xx.xx'])
不过,源码中指出,采用list格式参数是无法加载inventory data的。如果需要加载,还是得使用临时文件的办法。
C. python3.6环境下ansible拉取镜像失败
需要重新下载。
AnsibleInventory是包含静态Inventory和动态Inventory两部分的,静态Inventory指的是在文件中指定的主机和组,动态Inventory指通过外部脚本获取主机列表,并按照ansible所要求的格式返回给ansilbe命令的这部分一般会结合CMDB资管系统、云计算平台等获取主机信息由于主机资源一般会动态的进行增减,而这些系统一般会智能更新我们可以通过这些工具提供的API或者接入库查询等方式返回主机列表。
在执行kolla_ansible部署openstack之前,提前拉取镜像显得很有必要。
D. 如何将ansible tower安装到python2.7目录下
pip2.6安装Ansible,但是pip2.6是基于python2.6安装的,而python2.6版本有点老。所以而已用python2.7安装Ansible。
其实python2.7安装Ansible和python2.6安装过程基本上是一样的,只不过在安装Ansible所需要的模块和Ansible时,需要用pip2.7来安装。
安装过程如下:
1、安装python2.7
安装python2.7前的准备
yum-yinstallreadlinereadline-devel
yum-yinstallzlib-devel
yum-yinstallopensslopenssl-devel
安装gcc编译工具
yum-yinstallgcc
下载python2.7安装包
下载地址:www python.org
yum-yinstallxz
tarJxfPython-2.7.11.tar.xz
cdPython-2.7.11
mkdir/usr/local/python27
./configure--prefix=/usr/local/python27
make&&makeinstall
创建软连接
ln-s/usr/local/python27/bin/python2.7/usr/bin/python2.7
2、安装pip2.7
安装setuptools
下载地址:https//pypi.python.org/pypi?%3Aaction=search&term=setuptools&submit=search
安装:
tarzxfsetuptools-19.6.2.tar.gz
cdsetuptools-19.6.2
python2.7setup.pyinstall
安装pip
下载地址:https//pypi.python.org/pypi/pip/
安装:
tarzxfpip-8.1.0.tar.gz
cdpip-8.1.0
python2.7setup.pyinstall
创建软连接
ln-s/usr/local/python27/bin/pip2.7/usr/bin/pip2.7
3、安装Ansible
安装依赖包
yum-yinstalllibffilibffi-devel
yum-yinstallgccgcc-c++python-develpython-simplejson
安装Ansible需要的python模块
pip2.
安装Ansible
pipinstallansible
安装完成后,ansible的执行文件在python2.7的bin目录下
[root@localhostbin]#cd/usr/local/python27/bin/
[root@localhostbin]#ll
total6240
-rwxr-xr-x.1rootroot110Jun1517:312to3
-rwxr-xr-x.1rootroot4203Jun1517:48ansible
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-console
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-doc
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-galaxy
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-playbook
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-pull
-rwxr-xr-x.1rootroot4203Jun1517:48ansible-vault
-rwxr-xr-x.1rootroot326Jun1517:41easy_install
-rwxr-xr-x.1rootroot334Jun1517:41easy_install-2.7
-rwxr-xr-x.1rootroot108Jun1517:31idle
-rwxr-xr-x.1rootroot284Jun1517:42pip
-rwxr-xr-x.1rootroot286Jun1517:42pip2
-rwxr-xr-x.1rootroot290Jun1517:42pip2.7
-rwxr-xr-x.1rootroot93Jun1517:31pydoc
lrwxrwxrwx.1rootroot7Jun1517:33python->python2
lrwxrwxrwx.1rootroot9Jun1517:33python2->python2.7
-rwxr-xr-x.1rootroot6271354Jun1517:31python2.7
-rwxr-xr-x.1rootroot1696Jun1517:33python2.7-config
lrwxrwxrwx.1rootroot16Jun1517:33python2-config->python2.7-config
lrwxrwxrwx.1rootroot14Jun1517:33python-config->python2-config
-rwxr-xr-x.1rootroot18556Jun1517:31smtpd.py
编辑/etc/profile文件,加入以下配置
exportANSIBLE_HOME=/usr/local/python27
exportPATH=$PATH:$ANSIBLE_HOME/bin[root@localhostbin]#ansible--version
ansible2.1.0.0
configfile=
configuredmolesearchpath=Defaultw/ooverrides
E. ansible调度python,他所在的agent机器需要安装python么
肯定需要的,如果没有Python.那么是无法启动,你也就调度不成功的
F. python Testinfra这个插件是干什么的,有高手来解答一下小白的困惑吗
Testinfra 是一个功能强大的库,可用于编写测试来验证基础设施的状态。另外它与 Ansible 和 Nagios 相结合,提供了一个用于架构即代码 (IaC) 的简单解决方案。
-- Clement Verna(作者)
根据设计, Ansible 传递机器的期望状态,以确保 Ansible 剧本或角色的内容部署到目标机器上。但是,如果你需要确保所有基础架构更改都在 Ansible 中,该怎么办?或者想随时验证服务器的状态?
Testinfra 是一个基础架构测试框架,它可以轻松编写单元测试来验证服务器的状态。它是一个 Python 库,使用强大的 pytest 测试引擎。
开始使用 Testinfra
可以使用 Python 包管理器(pip)和 Python 虚拟环境轻松安装 Testinfra。
$ python3 -m venv venv$ source venv/bin/activate(venv) $ pip install testinfra
Testinfra 也可以通过 Fedora 和 CentOS 的 EPEL 仓库中使用。例如,在 CentOS 7 上,你可以使用以下命令安装它:
$ yum install -y epel-release$ yum install -y python-testinfra
一个简单的测试脚本
在 Testinfra 中编写测试很容易。使用你选择的代码编辑器,将以下内容添加到名为 test_simple.py 的文件中:
import testinfradef test_os_release(host): assert host.file("/etc/os-release").contains("Fedora")def test_sshd_inactive(host): assert host.service("sshd").is_running is False
默认情况下,Testinfra 为测试用例提供了一个 host 对象,该对象能访问不同的辅助模块。例如,第一个测试使用 file 模块来验证主机上文件的内容,第二个测试用例使用 service 模块来检查 systemd 服务的状态。
要在本机运行这些测试,请执行以下命令:
(venv)$ pytest test_simple.py================================ test session starts ================================platform linux -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0rootdir: /home/cverna/Documents/Python/testinfraplugins: testinfra-3.0.0collected 2 itemstest_simple.py ..================================ 2 passed in 0.05 seconds ================================
有关 Testinfra API 的完整列表,你可以参考 文档 。
Testinfra 和 Ansible
Testinfra 支持的后端之一是 Ansible,这意味着 Testinfra 可以直接使用 Ansible 的清单文件和清单中定义的一组机器来对它们进行测试。
我们使用以下清单文件作为示例:
[web]app-frontend01app-frontend02[database]db-backend01
我们希望确保我们的 Apache Web 服务器在 app-frontend01 和 app-frontend02 上运行。让我们在名为 test_web.py 的文件中编写测试:
def check_httpd_service(host): """Check that the httpd service is running on the host""" assert host.service("httpd").is_running
要使用 Testinfra 和 Ansible 运行此测试,请使用以下命令:
(venv) $ pip install ansible(venv) $ py.test --hosts=web --ansible-inventory=inventory --connection=ansible test_web.py
在调用测试时,我们使用 Ansible 清单文件的 [web] 组作为目标计算机,并指定我们要使用 Ansible 作为连接后端。
使用 Ansible 模块
Testinfra 还为 Ansible 提供了一个很好的可用于测试的 API。该 Ansible 模块能够在测试中运行 Ansible 动作,并且能够轻松检查动作的状态。
def check_ansible_play(host): """ Verify that a package is installed using Ansible package mole """ assert not host.ansible("package", "name=httpd state=present")["changed"]
默认情况下,Ansible 的 检查模式 已启用,这意味着 Ansible 将报告在远程主机上执行动作时会发生的变化。
Testinfra 和 Nagios
现在我们可以轻松地运行测试来验证机器的状态,我们可以使用这些测试来触发监控系统上的警报。这是捕获意外的更改的好方法。
Testinfra 提供了与 Nagios 的集成,它是一种流行的监控解决方案。默认情况下,Nagios 使用 NRPE 插件对远程主机进行检查,但使用 Testinfra 可以直接从 Nagios 主控节点上运行测试。
要使 Testinfra 输出与 Nagios 兼容,我们必须在触发测试时使用 --nagios 标志。我们还使用 -qq 这个 pytest 标志来启用 pytest 的静默模式,这样就不会显示所有测试细节。
(venv) $ py.test --hosts=web --ansible-inventory=inventory --connection=ansible --nagios -qq line test.pyTESTINFRA OK - 1 passed, 0 failed, 0 skipped in 2.55 seconds
Testinfra 是一个功能强大的库,可用于编写测试以验证基础架构的状态。 另外与 Ansible 和 Nagios 相结合,提供了一个用于架构即代码 (IaC) 的简单解决方案。 它也是使用 Molecule 开发 Ansible 角色过程中添加测试的关键组件。
via: https://opensource.com/article/19/5/using-testinfra-ansible-verify-server-state
G. 去哪里找python的开源项目
GitHub是一个面向开源及私有软件项目的托管平台,因为只支持git 作为唯一的版本库格式进行托管,故名GitHub。作为开源代码库以及版本控制系统,Github拥有超过900万开发者用户。随着越来越多的应用程序转移到了云上,Github已经成为了管理软件开发以及发现已有代码的首选方法。在GitHub,用户可以十分轻易地找到海量的开源代码。
下面给大家介绍一些GitHub上25个开源项目:
(1)TensorFlow Models
如果你对机器学习和深度学习感兴趣,一定听说过TensorFlow。TensorFlow Models是一个开源存储库,可以找到许多与深度学习相关的库和模型。
(GitHub: https://github.com/tensorflow/models )
(2)Keras
Keras是一个高级神经网络API,用Python编写,能够在TensorFlow,CNTK或Theano之上运行。旨在完成深度学习的快速开发(GitHub: https://github.com/keras-team/keras )
(3)Flask
Flask 是一个微型的 Python 开发的 Web 框架,基于Werkzeug WSGI工具箱和Jinja2 模板引擎,使用BSD授权。
(GitHub: https://github.com/pallets/flask )
(4)scikit-learn
scikit-learn是一个用于机器学习的Python模块,基于 NumPy、SciPy 和 matplotlib 构建。,并遵循 BSD 许可协议。
(GitHub: https://github.com/scikit-learn )
(5)Zulip
Zulip是一款功能强大的开源群聊应用程序,它结合了实时聊天的即时性和线程对话的生产力优势。Zulip作为一个开源项目,被许多世界500强企业,大型组织以及其他需要实时聊天系统的用户选择使用,该系统允许用户每天轻松处理数百或数千条消息。Zulip拥有超过300名贡献者,每月合并超过500次提交,也是规模最大,发展最快的开源群聊项目。
(GitHub: https://github.com/zulip/zulip )
相关推荐:《Python入门教程》
(6)Django
Django 是 Python 编程语言驱动的一个开源模型-视图-控制器(MVC)风格的 Web 应用程序框架,旨在快速开发出清晰,实用的设计。使用 Django,我们在几分钟之内就可以创建高品质、易维护、数据库驱动的应用程序。
(GitHub: https://github.com/django/django )
(7)Rebound
Rebound 是一个当你得到编译错误时即时获取 Stack Overflow 结果的命令行工具。 就用 rebound 命令执行你的文件。这对程序员来说方便了不少。
(GitHub: https://github.com/shobrook/rebound )
(8)Google Images Download
这是一个命令行python程序,用于搜索Google Images上的关键字/关键短语,并可选择将图像下载到您的计算机。你也可以从另一个python文件调用此脚本。
(GitHub: https://github.com/hardikvasa/google-images-download )
(9)YouTube-dl
youtube-dl 是基于 Python 的命令行媒体文件下载工具,完全开源免费跨平台。用户只需使用简单命令并提供在线视频的网页地址即可让程序自动进行嗅探、下载、合并、命名和清理,最终得到已经命名的完整视频文件。
(GitHub: htt ps://github.com/rg3/youtube-dl )
(10)System Design Primer
此repo是一个系统的资源集合,可帮助你了解如何大规模构建系统。
(GitHub: https://github.com/donnemartin/system-design-primer )
(11)Mask R-CNN
Mask R-CNN用于对象检测和分割。这是对Python 3,Keras和TensorFlow的Mask R-CNN实现。该模型为图像中对象的每个实例生成边界框和分割蒙版。它基于特Feature Pyramid Network(FPN)和 ResNet101 backbone。
(GitHub: https://github.com/matterport/Mask_RCNN )
(12)Face Recognition
Face Recognition 是一个基于 Python 的人脸识别库,使用十分简便。这还提供了一个简单的face_recognition命令行工具,可以让您从命令行对图像文件夹进行人脸识别!
(GitHub: https://github.com/ageitgey/face_recognition )
(13)snallygaster
用于扫描HTTP服务器上的机密文件的工具。
(GitHub: https://github.com/hannob/snallygaster )
(14)Ansible
Ansible是一个极其简单的IT自动化系统。它可用于配置管理,应用程序部署,云配置,支持远程任务执行和多节点发布 - 包括通过负载平衡器轻松实现零停机滚动更新等操作。
(GitHub: https://github.com/ansible/ansible )
(15)Detectron
Detectron是Facebook AI 研究院开源的的软件系统,它实现了最先进的目标检测算法,包括Mask R-CNN。它是用Python编写的,由Caffe2深度学习框架提供支持。
(16)asciinema
终端会话记录器和asciinema.org的最佳搭档。
(GitHub: https://github.com/asciinema/asciinema )
(17)HTTPie
HTTPie 是一个开源的命令行的 HTTP 工具包,其目标是使与Web服务的CLI交互尽可能人性化。它提供了一个简单的http命令,允许使用简单自然的语法发送任意HTTP请求,并显示彩色输出。HTTPie可用于测试,调试以及通常与HTTP服务器交互。
(GitHub: https://github.com/jakubroztocil/httpie )
(18)You-Get
You-Get是一个小型命令行实用程序,用于从Web下载媒体内容(视频,音频,图像),支持国内外常用的视频网站。
(GitHub: https://github.com/soimort/you-get )
(19)Sentry
Sentry从根本上讲是一项服务,可以帮助用户实时监控和修复崩溃。基于Django构建,它包含一个完整的API,用于从任何语言、任何应用程序中发送事件。
(GitHub: https://github.com/getsentry/sentry )
(20)Tornado
Tornado是使用Python开发的全栈式(full-stack)Web框架和异步网络库,,最初是由FriendFeed上开发的。通过使用非阻塞网络I / O,Tornado可以扩展到数万个开放连接,是long polling、WebSockets和其他需要为用户维护长连接应用的理想选择。
(GitHub: https://github.com/tornadoweb/tornado )
(21)Magenta
Magenta是一个探索机器学习在创造艺术和音乐过程中的作用的研究项目。这主要涉及开发新的深度学习和强化学习算法,用于生成歌曲,图像,绘图等。但它也是构建智能工具和界面的探索,它允许艺术家和音乐家使用这些模型。
(GitHub: https://github.com/tensorflow/magenta )
(22)ZeroNet
ZeroNet是一个利用比特币的加密算法和BitTorrent技术提供的不受审查的网络,完全开源。
(GitHub: https://github.com/HelloZeroNet/ZeroNet )
(23)Gym
OpenAI Gym是一个用于开发和比较强化学习算法的工具包。这是Gym的开源库,可让让你访问标准化的环境。
(GitHub: https://github.com/openai/gym )
(24)Pandas
Pandas是一个Python包,提供快速,灵活和富有表现力的数据结构,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。此外,它还有更广泛的目标,即成为所有语言中最强大,最灵活的开源数据分析/操作工具。它目前已经朝着这个目标迈进。
(GitHub: https://github.com/pandas-dev/pandas )
(25)Luigi
Luigi 是一个 Python 模块,可以帮你构建复杂的批量作业管道。处理依赖决议、工作流管理、可视化展示等等,内建 Hadoop 支持。(GitHub: https://github.com/spotify/luigi )
H. python为什么不能调用ansible模块
需要将ansible作为python的一个库组件写入到自己的脚本中,今天的脚本脚本就将展示下ansible如何跟python脚本结合,也就是如何在python脚本中使用ansible,逐步展先看第一个例子:
#!/usr/bin/python
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json
# the fastest way to set up the inventory
# hosts list
hosts = ["10.11.12.66"]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)
pm = ansible.runner.Runner(
mole_name = 'command',
mole_args = 'uname -a',
timeout = 5,
inventory = example_inventory,
subset = 'all' # name of the hosts group
)
out = pm.run()
print json.mps(out, sort_keys=True, indent=4, separators=(',', ': '))
I. 如何使用ansible 2.0 python api
Ansible 和 SaltStack 都提供了 Python 直接调用的API, 这方便了 Pythoner 对这些软件进行二次开发和整合, 此功能着实方便了不少, 比起 Python 代码中调用 shell 也略显专业!
然而 Ansible 在2.0版本后重构了大部分的代码逻辑, 启用了2.0版本之前的 Runner 和 Playbook 类, 使得广大同学之前的代码运行错误. 择日不如撞日, 今天中午对照 官方的文档 , 结合源代码, 对2.0版本之后的 Python API 做了下探究
Adhoc
adhoc 其实就是执行 Ansible 模块, 通过 adhoc 我们可以方便快捷的完成一些临时的运维操作.
2.0 之前的调用
import ansible.runner
import json
runner = ansible.runner.Runner(
mole_name='ping', # 模块名
mole_args='', # 模块参数
pattern='all', # 目标机器的pattern
forks=10
)
datastructure = runner.run()
data = json.mps(datastructure,indent=4)
当然这里会去加载默认的 inventory
如果不想使用 inventory 文件或者想使用动态的 inventory, 则可以使用 host_list 参数代替
import ansible.runner
import json
runner = ansible.runner.Runner(
host_list=["10.10.0.1"], # 这里如果明确指定主机需要传递一个列表, 或者指定动态inventory脚本
mole_name='ping', # 模块名
mole_args='', # 模块参数
extra_vars={"ansible_ssh_user":"root","ansible_ssh_pass":"xx"},
forks=10
)
datastructure = runner.run()
data = json.mps(datastructure,indent=4)
2.0 之后的调用
import json
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
loader = DataLoader() # 用来加载解析yaml文件或JSON内容,并且支持vault的解密
variable_manager = VariableManager() # 管理变量的类,包括主机,组,扩展等变量,之前版本是在 inventory 中的
inventory = Inventory(loader=loader, variable_manager=variable_manager)
variable_manager.set_inventory(inventory) # 根据 inventory 加载对应变量
class Options(object):
'''
这是一个公共的类,因为ad-hoc和playbook都需要一个options参数
并且所需要拥有不同的属性,但是大部分属性都可以返回None或False
因此用这样的一个类来省去初始化大一堆的空值的属性
'''
def __init__(self):
self.connection = "local"
self.forks = 1
self.check = False
def __getattr__(self, name):
return None
options = Options()
def run_adhoc():
variable_manager.extra_vars={"ansible_ssh_user":"root" , "ansible_ssh_pass":"xxx"} # 增加外部变量
# 构建pb, 这里很有意思, 新版本运行ad-hoc或playbook都需要构建这样的pb, 只是最后调用play的类不一样
# :param name: 任务名,类似playbook中tasks中的name
# :param hosts: playbook中的hosts
# :param tasks: playbook中的tasks, 其实这就是playbook的语法, 因为tasks的值是个列表,因此可以写入多个task
play_source = {"name":"Ansible Ad-Hoc","hosts":"10.10.0.1","gather_facts":"no","tasks":[{"action":{"mole":"shell","args":"w"}}]}
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=None,
stdout_callback='minimal',
run_tree=False,
)
result = tqm.run(play)
print result
finally:
if tqm is not None:
tqm.cleanup()
if __name__ == '__main__':
run_adhoc()
Playbook
playbook 则类似于 SaltStack 中的 state
2.0 之前的调用
from ansible import callbacks
from ansible import utils
from ansible.playbook import PlayBook
stats = callbacks.AggregateStats()
callback = callbacks.PlaybookCallbacks()
runner_callbacks = callbacks.PlaybookRunnerCallbacks(stats)
pb = ansible.playbook.PlayBook(
playbook="tasks.yml",
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
check=True
)
pb.run()
2.0 之后的调用
import json
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
loader = DataLoader() # 用来加载解析yaml文件或JSON内容,并且支持vault的解密
variable_manager = VariableManager() # 管理变量的类,包括主机,组,扩展等变量,之前版本是在 inventory 中的
inventory = Inventory(loader=loader, variable_manager=variable_manager)
variable_manager.set_inventory(inventory) # 根据 inventory 加载对应变量
class Options(object):
'''
这是一个公共的类,因为ad-hoc和playbook都需要一个options参数
并且所需要拥有不同的属性,但是大部分属性都可以返回None或False
因此用这样的一个类来省去初始化大一堆的空值的属性
'''
def __init__(self):
self.connection = "local"
self.forks = 1
self.check = False
def __getattr__(self, name):
return None
options = Options()
def run_playbook():
playbooks=['task.yaml'] # 这里是一个列表, 因此可以运行多个playbook
variable_manager.extra_vars={"ansible_ssh_user":"root" , "ansible_ssh_pass":"xxx"} # 增加外部变量
pb = PlaybookExecutor(playbooks=playbooks, inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=None)
result = pb.run()
print result
if __name__ == '__main__':
run_playbook()