ansible 2.8 接口 python调用执行命令

本文介绍了一种基于Ansible 2.8版本的自动化部署方案,通过自定义接口调用和参数传递,实现对远程主机的批量管理和任务执行。重点展示了如何通过Python脚本动态创建Ansible inventory,设置变量,并自定义回调函数来处理执行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:根据ansible2.8官方提供的接口,做了以下调整,可以加参数

例如:请求的参数是:{"fork":"5","hosts":[{"group":"aa","ip":"192.168.100.3","port":"22","vars":{"ansible_ssh_user":"root","ansible_ssh_pass":"123456"}}],"modules":"shell","args_list":"df -h"}

#!/usr/bin/env python
#encoding=utf-8

import json
import shutil,requests
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

#重写callback
class ResultCallback(CallbackBase):
    def call_message(self,ip,message):
        #将执行结果通过接口返回给server服务器
	url = 'http://192.168.100.2/ansible/showstatus/?ip=%s&message=%s' % (ip,message)
	text = requests.get(url)
        #执行的结果正常
    def v2_runner_on_ok(self, result, **kwargs):
        host = result._host
        self.call_message(host.name,result._result['stdout'])
	print(host.name,result._result['stdout'])
        print json.dumps({"hostname":host.name,"result":result._result['stdout']}, indent=4)
    #主机不可达
    def v2_runner_on_unreachable(self, result):
        host = result._host.get_name()
	self.call_message(host,result._result['msg'])
        print json.dumps({"hostname":host,"result":result._result['msg']}, indent=4)
    #执行失败
    def v2_runner_on_failed(self, result, ignore_errors=False):
        host = result._host.get_name()
	self.call_message(host,result._result['msg'])
        print json.dumps({"hostname":host,"result":result._result['msg']}, indent=4)



def operate(hosts):

    fork = hosts["fork"]
    context.CLIARGS = ImmutableDict(connection='ssh', module_path='/path/to/mymodules', forks=fork, become=None,
                      become_method=None,
                      become_user=None, check=False, diff=False)

    passwords = dict(vault_pass='www')

    results_callback = ResultCallback()
    loader = DataLoader()

    inventory = InventoryManager(loader)
    for host in hosts["hosts"]:
        try:
            if host["group"] not in inventory.get_groups_dict()["group"]:
            	inventory.add_group(host["group"])
	        inventory.add_host(host["ip"], group=host["group"], port=host["port"])
        except:
            inventory.add_group(host["group"])
            inventory.add_host(host["ip"], group=host["group"], port=host["port"])
    
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    groups = []
    for host in hosts["hosts"]:
        groups.append(host["group"])
        ip = inventory.get_host(host["ip"])
        for key in host["vars"]:
            variable_manager.set_host_variable(ip, key, host["vars"][key])

    play_source = dict(
        name="Test",
        hosts=groups,
        gather_facts='no',
        tasks=[
            dict(action=dict(module=hosts["modules"], args=hosts["args_list"]),register='shell_out'),
	    #dict(action=dict(module='shell', args='ls'), 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,
            passwords=passwords,
            stdout_callback=results_callback,
        )
        result=tqm.run(play)

    finally:
        if tqm is not None:
            tqm.cleanup()

	shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
hosts = {
    'fork':'5',
    'hosts':[
    {
        'group':'aa',
        'ip':'192.168.100.3',
        'port':'22',
        'vars':{
            'ansible_ssh_user':'root',
            'ansible_ssh_pass':'123456'
        }
    }],
    'modules':'shell',
    'args_list':'df -h'
}


operate(hosts)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值