Loading

ansibleplaybook api

#!/usr/bin/env python
# coding=utf-8
import os
import time

from ansible import context
from ansible.cli import CLI
from ansible.module_utils.common.collections import ImmutableDict
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager


class AnsibleDh(object):
    def __init__(self, hostsFile="ansible-hosts"):
        self.hostsFile = hostsFile
        self.empty_file()

    def empty_file(self):
        """
        清空ansible hosts文件
        :return: None
        """
        if os.path.exists(self.hostsFile):
            os.remove(self.hostsFile)

    def add_host(self, lineContenet):
        """
        把配置内容(一台主机信息)追加写入ansible hosts文件中
        :param lineContenet: ansible hosts的一行内容
        :return: None
        """
        with open(self.hostsFile, encoding="utf-8", mode="a") as f:
            f.write(lineContenet)

    def cmd_palybook(self, playbook):
        """
        执行剧本
        :param playbook: playbook绝对路径
        :return:
        """
        loader = DataLoader()
        context.CLIARGS = ImmutableDict(tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False,
                                        connection='ssh', module_path=None, forks=100, remote_user='root',
                                        private_key_file=None, ssh_common_args='-o StrictHostKeyChecking=no',
                                        ssh_extra_args='-o StrictHostKeyChecking=no', sftp_extra_args=None,
                                        scp_extra_args=None, become=True, become_method='sudo', become_user='root',
                                        verbosity=True, check=False, start_at_task=None)
        inventory = InventoryManager(loader=loader, sources=(self.hostsFile,))
        variableManager = VariableManager(loader=loader, inventory=inventory,
                                           version_info=CLI.version_info(gitinfo=False))

        try:
            pbExec = PlaybookExecutor(playbooks=[playbook], inventory=inventory,
                                    variable_manager=variableManager, loader=loader, passwords={})
            res = pbExec.run()
        except Exception as error:
            print("[错误] Playbook执行异常")
            print(error)
        else:
            # 备份ansible hosts文件
            now = time.strftime("%Y%m%d-%H:%M:%S", time.localtime())
            os.rename(self.hostsFile, self.hostsFile + '-' + now)


if __name__ == '__main__':
    print('ok')

 

posted @ 2023-11-07 09:26  wsongl  阅读(29)  评论(0编辑  收藏  举报