http://www.lxweimin.com/p/ec1e4d8438e9
一、安裝方式
安裝方式有兩種:
- YUM 工具
- PIP 工具
1 YUM 工具安裝(適用于給系統自帶的 python 版本安裝 ansilbe 模塊)
- 安裝 epel 源
yum install epel-release -y
- 安裝 Ansible
yum install ansible -y
- 導入模塊
[root@5e4b448b73e5 ~]# python
Python 2.7.5 (default, Aug 7 2019, 00:51:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ansible
>>> ansible.__file__
'/usr/lib/python2.7/site-packages/ansible/__init__.pyc'
>>>
2 PIP3 工具安裝(使用于給指定版本的 Python 安裝 ansible 模塊)
- 創建虛擬環境
[root@5e4b448b73e5 ~]# pip3 install virtualenvwrapper
export VIRTUALENVWRAPPER_PYTHON=$(which python3)
export WORKON_HOME=$HOME/.virtualenv
source /usr/local/bin/virtualenvwrapper.sh
[root@5e4b448b73e5 ~]# ~/.virtualenv
[root@5e4b448b73e5 ~]# source .bashrc
創建虛擬環境
[root@5e4b448b73e5 ~]# mkvirtualenv ansibleapi
- 安裝 ansible
(ansibleapi) [root@5e4b448b73e5 ~]# pip3 install ansible
- 導入模塊
(ansibleapi) [root@5e4b448b73e5 ~]# python3
Python 3.7.6 (default, Aug 11 2020, 10:30:02)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ansible
>>> ansible.__file__
'/root/.virtualenv/ansibleapi/lib/python3.7/site-packages/ansible/__init__.py'
>>>
3 配置文件位置說明
這種安裝方式,配置文件和資產配置文件不會在 /etc
下產生。
將會在下面的路徑下:
/root/.virtualenv/ansibleapi/lib/python3.7/site-packages/ansible/galaxy/data/container/tests/
用到這些文件的時候,需要在 /etc
目錄想創建目錄 ansible
, 之后把需要的配置文件和資產配置文件放到 /etc/ansible/
目錄下。
二、 先從官方示例入手
點擊 官方示例源碼 v2.8
注意:下面的所有開發,都是以
2.8
版本為例的(2.9.9
已通過測試 )。2.7
和2.8
版本有一些差異:
2.7 使用了 Python 標準庫里的 命名元組來初始化選項,而2.8
是 Ansible 自己封裝了一個ImmutableDict
,之后需要和context
結合使用的。兩者不能互相兼容。 點擊 2.7 官方示例
#!/usr/bin/env python3
import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from ansible import context
import ansible.constants as C
class ResultCallback(CallbackBase):
"""A sample callback plugin used for performing an action as results come in
If you want to collect all results into a single object for processing at
the end of the execution, look into utilizing the ``json`` callback plugin
or writing your own custom callback plugin
"""
def v2_runner_on_ok(self, result, **kwargs):
"""Print a json representation of the result
This method could store the result in an instance attribute for retrieval later
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
# since the API is constructed for CLI it expects certain options to always be set in the context object
context.CLIARGS = ImmutableDict(connection='local', module_path=['/to/mymodules'], forks=10, become=None,
become_method=None, become_user=None, check=False, diff=False)
# initialize needed objects
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
# 注意這里的 vault_pass 是錯誤的,正確的應該是 conn_pass
passwords = dict(vault_pass='secret')
# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
results_callback = ResultCallback()
# create inventory, use path to host config file as source or hosts in a comma separated string
inventory = InventoryManager(loader=loader, sources='localhost,')
# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)
# create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.
play_source = dict(
name = "Ansible Play",
hosts = 'localhost',
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='ls'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
# Create play object, playbook objects use .load instead of init or new methods,
# this will also automatically create the task objects from the info provided in play_source
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
)
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
# we always need to cleanup child procs and the structures we use to communicate with them
if tqm is not None:
tqm.cleanup()
# Remove ansible tmpdir
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
下面是把官方的示例分解開了
1. 首先是需要導入的模塊
import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from ansible import context
import ansible.constants as C
核心類介紹
導入類完整路徑 | 功能用途 |
---|---|
from ansible.module_utils.common.collections import ImmutableDict |
用于添加選項。比如: 指定遠程用戶remote_user=None
|
from ansible.parsing.dataloader import DataLoader |
讀取 json/ymal/ini 格式的文件的數據解析器 |
from ansible.vars.manager import VariableManager |
管理主機和主機組的變量管理器 |
from ansible.inventory.manager import InventoryManager |
管理資源庫的,可以指定一個 inventory 文件等 |
from ansible.playbook.play import Play |
用于執行 Ad-hoc 的類 ,需要傳入相應的參數 |
from ansible.executor.task_queue_manager import TaskQueueManager |
ansible 底層用到的任務隊列管理器 |
ansible.plugins.callback.CallbackBase |
處理任務執行后返回的狀態 |
from ansible import context |
上下文管理器,他就是用來接收 ImmutableDict 的示例對象 |
import ansible.constants as C |
用于獲取 ansible 產生的臨時文檔。 |
from ansible.executor.playbook_executor import PlaybookExecutor |
執行 playbook 的核心類 |
from ansible.inventory.host import Group |
對 主機組 執行操作 ,可以給組添加變量等操作,擴展 |
from ansible.inventory.host import Host |
對 主機 執行操作 ,可以給主機添加變量等操作,擴展 |
2. 回調插件
回調插件就是一個類。
用于處理執行結果的。
后面我們可以改寫這個類,以便滿足我們的需求。
class ResultCallback(CallbackBase):
"""回調插件,用于對執行結果的回調,
如果要將執行的命令的所有結果都放到一個對象中,應該看看如何使用 JSON 回調插件或者
編寫自定義的回調插件
"""
def v2_runner_on_ok(self, result, **kwargs):
"""
將結果以 json 的格式打印出來
此方法可以將結果存儲在實例屬性中以便稍后檢索
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
3. 選項
這是最新 2.8 中的方式。老版本,請自行谷歌。
# 需要始終設置這些選項,值可以變
context.CLIARGS = ImmutableDict(
connection='local', module_path=['module_path'],
forks=10, become=None, become_method=None,
become_user=None, check=False, diff=False)
4. 數據解析器、密碼和回調插件對象
數據解析器,用于解析 存放主機列表的資源庫文件 (比如:
/etc/ansible/hosts
) 中的數據和變量數據的。
密碼這里是必須使用的一個參數,假如通過了公鑰信任,也可以給一個空字典
# 需要實例化一下
loader = DataLoader()
# ssh 用戶的密碼, 2.9.9 版本中測試通過,需要安裝 sshpass 程序
passwords = dict(conn_pass='secret')
# 實例化一下
results_callback = ResultCallback()
5. 創建資源庫對象
這里需要使用數據解析器
sources
的值可以是一個配置好的inventory
資源庫文件;也可以是一個含有以 逗號,
為分割符的字符串,
注意不是元組哦,正確示例:sources='localhost,'
這里寫的是自己主機上實際的資源庫文件
inventory = InventoryManager(loader=loader, sources='/etc/ansible/hosts')
6. 變量管理器
假如有變量,所有的變量應該交給他管理。
這里他會從inventory
對象中獲取到所有已定義好的變量。
這里也需要數據解析器。
variable_manager = VariableManager(loader=loader, inventory=inventory)
7. 創建一個 Ad-hoc
這里創建一個命令行執行的 ansible 命令是可以是多個的。以
task
的方式體現。
既然都是 python 寫的,那么這些變量的值都可以是從數據庫中取到的數據或者從前端接收到的參數。
開發的雛形若隱若現了...
play_source = dict(
name = "Ansible Play",
hosts = 'nginx',
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='ls'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
9. 從 Play 的靜態方法 load
中創建一個 play 對象。
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
8. 任務隊列管理器
要想執行 Ad-hoc ,需要把上面的 play 對象交個任務隊列管理器的
run
方法去運行。
# 先定義一個值,防止代碼出錯后, `finally` 語句中的 `tqm` 未定義。
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords,
stdout_callback=results_callback, # 這里是使用了之前,自定義的回調插件,而不是默認的回調插件 `default`
)
result = tqm.run(play) # 執行的結果返回碼,成功是 0
finally:
# `finally` 中的代碼,無論是否發生異常,都會被執行。
# 如果 `tqm` 不是 `None`, 需要清理子進程和我們用來與它們通信的結構。
if tqm is not None:
tqm.cleanup()
# 最后刪除 ansible 產生的臨時目錄
# 這個臨時目錄會在 ~/.ansible/tmp/ 目錄下
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
總結一下
Ad-hoc 模式到 API 的映射
三、二次開發
說完官方示例,那么我們究竟可以使用 ansible API 干些不一樣的事情呢?
1. 重寫回調插件
首先,官方示例值的回調函數沒有進行進一個的格式化,這個我們可以改寫一下這個類里的回調函數。
還有,可以增加上失敗的信息展示以及主機不可達的信息展示。
class ResultCallback(CallbackBase):
"""
重寫callbackBase類的部分方法
"""
def __init__(self, *args, **kwargs):
super().__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, **kwargs):
self.host_ok[result._host.get_name()] = result
def v2_runner_on_failed(self, result, **kwargs):
self.host_failed[result._host.get_name()] = result
如何使用
for host, result in results_callback.host_ok.items():
print("主機{}, 執行結果{}".format(host, result._result))
四、如何執行 playbook
1. 先看 playbook_executor.PlaybookExecutor
源碼
class PlaybookExecutor:
'''
This is the primary class for executing playbooks, and thus the
basis for bin/ansible-playbook operation.
'''
def __init__(self, playbooks, inventory, variable_manager, loader, passwords):
self._playbooks = playbooks
self._inventory = inventory
self._variable_manager = variable_manager
self._loader = loader
self.passwords = passwords
self._unreachable_hosts = dict()
...略...
2. 執行 playbook
其他用到的部分和 Ad-hoc 方式時的一樣
from ansible.executor.playbook_executor import PlaybookExecutor
playbook = PlaybookExecutor(playbooks=['/root/test.yml'], # 注意這里是一個列表
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords)
# 使用回調函數
playbook._tqm._stdout_callback = results_callback
result = playbook.run()
for host, result in results_callback.host_ok.items():
print("主機{}, 執行結果{}".format(host, result._result['result']['stdout'])
五、動態添加主機和主機組
使用 ansible API 可以從其他來源中動態的創建資源倉庫。比如從 CMDB 的數據庫中。
InventoryManager 類
方法
inv = InventoryManager(loader=loader, sources='localhost,')
# 創建一個組 nginx
inv.add_group('nginx')
# 向 nginx 組中添加主機
inv.add_host(host='node1',group='nginx')
inv.add_host(host='node2',group='nginx')
# 獲取目前所有的組和主機的信息
In [38]: inv.get_groups_dict()
Out[38]: {'all': ['localhost'], 'ungrouped': ['localhost'], 'nginx': ['node1', 'node2']}
這樣就會動態創建一個 nginx 的組,并且向組內添加了兩個主機
寫到一個類里
import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from ansible import context
import ansible.constants as C
class ResultCallback(CallbackBase):
"""
重寫callbackBase類的部分方法
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.task_ok = {}
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result
def v2_runner_on_ok(self, result, **kwargs):
self.host_ok[result._host.get_name()] = result
def v2_runner_on_failed(self, result, **kwargs):
self.host_failed[result._host.get_name()] = result
class MyAnsiable2():
def __init__(self,
connection='local', # 連接方式 local 本地方式,smart ssh方式
remote_user=None, # ssh 用戶
remote_password=None, # ssh 用戶的密碼,應該是一個字典, key 必須是 conn_pass
private_key_file=None, # 指定自定義的私鑰地址
sudo=None, sudo_user=None, ask_sudo_pass=None,
module_path=None, # 模塊路徑,可以指定一個自定義模塊的路徑
become=None, # 是否提權
become_method=None, # 提權方式 默認 sudo 可以是 su
become_user=None, # 提權后,要成為的用戶,并非登錄用戶
check=False, diff=False,
listhosts=None, listtasks=None,listtags=None,
verbosity=3,
syntax=None,
start_at_task=None,
inventory=None):
# 函數文檔注釋
"""
初始化函數,定義的默認的選項值,
在初始化的時候可以傳參,以便覆蓋默認選項的值
"""
context.CLIARGS = ImmutableDict(
connection=connection,
remote_user=remote_user,
private_key_file=private_key_file,
sudo=sudo,
sudo_user=sudo_user,
ask_sudo_pass=ask_sudo_pass,
module_path=module_path,
become=become,
become_method=become_method,
become_user=become_user,
verbosity=verbosity,
listhosts=listhosts,
listtasks=listtasks,
listtags=listtags,
syntax=syntax,
start_at_task=start_at_task,
)
# 三元表達式,假如沒有傳遞 inventory, 就使用 "localhost,"
# 指定 inventory 文件
# inventory 的值可以是一個 資產清單文件
# 也可以是一個包含主機的元組,這個僅僅適用于測試
# 比如 : 1.1.1.1, # 如果只有一個 IP 最后必須有英文的逗號
# 或者: 1.1.1.1, 2.2.2.2
self.inventory = inventory if inventory else "localhost,"
# 實例化數據解析器
self.loader = DataLoader()
# 實例化 資產配置對象
self.inv_obj = InventoryManager(loader=self.loader, sources=self.inventory)
# 設置密碼
self.passwords = remote_password
# 實例化回調插件對象
self.results_callback = ResultCallback()
# 變量管理器
self.variable_manager = VariableManager(self.loader, self.inv_obj)
def run(self, hosts='localhost', gether_facts="no", module="ping", args='', task_time=0):
"""
參數說明:
task_time -- 執行異步任務時等待的秒數,這個需要大于 0 ,等于 0 的時候不支持異步(默認值)。這個值應該等于執行任務實際耗時時間為好
"""
play_source = dict(
name = "Ad-hoc",
hosts = hosts,
gather_facts = gether_facts,
tasks = [
# 這里每個 task 就是這個列表中的一個元素,格式是嵌套的字典
# 也可以作為參數傳遞過來,這里就簡單化了。
{"action":{"module": module, "args": args}, "async": task_time, "poll": 0}])
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inv_obj ,
variable_manager=self.variable_manager,
loader=self.loader,
passwords=self.passwords,
stdout_callback=self.results_callback)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def playbook(self,playbooks):
"""
Keyword arguments:
playbooks -- 需要是一個列表類型
"""
from ansible.executor.playbook_executor import PlaybookExecutor
playbook = PlaybookExecutor(playbooks=playbooks,
inventory=self.inv_obj,
variable_manager=self.variable_manager,
loader=self.loader,
passwords=self.passwords)
# 使用回調函數
playbook._tqm._stdout_callback = self.results_callback
result = playbook.run()
def get_result(self):
result_raw = {'success':{},'failed':{},'unreachable':{}}
# print(self.results_callback.host_ok)
for host,result in self.results_callback.host_ok.items():
result_raw['success'][host] = result._result
for host,result in self.results_callback.host_failed.items():
result_raw['failed'][host] = result._result
for host,result in self.results_callback.host_unreachable.items():
result_raw['unreachable'][host] = result._result
# 最終打印結果,并且使用 JSON 繼續格式化
print(json.dumps(result_raw, indent=4))
這個類可以執行 Ad-hoc 也可以執行 playbook
為了測試方便,這里設置了一些默認值:
連接模式采用local
,也就是本地方式
資產使用"localhost,"
執行 Ad-hoc 時,默認的主機是localhost
執行 Playbook 時,必須傳入
playbooks
位置參數,其值是一個包含playbook.yml
文件路徑的列表,如:
絕對路徑寫法["/root/test.yml"]
當前路徑寫法["test.yml"]
使用范例一:
記得要先建立免密登錄
執行 默認的 Ad-hoc
實例化
ansible2 = MyAnsiable2()
執行 ad-hoc
ansible2.run()
打印結果
ansible2.get_result()
輸出內容
[root@635bbe85037c ~]# /usr/local/bin/python3 /root/code/ansible2api2.8.py
{
"success": {
"localhost": {
"invocation": {
"module_args": {
"data": "pong"
}
},
"ping": "pong",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false,
"changed": false
}
},
"failed": {},
"unreachable": {}
}
使用范例二:
執行自定義的 ad-hoc
資產配置文件 /etc/ansible/hosts
內容
[nginx]
172.19.0.2
172.19.0.3
代碼
使用自己的 資產配置文件,并使用 ssh 的遠程連接方式
ansible2 = MyAnsiable2(inventory='/etc/ansible/hosts', connection='smart')
執行自定義任務,執行對象是 nginx 組
ansible2.run(hosts= "nginx", module="shell", args='ip a |grep "inet"')
打印結果
ansible2.get_result()
輸出內容
[root@635bbe85037c ~]# /usr/local/bin/python3 /root/code/ans
ible2api2.8.py
{
"success": {
"172.19.0.2": {
"changed": true,
"end": "2019-08-11 11:09:28.954365",
"stdout": " inet 127.0.0.1/8 scope host lo\n
inet 172.19.0.2/16 brd 172.19.255.255 scope global eth0",
"cmd": "ip a |grep \"inet\"",
"rc": 0,
"start": "2019-08-11 11:09:28.622177",
"stderr": "",
"delta": "0:00:00.332188",
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": true,
"strip_empty_ends": true,
"_raw_params": "ip a |grep \"inet\"",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin_add_newline": true,
"stdin": null
}
},
"stdout_lines": [
" inet 127.0.0.1/8 scope host lo",
" inet 172.19.0.2/16 brd 172.19.255.255 scope global eth0"
],
"stderr_lines": [],
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false
},
"172.19.0.3": {
"changed": true,
"end": "2019-08-11 11:09:28.952018",
"stdout": " inet 127.0.0.1/8 scope host lo\n inet 172.19.0.3/16 brd 172.19.255.255 scope global eth0",
"cmd": "ip a |grep \"inet\"",
"rc": 0,
"start": "2019-08-11 11:09:28.643490",
"stderr": "",
"delta": "0:00:00.308528",
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": true,
"strip_empty_ends": true,
"_raw_params": "ip a |grep \"inet\"",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin_add_newline": true,
"stdin": null
}
},
"stdout_lines": [
" inet 127.0.0.1/8 scope host lo",
" inet 172.19.0.3/16 brd 172.19.255.255 scope global eth0"
],
"stderr_lines": [],
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false
}
},
"failed": {},
"unreachable": {}
}
使用范例三 執行 playbook:
沿用上例繼續執行一個 playbook
playbook /root/test.yml
內容
---
- name: a test playbook
hosts: [nginx]
gather_facts: no
tasks:
- shell: ip a |grep inet
...
代碼
ansible2 = MyAnsiable2(inventory='/etc/ansible/hosts', connection='smart')
傳入playbooks 的參數,需要是一個列表的數據類型,這里是使用的相對路徑
相對路徑是相對于執行腳本的當前用戶的家目錄
ansible2.playbook(playbooks=['test.yml'])
ansible2.get_result()
輸出內容
[root@635bbe85037c ~]# /usr/local/bin/python3 /root/code/ansible2api2.8.py
{
"success": {
"172.19.0.2": {
"changed": true,
"end": "2019-08-11 11:12:34.563817",
"stdout": " inet 127.0.0.1/8 scope host lo\n inet 172.19.0.2/16 brd 172.19.255.255 scope global eth0",
"cmd": "ip a |grep inet",
"rc": 0,
"start": "2019-08-11 11:12:34.269078",
"stderr": "",
"delta": "0:00:00.294739",
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": true,
"strip_empty_ends": true,
"_raw_params": "ip a |grep inet",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin_add_newline": true,
"stdin": null
}
},
"stdout_lines": [
" inet 127.0.0.1/8 scope host lo",
" inet 172.19.0.2/16 brd 172.19.255.255 scope global eth0"
],
"stderr_lines": [],
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false
},
"172.19.0.3": {
"changed": true,
"end": "2019-08-11 11:12:34.610433",
"stdout": " inet 127.0.0.1/8 scope host lo\n inet 172.19.0.3/16 brd 172.19.255.255 scope global eth0",
"cmd": "ip a |grep inet",
"rc": 0,
"start": "2019-08-11 11:12:34.290794",
"stderr": "",
"delta": "0:00:00.319639",
"invocation": {
"module_args": {
"creates": null,
"executable": null,
"_uses_shell": true,
"strip_empty_ends": true,
"_raw_params": "ip a |grep inet",
"removes": null,
"argv": null,
"warn": true,
"chdir": null,
"stdin_add_newline": true,
"stdin": null
}
},
"stdout_lines": [
" inet 127.0.0.1/8 scope host lo",
" inet 172.19.0.3/16 brd 172.19.255.255 scope global eth0"
],
"stderr_lines": [],
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false
}
},
"failed": {},
"unreachable": {}
}
使用范例四 playbook 中提權
---
- name: a test playbook
hosts: [nginx]
gather_facts: no
remote_user: shark
become: True
become_method: sudo
vars:
ansible_become_password: upsa
tasks:
- shell: id
...
使用范例五 執行異步任務
代碼
ansible2 = MyAnsiable2(connection='smart')
ansible2.run(module="shell", args="sleep 15;hostname -i", task_time=15)
ansible2.get_result()
執行輸出結果
(ansible) [root@iZ2zecj761el8gvy7p9y2kZ ~]# python3 myansibleapi2.py
{
"success": {
"localhost": {
"started": 1,
"finished": 0,
"results_file": "/root/.ansible_async/118567079981.4210",
"ansible_job_id": "118567079981.4210",
"changed": true,
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"_ansible_no_log": false
}
},
"failed": {},
"unreachable": {}
}
ansible_job_id
是這個任務返回的任務 ID
獲取任務結果
(ansible) [root@iZ2zecj761el8gvy7p9y2kZ ~]# ansible 127.0.0.1 -i 127.0.0.1, -m async_status -a "jid=118567079981.4210"
127.0.0.1 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"ansible_job_id": "118567079981.4210",
"changed": true,
"cmd": "sleep 15;hostname -i",
"delta": "0:00:15.034476",
"end": "2020-06-11 12:06:57.723919",
"finished": 1,
"rc": 0,
"start": "2020-06-11 12:06:42.689443",
"stderr": "",
"stderr_lines": [],
"stdout": "127.0.0.1 172.17.125.171 ::1",
"stdout_lines": [
"127.0.0.1 172.17.125.171 ::1"
]
}
使用范例六 在 playbook 中執行異步任務
playbook 中執行異步任務可以說和 api 的開發幾乎沒有關系, 是在 playbook 中實現的。
---
- name: a test playbook
hosts: [localhost]
gather_facts: no
tasks:
- shell: sleep 10;hostname -i
async: 10 # 異步
poll: 0
register: job
- name: show job id
debug:
msg: "Job id is {{ job }}"
...
執行和獲取結果參考前面的范例三
參考
Inventory 部分參數說明
ansible_ssh_host
將要連接的遠程主機名.與你想要設定的主機的別名不同的話,可通過此變量設置.
?
ansible_ssh_port
ssh端口號.如果不是默認的端口號,通過此變量設置.
?
ansible_ssh_user
默認的 ssh 用戶名
?
ansible_ssh_pass
ssh 密碼(這種方式并不安全,我們強烈建議使用 --ask-pass 或 SSH 密鑰)
?
ansible_sudo_pass
sudo 密碼(這種方式并不安全,我們強烈建議使用 --ask-sudo-pass)
?
ansible_sudo_exe (new in version 1.8)
sudo 命令路徑(適用于1.8及以上版本)
?
ansible_connection
與主機的連接類型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默認使用 paramiko.1.2 以后默認使用 'smart','smart' 方式會根據是否支持 ControlPersist, 來判斷'ssh' 方式是否可行.
?
ansible_ssh_private_key_file
ssh 使用的私鑰文件.適用于有多個密鑰,而你不想使用 SSH 代理的情況.
?
ansible_shell_type
目標系統的shell類型.默認情況下,命令的執行使用 'sh' 語法,可設置為 'csh' 或 'zsh'.
?
ansible_python_interpreter
目標主機的 python 路徑.適用于的情況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",比如 \*BSD, 或者 /usr/bin/python
不是 2.X 版本的 Python.我們不使用 "/usr/bin/env" 機制,因為這要求遠程用戶的路徑設置正確,且要求 "python" 可執行程序名不可為 python以外的名字(實際有可能名為python26).
?
與 ansible_python_interpreter 的工作方式相同,可設定如 ruby 或 perl 的路徑....