一、简介
ansible中的filter: map ,其实是jinja2中的filter
python中 map(func, iter) 返回func与每个元素计算后的迭代器,iter是个可迭代对象
ansible中的map和python中的基本上用法相似。
二、实例
1、value | map('func') : 没有仔细看代码,func可能是只能用jinja2的filter。举例来说,标签:map,ok,list,ansible,func,debug,localhost From: https://blog.51cto.com/u_13236892/6079263
---
- hosts: localhost
vars:
t1: ['abc','cde']
tasks:
- name: upper
debug: var=t1|map('upper')|list
###########################
ok: [localhost] => {
"t1|map('upper')|list": [
"ABC",
"CDE"
]
}
2、如果func需要多个参数,如替换 map('regex_replace','[0-9]+','foo') | list
---
- hosts: localhost
vars:
mylist:
- group_1
- group_2
tasks:
- debug:
msg: "{{ mylist | map('regex_replace', '([0-9]+)', 'foo') | list }}"
############################################
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {}
MSG:
[u'group_foo', u'group_foo']
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
3、还有一种常用的方法,就是attribute=key的用法
---
- hosts: controller
tasks:
- name: get ifconfig
shell: ifconfig {{ item }} | awk '/inet/{print $2}'
register: ifout
with_items:
- 'br-ex'
- 'br-mgmt'
- debug: var=ifout.results|map(attribute='stdout')|list
#######################################
TASK [debug] *******************************************************************
ok: [192.168.10.3] => {
"ifout.results|map(attribute='stdout')|list": [
"172.16.20.3",
"192.168.10.3"
]
}
ok: [192.168.10.4] => {
"ifout.results|map(attribute='stdout')|list": [
"172.16.20.4",
"192.168.10.4"
]
}