当满足条件时,应替换ansible列表项



我遇到了一个容易解决的问题,在某些情况下我必须更改列表中的项目。想象一下,如果存在字符串";苹果0";并且列表元素的从0到9的另一个数字应当由字符串T2附加。如果还有任何其他元素,比如香蕉或桃子,它应该保持原样

---
- hosts: localhost
become: no
vars:
fruit: [banana,apple05,apple04,peach]

tasks:
- name: my task
set_fact:
"{{ item | replace('^apple0[0-9]*$','?1T2') }}"
loop: "{{fruit}}"
- debug:
msg:
- "{{fruit}}"

建议输出:

ok: [localhost] => {
"msg": [
[
"banana",
"apple05T2",
"apple04T2",
"peach"
]
]
}

例如

- set_fact:
fruit2: "{{ fruit2|default([]) + [(item is match('^apple0\d$'))|
ternary(item ~ 'T2', item)] }}"
loop: "{{ fruit }}"

给出

fruit2:
- banana
- apple05T2
- apple04T2
- peach

下一个选项是映射过滤器regex_replace。例如,下面的任务给出了相同的结果

- set_fact:
fruit2: "{{ fruit|map('regex_replace', my_regex, my_replace)|list }}"
vars:
my_regex: '^(apple0d)$'
my_replace: '1T2'

最新更新