ansible API 常用模块
常用模块
用于读取yaml,json格式的文件
from ansible.parsing.dataloader import DataLoader
#用于管理变量的类,包括主机,组,扩展等变量
from ansible.vars.manager import VariableManager
#用于创建和管理inventory,倒入inventory文件
from ansible.inventory.manager import InventoryManager
#ad-hoc 存储着角色列表,任务,处理代码块
from ansible.playbook.play import Play
#ad-hoc ansible底层用到的任务队列
from ansible.executor.task_queue_manager import TaskQueueManager
#回调基类,用来定义回调事件,比如返回失败成功等信息
from ansible.plugins.callback import CallbackBase
#执行playbook
from ansible.executor.playbook_executor import PlaybookExecutor
#操作单个主机
from ansible.inventory import host
#操作单个主机组
from ansible.inventory import group
InventoryManager
#实例化需要两个参数
"参数一为读取yml文件的信息,需要实例化 DataLoader"
"参数二为读取从那个位置读取资产配置文件,多个可逗号分割"
intertory = InventoryManager(loader='',sources='')
#以字典的方式打印出主机和主机组相关信息
intertory.get_group_dict()
#获取所有的主机
inventory.get_hosts()
#添加主机到指定主机组
"参数一指定主机地址"
"参数二指定主机端口"
"参数三指定主机群组,必须存在的群组"
inventory.add_host(host='1.1.1.1',port=2222,group='web_server')
#获取指定的主机对象
inventory.get_host(hostname='1.1.1.1')
VariableManager
#实例化需要两个参数
"参数一为读取yml文件的信息,需要实例化 DataLoader"
"参数二为资产管理配置变量"
variable = VariableManager(loader=loader,inventory=inventory)
#获取变量
variable.get_vars()
# 查看指定主机的详细变量信息
"传入的host是inventory.get_host获得的主机对象"
host = inventory.get_host(hostname='1.1.1.1')
host_vars = variable.get_vars(host=host)
#设置主机变量方法
"传入的host是inventory.get_host获得的主机对象"
host = inventory.get_host(hostname='1.1.1.1')
variable.set_host_variable(host=host,varname='ansible_ssh_pass',value='')
#添加扩展变量
"参数是一个字典多个逗号分割"
variable.extra_vars={'devops':'best'}
基于CMDB接口返回主机&主机信息进行动态执行
#!/usr/bin/env python
# -*- coding:utf-8 -*- import json
import sys
import os
import django
sys.path.append('../../')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "automation_ansible_api.settings")
django.setup()
from assets.models import Group def Group_list():
'''
这个函数的目的是获取所有主机以及群组的相关信息,必须是json格式,格式如下
{
"Devops": {
"hosts": [
"172.20.35.177",
"172.20.35.16",
"106.14.154.11",
"139.196.90.14",
"140.143.191.129"
]
}
}
'''
result = {}
groups = Group.objects.all() #主机组的所有名字,多对多关系这里能反向查找出来
for i in groups:
if i.host_set.all():
result[i.name] = {'hosts':[]}
for x in i.host_set.all():
result[i.name]['hosts'].append(x.ip_address)
print(json.dumps(result,indent=4)) def Host_list(ip):
'''
这个函数目的是存储一些变量,inventory的一些参数比如执行的用户,密码,端口等等,可返回空,根据自身需求
{
"ansible_ssh_host": "172.20.35.177",
"ansible_ssh_user": "root"
}
'''
print(json.dumps({
"ansible_ssh_host": ip,
"ansible_ssh_user": "root"},indent=4)) if __name__ == '__main__':
'''
一下两个参数必须存在,这个是用于ansible去执行和发现的!
'''
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
Group_list()
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
Host_list(sys.argv[2])
ansible-api调用执行
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from ansible.plugins.callback import CallbackBase
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 collections import namedtuple
#实例化解析yml
loader = DataLoader()
#实例化资产管理
'''
2.4+的inventory必须有sources参数,参数路径为动态执行的那个脚本!这里很坑我研究了一天!
'''
inventory = InventoryManager(loader=loader,sources='hosts')
#实例化变量管理
variable_manager = VariableManager(loader=loader,inventory=inventory)
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 = 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_source = dict(
'''
hosts为执行的主机或者群组!
'''
name = "Ansible Play ad-hoc test",
hosts = '139.196.90.14',
gather_facts = 'no',
tasks = [
dict(action=dict(module='ping', args='')),
# dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader) class ModelResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ModelResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result
def v2_runner_on_ok(self, result):
self.host_ok[result._host.get_name()] = result
def v2_runner_on_failed(self, result):
self.host_failed[result._host.get_name()] = result
callback = ModelResultsCollector()
passwords = dict()
# 传入自定义的callback
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=callback,
)
result = tqm.run(play)
# 自定义格式化输出,执行结果数据在result对象的_result属性里
result_raw = {'success':{},'failed':{},'unreachable':{}}
for host,result in callback.host_ok.items():
result_raw['success'][host] = result._result
for host,result in callback.host_failed.items():
result_raw['failed'][host] = result._result print(json.dumps(result_raw,indent=4))
ansible API 常用模块的更多相关文章
- ansible api常用模块与参数
###ansibleAPI 常用模块 用于读取yaml,json格式的文件 from ansible.parsing.dataloader import DataLoader #用于管理变量的类,包括 ...
- ansible中常用模块详解
ansible中常用的模块详解: file模块 ansible内置的可以查看模块用法的命令如下: [root@docker5 ~]# ansible-doc -s file - name: Sets ...
- Ansible之常用模块(一)
ansible之所以功能强大,不是ansible本身,是因为它有众多的模块,前文我们介绍了ansible的基础介绍,系列命令的用法以及选项的说明,通过前文的学习我们知道了ansible是基于pytho ...
- ansible 四常用模块
常用模块 Ansible默认提供了很多模块来供我们使用.在Linux中,我们可以通过 ansible-doc -l 命令查看到当前Ansible支持哪些模块,通过 ansible-doc -s [模块 ...
- ansible 003 常用模块
常用模块 file 模块 管理被控端文件 回显为绿色则,未变更,符合要求 黄色则改变 红色则报错 因为默认值为file,那么文件不存在,报错 改为touch则创建 将state改为directory变 ...
- Ansible Playbooks 常用模块
官网链接:https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html ansible python module ...
- ansible小结常用模块
根据官方的分类,将模块按功能分类为:云模块.命令模块.数据库模块.文件模块.资产模块.消息模块.监控模块.网络模块.通知模块.包管理模块.源码控制模块.系统模块.单元模块.web设施模块.window ...
- Ansible之常用模块(二)
1.hostname:此模块的主要作用是管理远端节点主机名 模块帮助: root@localhost ~]# ansible-doc -s hostname - name: Manage hostna ...
- Ansible之常用模块介绍
环境 ansible HOST-PATTERN -m MOD_NAME -a MOD_ARGS -C -f forks ssh-keygen -t rsa -P "" ssh-co ...
随机推荐
- [转帖]postgresql查看用户连接以及杀死连接的会话
postgresql查看用户连接以及杀死连接的会话 2017年10月11日 15:21:18 DB_su 阅读数 8908更多 分类专栏: postgresql 版权声明:本文为博主原创文章,遵循 ...
- go 计算 MD5
Golang的加密库都放在crypto目录下,其中MD5库在crypto/md5包中,该包主要提供了New和Sum函数 直接调用md5计算 package main import ( "cr ...
- oracle父子级查询数据树结构
select t.*, level , sys_connect_by_path (t .id, '-->') as tree from isc_res_res_r t connect by pr ...
- Symfony 服务配置 看这一篇就够了
对于刚接触 Symfony 的新手来说,如何配置服务是一件很困难的事情.虽然在 Symfony 的新版本的框架中加入了自动加载(autowire),基本上满足了一般的需求,但是如果你想深入了解“服务” ...
- Python基础 第三章 使用字符串(3)字符串方法&本章小结
字符串的方法非常之多,重点学习一些最有用的,完整的字符串方法参见<Python基础教程(第三版)>附录B. 模块string,虽然风头已小,但其包含了一些字符串方法中没有的常量和函数,故将 ...
- opencv实现人脸识别(三) 训练图片模块
现在我们已经拍好了需要训练的图片,接下来就是进行训练 流程图: 我们在这里用到了numpy库,NumPy是一个功能强大的Python库,主要用于对多维数组执行计算. 使用numpy的目的是减少pyth ...
- 关于@service、@controller和@transactional 在spring中的位置说明
Spring容器优先加载由ServletContextListener(对应applicationContext.xml)产生的父容器,而SpringMVC(对应mvc_dispatcher_serv ...
- maven中添加memcached.jar配置方法
一.java memcached client的jar包下载地址:https://github.com/gwhalin/Memcached-Java-Client/downloads 二.cd jav ...
- TCP协议探究(一):报文格式与连接建立终止
一 TCP:传输控制协议报文格式 1 TCP服务 提供面向连接.可靠的字节流服务 面向连接意味着两方通信,不支持多播和广播 可靠性的支持: 应用数据被分割成TCP认为最适合发送的数据块.由TCP传递给 ...
- MyEclipse中XML的智能提示和关于Spring 配置文件头的一些记录和解释
一. 首先介绍XML文件的一些知识: <?xml version="1.0" encoding="UTF-8"?><beans xmlns ...