python ansible使用(1)ansible-api

本文介绍了如何利用Python与Ansible的API进行交互,实现自动化运维任务。内容包括设置环境、导入Ansible模块、执行 playbook 和任务、处理结果等关键步骤,旨在帮助开发者更高效地进行系统管理。
摘要由CSDN通过智能技术生成

python2.7.5   ansible==2.7.0
# -*- coding:utf8 -*-

import os
import sys
import logging

# from collections import namedtuple
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.inventory.host import Host
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase

import public, constant


logger = logging.getLogger(__name__)



def writeFile(filename,s_body,mode='w+'):
    """
    写入文件内容
    @filename 文件名
    @s_body 欲写入的内容
    return bool 若文件不存在则尝试自动创建
    """
    try:
        fp = open(filename, mode)
        fp.write(s_body)
        fp.close()
        return True
    except:
        try:
            fp = open(filename, mode, encoding="utf-8")
            fp.write(s_body)
            fp.close()
            return True
        except:
            return False


def playbook_logs(result, _type="", log_file=None):
    """ResultsCallback 返回的日志解析"""

    if not log_file:
        log_file = os.path.join(os.getcwd(), "logs/ansible_playbooks.log")

    print("|--------playbook_logs-----_type:{}--log_file:{}".format(_type, log_file))
    _dict = result.__dict__
    try:
        print("|---------------_dict:{}".format(_dict))
        host = _dict["_host"]
        task = _dict["_task"]
        msg = "{}  HOST:{}   {}   status:{} ********************************\n".format(public.str_date_time(), host, task, _type)
        writeFile(log_file, msg, mode="a")
        writeFile(log_file, "{}\n\n".format(_dict), mode="a")
    except Exception as ex:
        print("|-------playbook_logs--Exception--error:{}".format(ex))
        str_log = "\nerror:{}\n----result.__dict__----\n{}\n".format(ex, _dict)
        logger.info(str_log)


class Options(object):
    def __init__(self, verbosity=10, inventory=None, listhosts=None, subset=None,
                 module_paths=None, extra_vars=None, forks=20, ask_vault_pass=None,
                 vault_password_files=None, new_vault_password_file=None, output_file=None,
                 tags=None, skip_tags=None, one_line=None, tree=None, ask_sudo_pass=None,
                 ask_su_pass=None, sudo=None, sudo_user=None, become=None, become_method=None,
                 become_user=None, become_ask_pass=None, ask_pass=None, private_key_file=None,
                 remote_user=None, connection='smart', timeout=5, ssh_common_args=None,
                 sftp_extra_args=None, scp_extra_args=None, ssh_extra_args=None, poll_interval=None,
                 seconds=None, check=None, syntax=None, diff=None, force_handlers=None,
                 flush_cache=None, listtasks=None, listtags=None, module_path=None):
        self.verbosity = verbosity
        self.inventory = inventory
        self.listhosts = listhosts
        self.subset = subset
        self.module_paths = module_paths
        self.extra_vars = extra_vars
        self.forks = forks
        self.ask_vault_pass = ask_vault_pass
        self.vault_password_files = vault_password_files
        self.new_vault_password_file = new_vault_password_file
        self.output_file = output_file
        self.one_line = one_line
        self.tree = tree
        self.ask_sudo_pass = ask_sudo_pass
        self.ask_su_pass = ask_su_pass
        self.sudo = sudo
        self.sudo_user = sudo_user
        self.become = become
        self.become_method = become_method
        self.become_user = become_user
        self.become_ask_pass = become_ask_pass
        self.ask_pass = ask_pass
        self.private_key_file = private_key_file
        self.remote_user = remote_user
        # self.remote_port = remote_port
        self.connection = connection
        self.timeout = timeout
        self.ssh_common_args = ssh_common_args
        self.sftp_extra_args = sftp_extra_args
        self.scp_extra_args = scp_extra_args
        self.ssh_extra_args = ssh_extra_args
        self.poll_interval = poll_interval
        self.seconds = seconds
        self.check = check
        self.syntax = syntax
        self.diff = diff
        self.force_handlers = force_handlers
        self.flush_cache = flush_cache
        self.listtasks = listtasks
        self.listtags = listtags
        self.module_path = module_path
        self.log_path = "/var/log/ansible.log"


class ResultsCallback(CallbackBase):
    '''
    Callback the result of execute AdHoc and playbook
    '''

    def __init__(self, log_type=None, *args, **kwargs):
        super(ResultsCallback, self).__init__(*args, **kwargs)
        self.host_ok = {}
        self.host_unreachable = {}
        self.host_failed = {}
        # 日志分类,指定日志文件;(ip/组件安装日志)
        self.log_type = log_type

    def log_file_abs(self, result):
        """ ansible日志输入分类
         ../logs/{ip}/ansible_{srv}.log
         ../logs/ansible_playbooks.log
         ../logs/ansible_{uuid}.log
        ""&#
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值