Python呼叫ansible API系列(二)執行adhoc和playbook

昀溪發表於2019-04-09

執行adhoc

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import namedtuple
# 核心類
# 用於讀取YAML和JSON格式的檔案
from ansible.parsing.dataloader import DataLoader
# 用於儲存各類變數資訊
from ansible.vars.manager import VariableManager
# 用於匯入資產檔案
from ansible.inventory.manager import InventoryManager
# 操作單個主機資訊
from ansible.inventory.host import Host
# 操作單個主機組資訊
from ansible.inventory.group import Group
# 儲存執行hosts的角色資訊
from ansible.playbook.play import Play
# ansible底層用到的任務佇列
from ansible.executor.task_queue_manager import TaskQueueManager
# 核心類執行playbook
from ansible.executor.playbook_executor import PlaybookExecutor


def adhoc():
    """
    ad-hoc 呼叫
    資產配置資訊  這個是透過 InventoryManager和VariableManager 定義
    執行選項 這個是透過namedtuple來定義
    執行物件和模組 透過dict()來定義
    定義play 透過Play來定義
    最後透過 TaskQueueManager 的例項來執行play
    :return:
    """
    # 資產配置資訊
    dl = DataLoader()
    im = InventoryManager(loader=dl, sources=["hosts"])
    vm = VariableManager(loader=dl, inventory=im)
    # 執行選項,這個類不是ansible的類,這個的功能就是為了構造引數
    Options = namedtuple("Options", [
        "connection", "remote_user", "ask_sudo_pass", "verbosity", "ack_pass",
        "module_path", "forks", "become", "become_method", "become_user", "check",
        "listhosts", "listtasks", "listtags", "syntax", "sudo_user", "sudo", "diff"
    ])
    """
    這裡就是Options的例項,然後你就可以賦值,這個為了給ansible設定執行選項 ansibile 172.16.48.171 -m shell -a 'ls /tmp' -f 5
    這裡的選項就是ansible命令中 -f -C -D -m等執行選項
    """
    options = Options(connection='smart', remote_user=None, ack_pass=None, sudo_user=None, forks=5, sudo=None, ask_sudo_pass=False,
                      verbosity=5, module_path=None, become=None, become_method=None, become_user=None, check=False, diff=False,
                      listhosts=None, listtasks=None, listtags=None, syntax=None)
    # play的執行物件和模組,這裡設定hosts,其實是因為play把play_source和資產資訊關聯後,執行的play的時候它會去資產資訊中設定的sources的hosts檔案中
    # 找你在play_source中設定的hosts是否在資產管理類裡面。
    play_source = dict(name="Ansible Play",  # 任務名稱
                       hosts="172.16.48.242",  # 目標主機,可以填寫具體主機也可以是主機組名稱
                       gather_facts="no",  # 是否收集配置資訊

                       # tasks是具體執行的任務,列表形式,每個具體任務都是一個字典
                       tasks=[
                           dict(action=dict(module="shell", args="ls /tmp"))
                       ])
    # 定義play
    play = Play().load(play_source, variable_manager=vm, loader=dl)

    passwords = dict()  # 這個可以為空,因為在hosts檔案中
    #
    tqm = TaskQueueManager(
        inventory=im,
        variable_manager=vm,
        loader=dl,
        options=options,
        passwords=passwords,
    )
    result = tqm.run(play)
    print(result)


def main():
    adhoc()


if __name__ == "__main__":
    try:
        main()
    finally:
        sys.exit()

執行playbook

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import namedtuple
# 核心類
# 用於讀取YAML和JSON格式的檔案
from ansible.parsing.dataloader import DataLoader
# 用於儲存各類變數資訊
from ansible.vars.manager import VariableManager
# 用於匯入資產檔案
from ansible.inventory.manager import InventoryManager
# 操作單個主機資訊
from ansible.inventory.host import Host
# 操作單個主機組資訊
from ansible.inventory.group import Group
# 儲存執行hosts的角色資訊
from ansible.playbook.play import Play
# ansible底層用到的任務佇列
from ansible.executor.task_queue_manager import TaskQueueManager
# 核心類執行playbook
from ansible.executor.playbook_executor import PlaybookExecutor


def execplaybook():
    """
    呼叫 playbook
    呼叫playboo大致和呼叫ad-hoc相同,只是真正呼叫的是使用PlaybookExecutor
    :return:
    """
    # 資產配置資訊
    dl = DataLoader()
    im = InventoryManager(loader=dl, sources=["hosts"])
    vm = VariableManager(loader=dl, inventory=im)
    # 執行選項,這個類不是ansible的類,這個的功能就是為了構造引數
    Options = namedtuple("Options", [
        "connection", "remote_user", "ask_sudo_pass", "verbosity", "ack_pass",
        "module_path", "forks", "become", "become_method", "become_user", "check",
        "listhosts", "listtasks", "listtags", "syntax", "sudo_user", "sudo", "diff"
    ])
    """
    這裡就是Options的例項,然後你就可以賦值,這個為了給ansible設定執行選項 ansibile 172.16.48.171 -m shell -a 'ls /tmp' -f 5
    這裡的選項就是ansible命令中 -f -C -D -m等執行選項
    """
    options = Options(connection='smart', remote_user=None, ack_pass=None, sudo_user=None, forks=5, sudo=None,
                      ask_sudo_pass=False,
                      verbosity=5, module_path=None, become=None, become_method=None, become_user=None, check=False,
                      diff=False,
                      listhosts=None, listtasks=None, listtags=None, syntax=None)
    passwords = dict()  # 這個可以為空,因為在hosts檔案中
    #
    try:
        # playbooks引數裡面放的就是playbook檔案路徑
        playbook = PlaybookExecutor(playbooks=["f1.yml"], inventory=im, variable_manager=vm, loader=dl, options=options, passwords=passwords)
        playbook.run()
    except Exception as err:
        print(err)


def main():
    execplaybook()

if __name__ == "__main__":
    try:
        main()
    finally:
        sys.exit()

下圖為f1.yml

相關文章