filter的格式:   value..| filter()  在python中就是类的实例化 filter(self,*args,**kwargs) self就是filter中管道符前的value。

本文基于ansible 2.4.2.0版本

core.py中核心过滤器

        # jinja2 overrides
        'groupby': do_groupby, # base 64
'b64decode': b64decode,
'b64encode': b64encode, # uuid
'to_uuid': to_uuid, # json
'to_json': to_json,
'to_nice_json': to_nice_json,
'from_json': json.loads, # yaml
'to_yaml': to_yaml,
'to_nice_yaml': to_nice_yaml,
'from_yaml': from_yaml, # date
'to_datetime': to_datetime, # path
'basename': partial(unicode_wrap, os.path.basename),
'dirname': partial(unicode_wrap, os.path.dirname),
'expanduser': partial(unicode_wrap, os.path.expanduser),
'realpath': partial(unicode_wrap, os.path.realpath),
'relpath': partial(unicode_wrap, os.path.relpath),
'splitext': partial(unicode_wrap, os.path.splitext),
'win_basename': partial(unicode_wrap, ntpath.basename),
'win_dirname': partial(unicode_wrap, ntpath.dirname),
'win_splitdrive': partial(unicode_wrap, ntpath.splitdrive), # value as boolean
'bool': to_bool, # date formating
'strftime': strftime, # quote string for shell usage
'quote': quote, # hash filters
# md5 hex digest of string
'md5': md5s,
# sha1 hex digeset of string
'sha1': checksum_s,
# checksum of string as used by ansible for checksumming files
'checksum': checksum_s,
# generic hashing
'password_hash': get_encrypted_password,
'hash': get_hash, # file glob
'fileglob': fileglob, # regex
'regex_replace': regex_replace,
'regex_escape': regex_escape,
'regex_search': regex_search,
'regex_findall': regex_findall, # ? : ;
'ternary': ternary, # list
# random stuff
'random': rand,
'shuffle': randomize_list,
# undefined
'mandatory': mandatory, # merge dicts
'combine': combine, # comment-style decoration
'comment': comment, # array and dict lookups
'extract': extract, # debug
'type_debug': lambda o: o.__class__.__name__,

ipaddr.py中的ip地址相关过滤器

     # IP addresses and networks
'ipaddr': ipaddr,
'ipwrap': ipwrap,
'ip4_hex': ip4_hex,
'ipv4': ipv4,
'ipv6': ipv6,
'ipsubnet': ipsubnet,
'next_nth_usable': next_nth_usable,
'network_in_network': network_in_network,
'network_in_usable': network_in_usable,
'nthhost': nthhost,
'previous_nth_usable': previous_nth_usable,
'slaac': slaac, # MAC / HW addresses
'hwaddr': hwaddr,
'macaddr': macaddr

json_query.py中json过滤器

'json_query': json_query

mathstuff.py中的数学运算相关的过滤器

         # general math
'min': min,
'max': max, # exponents and logarithms
'log': logarithm,
'pow': power,
'root': inversepower, # set theory
'unique': unique,
'intersect': intersect,
'difference': difference,
'symmetric_difference': symmetric_difference,
'union': union, # combinatorial
'permutations': itertools.permutations,
'combinations': itertools.combinations, # computer theory
'human_readable': human_readable,
'human_to_bytes': human_to_bytes, # zip
'zip': zip,
'zip_longest': zip_longest,

network.py中网络相关的filter

        'parse_cli': parse_cli,
'parse_cli_textfsm': parse_cli_textfsm

urlsplit.py中的url的filter

    'urlsplit': split_url

jinjia2 的过滤器 ,路径/usr/lib/python2.7/site-packages/jinja2/filters.py

    'attr':                 do_attr,
'replace': do_replace,
'upper': do_upper,
'lower': do_lower,
'escape': escape,
'e': escape,
'forceescape': do_forceescape,
'capitalize': do_capitalize,
'title': do_title,
'default': do_default,
'd': do_default,
'join': do_join,
'count': len,
'dictsort': do_dictsort,
'sort': do_sort,
'length': len,
'reverse': do_reverse,
'center': do_center,
'indent': do_indent,
'title': do_title,
'capitalize': do_capitalize,
'first': do_first,
'last': do_last,
'map': do_map,
'random': do_random,
'reject': do_reject,
'rejectattr': do_rejectattr,
'filesizeformat': do_filesizeformat,
'pprint': do_pprint,
'truncate': do_truncate,
'wordwrap': do_wordwrap,
'wordcount': do_wordcount,
'int': do_int,
'float': do_float,
'string': soft_unicode,
'list': do_list,
'urlize': do_urlize,
'format': do_format,
'trim': do_trim,
'striptags': do_striptags,
'select': do_select,
'selectattr': do_selectattr,
'slice': do_slice,
'batch': do_batch,
'sum': do_sum,
'abs': abs,
'round': do_round,
'groupby': do_groupby,
'safe': do_mark_safe,
'xmlattr': do_xmlattr,
'urlencode': do_urlencode

