# 官方提供@yunTaoScripts Ansible 过滤器和插件 🔥🔥
# 过滤器
# default
如果cc 没定义打印None,aa,bb定义了打印原来的值
vars:
aa: 1
bb:
tasks:
- name: xxx
debug: msg="{{cc| default('None') }}"
# 数字操作
- int 强制类型转换
debug: msg="{{1+ ('2'| int) }}"
- float 强制类型转换
debug: msg="{{1+ ('2'| float) }}"
- abs 绝对值
debug: msg="{{-5 | abs}}"
- round 四舍五入
debug: msg="{{4.5 | round}}"
# 字符操作
- 转化为字符串
debug: msg="{{4.6| string}}"
- 大写转化
debug: msg="{{tom| upper}}"
- 小写转化
debug: msg="{{tom| lower}}"
- 首字母转化
debug: msg="{{tom| capitalize}}"
- 字符加密
debug: msg="{{'hfsah' | hash('md5') }}"
debug: msg="{{'hfsah' | hash('sha1') }}"
debug: msg="{{'hfsah' | password_hash('sha512') }}"
- 正则匹配和替换
---
- name: this is for test
hosts: localhost
vars:
a: 'afd 1.2.3.4 fdssa'
tasks:
- name: print date
debug:
msg: "{{a| regex_findall('\\b[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\b')}}"
- name: print date
debug:
msg: "{{a|regex_replace('\\.','X')}}"
- name: print date
debug:
msg: "{{a| regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b')}}"
正则分组
?: 代表不要看作分组,否则只打印分组内的信息,只显示第三组信息
# 列表操作
vars:
list: [4,42,1,44,999]
tasks:
- name: xxx
debug: msg="{{list | max }}"
debug: msg="{{list | min }}"
debug: msg="{{list | length }}"
debug: msg="{{list | sort }}"
debug: msg="{{list | sum }}"
debug: msg="{{list | shuffle }}"
debug: msg="{{list | unique }}"
debug: msg="{{list | to_yaml }}" # 列表转化为字符串
# 字典操作
---
- name: this is for test
hosts: localhost
vars:
mydict:
a: 1
b: 2
c: 3
tasks:
- name: print info
debug:
msg: "{{item.key}}====={{item.value}}"
with_dict: "{{mydict}}"
- name: print dict2item
debug:
msg: "{{item.key}}====={{item.value}}"
loop: "{{mydict|dict2items}}"
# 插件
# lookup file
把整个文件内容获取。
vars:
aa: "{{lookup('file','/etc/hosts')}}"
# query lines
将文件按行转化为列表
vars:
aa: "{{query('lines', 'cat /etc/hosts')}}"
tasks:
- name: xxx
debug: msg="{{aa[0]}}"
- name: xxx
debug: msg="{{item}}"
loop: aa
# lookup password
每个用户创建随机密码,并保存密码,如果密码存在就不会更新
tasks:
- name: xxx
vars:
password: "{{lookup('password', 'abcdir/'+item+' length=22')}}"
debug: msg="{{item}},{{password}}"
loop: "{{query('lines', 'cat userlist')}}"
- 校验哈希值checksum
vars_files:
- verfiy_file.yaml
tasks:
- name: verfiy file
vars:
- r1: "{{lookup('file',{{item.name}})|hash('sha1')}}"
- r1: "{{item.checksum}}"
assert:
that:
- r1 == r2
fail_msg: "fail {{item.name}}"
success_msg: "pass {{item.name}}"
loop: "{{files}}"
ignore_errors: yes
# assert 用法
---
- name: this is for test
hosts: localhost
tasks:
- name: print date
vars:
a: 1
b: 2
assert:
that:
- a == b
success_msg: "equal"
fail_msg: "not equal"