1. 程式人生 > >Ansible API 2.0的測試

Ansible API 2.0的測試

default roo ges ria toolbar bsp ict eve uem

因項目需要使用到ansible api,根據修改官方文檔提供的使用範例,經過多次測試,現將能用的代碼分享給大家,大家只需根據自己的實際環境修改該代碼即可。

官方文檔:http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html#python-api-2-0


#coding:utf-8
import json
from collections import namedtuple
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

class ResultCallback(CallbackBase):
    def v2_runner_on_ok(self, result, **kwargs):
        host = result._host
        print(json.dumps({host.name: result._result}, indent=4))


# 初始化需要的對象
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])

# module_path參數指定本地ansible模塊包的路徑
loader = DataLoader()
options = Options(connection='smart', module_path='/usr/lib/python2.7/dist-packages/ansible/modules', forks=5, become=None, become_method=None, become_user="root", check=False, diff=False)
passwords = dict(vault_pass='secret')

# 實例化ResultCallback來處理結果
results_callback = ResultCallback()

# 創建庫存(inventory)並傳遞給VariableManager
inventory = InventoryManager(loader=loader, sources=['../conf/hosts']) #../conf/hosts是定義hosts
variable_manager = VariableManager(loader=loader, inventory=inventory)

# 創建任務
play_source =  dict(
        name = "Ansible Play",
        hosts = "cephnode",
        gather_facts = 'no',
        tasks = [
            dict(action=dict(module='shell', args='touch /tmp/7.txt'), register='shell_out'), #定義一條任務,如有多條任務也應按照這樣的方式定義
         ]
    )
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=passwords,
              stdout_callback=results_callback,  # 使用自定義回調代替“default”回調插件(如不需要stdout_callback參數則按照默認的方式輸出)
          )
    result = tqm.run(play)
finally:
    if tqm is not None:
        tqm.cleanup()


我的../conf/hosts文件內容如下:

[cephnode]
192.168.89.136


註意:

如沒有明確指定inventory(如下的參數),那麽會默認從/etc/ansible/hosts中讀取hosts

sources=['../conf/hosts']


補充一下,剛說了定義多條任務的方式,舉個例子:

tasks = [
            dict(action=dict(module='shell', args='mkdir /tmp/toby'), register='shell_out'), #首先創建目錄
            dict(action=dict(module='copy', args='src=/tmp/abc123.txt dest=/tmp/toby'), register='shell_out') #然後將本地的abc123.txt通過copy模塊下發到目標主機的/tmp/toby/目錄下
         ]



Ansible API 2.0的測試