ternary(value,true_val,false_val):  传入三个值,如果value是true,则return true_val,否则return false_val。

def ternary(value, true_val, false_val):
''' value ? true_val : false_val '''
if bool(value):
return true_val
else:
return false_val
playbook示例
---
- name: ternary
hosts: localhost
tasks:
- name: set value
set_fact:
a: true
b: "if a true"
c: "if a false"
- name: debug
debug:
var: a|ternary(b,c)
... ################
脚本的执行
[root@node-1 filters_test]# ansible-playbook ternary_test.yml PLAY [ternary] ********************************************************************************* TASK [set value] *******************************************************************************
ok: [localhost] TASK [debug] ***********************************************************************************
ok: [localhost] => {
"a|ternary(b,c)": "if a true"
} PLAY RECAP *************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed

strftime的当前时间的用法

def strftime(string_format, second=None):
''' return a date string using string. See https://docs.python.org/2/library/time.html#time.strftime for format '''
if second is not None:
try:
second = int(second)
except:
raise errors.AnsibleFilterError('Invalid value for epoch value (%s)' % second)
return time.strftime(string_format, time.localtime(second))
如果要用指定时间则strftime(second)
示例:
- name: get time
set_fact:
curtime: "{{ '%Y-%m-%d %H:%M:%S'|strftime }}"

select、map和type_debug的用法

select('funtion_name', 'regexp') function可以是filter,map,reduce等
value|type_debug 类似type(value)获取值的数据类型 ---
- hosts: localhost
gather_facts: true
tasks:
- debug: msg="{{ ansible_interfaces|select('match','^eth|wlan[0-9]+')|list }}" # match、search、map获取的都是迭代器,需要list一下变成列表
- debug: msg="{{ ansible_interfaces|select('search','eth|wlan[0-9]+')|list }}"
- debug: msg="{{ ansible_interfaces|map('upper')|list }}" # map('func','args','arg2') map(attribute='key')      
- debug: msg="{{ ansible_interfaces + [\"VETH-1\",\"VETH-2\"] }}"  #列表的扩展方法之一 字符串也可以这么扩展
- debug: msg="{{ ansible_interfaces|type_debug }}" ##################################################################
PLAY [localhost] *******************************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [localhost]
TASK [debug] ***********************************************************************************
ok: [localhost] => {}
MSG:
[u'eth1', u'eth0'] TASK [debug] ***********************************************************************************
ok: [localhost] => {}
MSG:
[u'eth1', u'eth0', u'br-eth1', u'br-eth0'] TASK [debug] ***********************************************************************************
ok: [localhost] => {}
MSG:
[u'BR-VXLAN', u'OVS-SYSTEM', u'BR-STORAGEPUB', u'BR-EX-HAPR', u'BR-MGMT-HAPR', u'ETH1', u'ETH0', u'BR-ETH1', u'LO', u'IFB0', u'VXLAN_SYS_4789', u'BR-ROLLER', u'BR-PRV', u'BR-TUN', u'BR-INT', u'BR-BM', u'TAP0', u'BR-IPMI', u'HAPR-HOST', u'BR-ETH0', u'BR-STORAGE', u'BR-MGMT', u'BR-EX'] TASK [debug] ***********************************************************************************
ok: [localhost] => {}
MSG:
[u'br-vxlan', u'ovs-system', u'br-storagepub', u'br-ex-hapr', u'br-mgmt-hapr', u'eth1', u'eth0', u'br-eth1', u'lo', u'ifb0', u'vxlan_sys_4789', u'br-roller', u'br-prv', u'br-tun', u'br-int', u'br-bm', u'tap0', u'br-ipmi', u'hapr-host', u'br-eth0', u'br-storage', u'br-mgmt', u'br-ex', u'VETH-1', u'VETH-2'] TASK [debug] ***********************************************************************************
ok: [localhost] => {}
MSG:
list PLAY RECAP *************************************************************************************
localhost : ok=6 changed=0 unreachable=0 failed=0

first和last: 获取列表的第一个元素和最后一个元素

sort 可以对可迭代对象进行排序,类似列表
sort(value, reverse=False, case_sensitive=False, attribute=None) - name: find
find:
paths: /etc/nova
patterns: 'nova.conf.*'
register: find_out
- debug: var=(find_out.files|sort(attribute='mtime')|last).path 此示例 根据查找/etc/nova/中 nova.conf.*的文件,然后根据mtime进行排序,最后抓出last元素的path值

