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()