如何利用ansible callback插件对执行结果进行解析
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何利用ansible callback插件对执行结果进行解析相关的知识,希望对你有一定的参考价值。
参考技术A Adhocadhoc 其实执行 Ansible 模块, 通 adhoc 我便快捷完些临运维操作.
2.0 前调用
import ansible.runner
import json
runner = ansible.runner.Runner(
module_name='ping', # 模块名
module_args='', # 模块参数
pattern='all', # 目标机器pattern
forks=10
)
datastructure = runner.run()
data = json.dumps(datastructure,indent=4)
加载默认 inventory
想使用 inventory 文件或者想使用态 inventory, 则使用 host_list 参数代替
import ansible.runner
import json
runner = ansible.runner.Runner(
host_list=["10.10.0.1"], # 明确指定主机需要传递列表, 或者指定态inventory脚本
module_name='ping', # 模块名
module_args='', # 模块参数
extra_vars="ansible_ssh_user":"root","ansible_ssh_pass":"xx",
forks=10
)
datastructure = runner.run()
data = json.dumps(datastructure,indent=4)
2.0 调用
import json
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
loader = DataLoader() # 用加载解析yaml文件或JSON内容,并且支持vault解密
variable_manager = VariableManager() # 管理变量类,包括主机,组,扩展等变量,前版本 inventory
inventory = Inventory(loader=loader, variable_manager=variable_manager)
variable_manager.set_inventory(inventory) # 根据 inventory 加载应变量
class Options(object):
'''
公共类,ad-hocplaybook都需要options参数
并且所需要拥同属性,部属性都返None或False
用类省初始化堆空值属性
'''
def __init__(self):
self.connection = "local"
self.forks = 1
self.check = False
def __getattr__(self, name):
return None
options = Options()
def run_adhoc():
variable_manager.extra_vars="ansible_ssh_user":"root" , "ansible_ssh_pass":"xxx" # 增加外部变量
# 构建pb, 意思, 新版本运行ad-hoc或playbook都需要构建pb, 调用play类
# :param name: 任务名,类似playbooktasksname
# :param hosts: playbookhosts
# :param tasks: playbooktasks, 其实playbook语, tasks值列表,写入task
play_source = "name":"Ansible Ad-Hoc","hosts":"10.10.0.1","gather_facts":"no","tasks":["action":"module":"shell","args":"w"]
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=None,
stdout_callback='minimal',
run_tree=False,
)
result = tqm.run(play)
print result
finally:
if tqm is not None:
tqm.cleanup()
if __name__ == '__main__':
run_adhoc()
Playbook
playbook 则类似于 SaltStack state
2.0 前调用
from ansible import callbacks
from ansible import utils
from ansible.playbook import PlayBook
stats = callbacks.AggregateStats()
callback = callbacks.PlaybookCallbacks()
runner_callbacks = callbacks.PlaybookRunnerCallbacks(stats)
pb = ansible.playbook.PlayBook(
playbook="tasks.yml",
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
check=True
)
pb.run()
2.0 调用
import json
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
loader = DataLoader() # 用加载解析yaml文件或JSON内容,并且支持vault解密
variable_manager = VariableManager() # 管理变量类,包括主机,组,扩展等变量,前版本 inventory
inventory = Inventory(loader=loader, variable_manager=variable_manager)
variable_manager.set_inventory(inventory) # 根据 inventory 加载应变量
class Options(object):
'''
公共类,ad-hocplaybook都需要options参数
并且所需要拥同属性,部属性都返None或False
用类省初始化堆空值属性
'''
def __init__(self):
self.connection = "local"
self.forks = 1
self.check = False
def __getattr__(self, name):
return None
options = Options()
def run_playbook():
playbooks=['task.yaml'] # 列表, 运行playbook
variable_manager.extra_vars="ansible_ssh_user":"root" , "ansible_ssh_pass":"xxx" # 增加外部变量
pb = PlaybookExecutor(playbooks=playbooks, inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=None)
result = pb.run()
print result
if __name__ == '__main__':
run_playbook()本回答被提问者采纳
ansible plugins简介
ansible插件是增强ansible的核心功能的代码片段,ansible使用插件架构来实现丰富,灵活和可扩展的功能集。
Ansible提供了许多方便的插件,您可以轻松编写自己的插件。
下边简单介绍Ansible包含的各种插件(插件具体用法请参考官方文档或者ansible-doc):
1、action插件
Action插件与模块一起执行PlayBook任务所需的操作。它们通常在后台自动执行,在模块执行之前进行必要的工作。
“normal” action插件 用于尚未拥有action插件的模块。
您可以启用一个自定义操作插件,方法是将其放置到与role中的play相邻的action_plugins目录中,
当使用关联模块时,Action插件默认执行;不需要采取任何行动
2、cache插件
缓存插件实现的后端缓存机制,可以使ansible存储获得的facts和inventory元数据,不必再从源头检索这些数据,而降低性能。
默认的缓存插件是memory plugin,它只缓存ansible目前执行的数据,其他持久存储的插件也可以缓存数据
3、callback插件
回调插件可以在响应事件时向Ansible添加新行为。
默认情况下,回调插件控制运行命令行程序时看到的大部分输出,
但也可用于添加其他输出,与其他工具集成并将事件整理到存储后端。
- actionable - shows only items that need attention
- context_demo - demo callback that adds play/task context
- debug - formated stdout/stderr display
- default - default Ansible screen output
- dense - minimal stdout output
- foreman - Sends events to Foreman
- full_skip - suppresses tasks if all hosts skipped
- hipchat - post task events to hipchat
- jabber - post task events to a jabber server
- json - Ansible screen output as JSON
- junit - write playbook output to a JUnit file.
- log_plays - write playbook output to log file
- logentries - Sends events to Logentries
- logstash - Sends events to Logstash
- mail - Sends failure events via email
- minimal - minimal Ansible screen output
- null - Don’t display stuff to screen
- oneline - oneline Ansible screen output
- osx_say - oneline Ansible screen output
- profile_roles - adds timing information to roles
- profile_tasks - adds time information to tasks
- selective - only print certain tasks
- skippy - Ansible screen output that ignores skipped status
- slack - Sends play events to a Slack channel
- stderr - Splits output, sending failed tasks to stderr
- syslog_json - sends JSON events to syslog
- timer - Adds time to play stats
- tree - Save host events to files
- unixy - condensed Ansible output
- yaml - yaml-ized Ansible screen output
4、inventory插件
清单插件允许用户指向数据源,以便通过-i /path/to/file和/ 或-i ‘host1,host2 命令行参数
或其他配置来源编译Ansible用于定位任务的主机清单。
个人觉得ini最好用
- advanced_host_list - Parses a ‘host list’ with ranges
- auto - Loads and executes an inventory plugin specified in a YAML config
- aws_ec2 - ec2 inventory source
- constructed - Uses Jinja2 to construct vars and groups based on existing inventory.
- host_list - Parses a ‘host list’ string
- ini - Uses an Ansible INI file as inventory source.
- k8s - Kubernetes (K8s) inventory source
- openshift - OpenShift inventory source
- openstack - OpenStack inventory source
- script - Executes an inventory script that returns JSON
- virtualbox - virtualbox inventory source
- yaml - Uses a specifically YAML file as inventory source.
5、lookup插件
查找插件允许Ansible从外部来源访问数据。这可以包括:联系外部数据存储和服务,读取文件系统。
查找插件返回的数据可以使用Ansible中的标准模板系统提供,通常用于从这些系统中加载包含信息的变量或模板。
lookups是Jinja2模板语言的Ansible特定扩展。
- aws_account_attribute - Look up AWS account attributes.
- aws_service_ip_ranges - Look up the IP ranges for services provided in AWS such as EC2 and S3.
- aws_ssm - Get the value for a SSM parameter or all parameters under a path.
- cartesian - returns the cartesian product of lists
- chef_databag - fetches data from a Chef Databag
- config - Lookup current Ansilbe configuration values
- conjur_variable - Fetch credentials from CyberArk Conjur.
- consul_kv - Fetch metadata from a Consul key value store.
- credstash - retrieve secrets from Credstash on AWS
- csvfile - read data from a TSV or CSV file
- cyberarkpassword - get secrets from CyberArk AIM
- dict - returns key/value pair items from dictionaries
- dig - query DNS using the dnspython library
- dnstxt - query a domain(s)’s DNS txt fields
- env - read the value of environment variables
- etcd - get info from etcd server
- file - read file contents
- fileglob - list files matching a pattern
- filetree - recursively match all files in a directory tree
- first_found - return first file found from list
- flattened - return single list completely flattened
- hashi_vault - retrieve secrets from HasihCorp’s vault
- hiera - get info from hiera data
- indexed_items - rewrites lists to return ‘indexed items’
- ini - read data from a ini file
- inventory_hostnames - list of inventory hosts matching a host pattern
- items - list of items
- k8s - Query the K8s API
- keyring - grab secrets from the OS keyring
- lastpass - fetch data from lastpass
- lines - read lines from command
- list - simply returns what it is given.
- mongodb - lookup info from MongoDB
- nested - composes a list with nested elements of other lists
- nios - Query Infoblox NIOS objects
- nios_next_ip - Return the next available IP address for a network
- openshift - Query the OpenShift API
- password - retrieve or generate a random password, stored in a file
- passwordstore - manage passwords with passwordstore.org’s pass utility
- pipe - read output from a command
- random_choice - return random element from list
- redis - fetch data from Redis
- redis_kv - fetch data from Redis
- sequence - generate a list based on a number sequence
- shelvefile - read keys from Python shelve file
- subelements - traverse nested key from a list of dictionaries
- template - retrieve contents of file after templating with Jinja2
- together - merges lists into syncronized list
- url - return contents from URL
- vars - Lookup templated value of variables
6、shell插件
Shell插件可以确保Ansible运行的基本命令格式正确,可与目标机器一起使用,并允许用户配置某些与Ansible执行任务相关的行为
7、strategy插件
策略插件通过处理play和hosts调度 来控制play执行的流程。
8、vars插件
Vars插件将额外的变量注入到Ansible中运行,这些运行不是来自库存源,剧本或命令行。
Playbook使用vars插件构建像‘host_vars‘和‘group_vars‘的工作目录。
Vars插件在Ansible 2.0中部分实现,并被重写为从Ansible 2.4开始全面实施。
Ansible附带的host_group_vars插件可以从主机变量和组变量中读取变量。
9、filters
Ansible中的过滤器来自Jinja2,用于转换模板表达式中的数据。
Jinja2附带很多过滤器。请参阅官方Jinja2模板文档中的内置过滤器。
考虑到模板产生在Ansible控制器上,而不是在任务的目标主机上,所以过滤器也在控制器上执行,因为它们处理本地数据。
除了jinja2,Ansible附带自己的产品,并允许用户添加他们自己的自定义过滤器。
10、tests
Jinja中的tests是评估模板表达式,并返回True或False的一种方式,Jinja附带许多这些。在官方Jinja模板文档中查看内置测试。
tests和filters之间的主要区别在于Jinja tests用于比较,而filters用于数据处理,并且在jinja中有不同的应用程序,如map()和select()来选择列表中的项目。
像所有模板一样,tests总是在Ansible控制器上执行,而不是在任务的目标上执行,因为他们测试本地数据。
除了jinjia2 tests,Ansible提供更多功能,用户可以自己轻松创建。
11、插件过滤配置
Ansible 2.5为站点管理员添加了模块黑名单,用于禁用Ansible的某些模块。
这是通过yaml配置文件配置的(默认为/etc/ansible/plugin_filters.yml)。该文件的格式是:
--- filter_version: ‘1.0‘ module_blacklist: # Deprecated - docker # We only allow pip, not easy_install - easy_install
以上是关于如何利用ansible callback插件对执行结果进行解析的主要内容,如果未能解决你的问题,请参考以下文章
关于Ansible使用CallBack插件分析Playbook执行性能的一些笔记