ansible的Filter的更多相关文章

  1. ansible配置文件详解

    # ansible配置文件配置 配置项介绍 , 配置文件ansible.cfg, 运行playbook时,默认时在yaml文件所在路径寻找,然后再去/etc/ansible/下寻找 [defaults ...

  2. 初探ansible

    Ansible 基于ssh的自动化运维工具 ansible 配置文件详解 ansible.cfg 文件 文件默认放置在/etc/ansible下,ansible读取配置文件的顺序是: 当前命令执行目录 ...

  3. 002. Ansible部署及配置介绍

    一 Ansible的安装部署 1.1 PIP方式 安装PIP 略,可参考<001.Pip简介及使用>. 提示:建议将PIP升级到最新:pip install --upgrade pip. ...

  4. Ansible配置文件

    官方配置文件文档 Ansible安装完成之后默认配置文件为:/etc/asnible/ansible.cfg Ansible配置文件内容: cat ansible.cfg # config file ...

  5. ansible Developing Plugins

    Action plugins是模块的前端,可以在调用模块本身之前对控制器执行操作. Cache plugins用于保存“facts”的缓存,以避免代价高昂的fact-gathering操作. Call ...

  6. ansible 2.1.0 api 编程

    pdf文档 https://media.readthedocs.org/pdf/ansible/latest/ansible.pdf api介绍 http://blog.csdn.net/python ...

  7. 《Ansible自动化运维:技术与佳实践》第二章读书笔记

    Ansible 安装与配置 本章主要讲的是 Ansible 安装与基本配置,主要包含以下内容: Ansible 环境准备 安装 Ansible 配置运行环境 Ansible 环境准备 从 GitHub ...

  8. ansible 配置文件设置

    目录 ansible 配置文件设置 一.ansible configuration settings 二.ansible 配置文件查找顺序(从上到下,依次查找) 三.附录ansible配置参数 ans ...

  9. ansible笔记(二)--配置文件详解

    配置文件ansible.cfg约有350行语句,大多数为注释行默认配置项.该文件遵循INI格式,分为如下几类配置.(1)[defaults] [defaults] # inventory = /etc ...

随机推荐

  1. Flask 视图,中间件

    视图 FBV def index(nid): """ 请求相关信息 request.method # 请求方式 request.args # get 方式的参数获取 re ...

  2. Zookeeper分布式集群原理与功能

    Zookeeper功能简介 ZooKeeper 是一个开源的分布式协调服务,由雅虎创建,是 Google Chubby 的开源实现. 分布式应用程序可以基于 ZooKeeper 实现诸如数据发布/订阅 ...

  3. P1742 最小圆覆盖(计算几何)

    体验过\(O(n^3)\)过\(10^5\)吗?快来体验一波当\(wys\)的快感吧\(QAQ\) 前置芝士1:二元一次方程组求解 设 \[\begin{cases}a1 * x + b1*y=c1\ ...

  4. Mac spotlight无法搜索的解决方法

    出现问题: 1. 在打开spotlight快速搜索的时候输入两个字符,后该搜索框自动会消失,很是奇怪重启等操作也没有效果 问题原因: 可能因为之前因为耗电原因关闭的全局搜索的索引,或者由于索引出现错误 ...

  5. nginx服务器的基本配置

    nginx作为反向代理搭建服务器的优点. 处理响应请求很快:单次请求会得到更快的响应.在高峰期,Nginx 可以比其它的 Web 服务器更快的响应请求 高并发连接:理论上,Nginx 支持的并发连接上 ...

  6. vue实战记录(三)- vue实现购物车功能之渲染商品列表

    vue实战,一步步实现vue购物车功能的过程记录,课程与素材来自慕课网,自己搭建了express本地服务器来请求数据 作者:狐狸家的鱼 本文链接:vue实战-实现购物车功能(三) GitHub:sue ...

  7. python 爬虫之beautifulsoup(bs4)使用 --待完善

    #!/usr/bin/env python # -*- coding:utf- -*- from bs4 import BeautifulSoup import requests url = 'htt ...

  8. A Reliability-Aware Network Service Chain Provisioning With Delay Guarantees in NFV-Enabled Enterprise Datacenter Networks

    文章名称:A Reliability-Aware Network Service Chain Provisioning With Delay Guarantees in NFV-Enabled Ent ...

  9. 2018-2019-2 《Java程序设计》第4周学习总结

    20175319 2018-2019-2 <Java程序设计>第4周学习总结 教材学习内容总结 第四周学习了如下内容: 子类与父类 子类的继承性 子类与对象 重写方法 super关键字 f ...

  10. 第十五节:Expression表达式目录树(与委托的区别、自行拼接、总结几类实例间的拷贝)

    一. 基本介绍 回忆: 最早接触到表达式目录树(Expression)可能要追溯到几年前使用EF早期的时候,发现where方法里的参数是Expression<Func<T,bool> ...