【问题标题】:ansible list items should be replaced when meeting criteria满足条件时应替换 ansible 列表项
【发布时间】:2021-08-07 19:37:09
【问题描述】:

我遇到了一个问题,在某些情况下我必须更改列表中的项目。 想象一下,如果存在字符串“apple0”和另一个从 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"
        ]
    ]
}

【问题讨论】:

    标签: list replace ansible


    【解决方案1】:

    例如

       - 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: '^(apple0\d)$'
            my_replace: '\1T2'
    

    【讨论】:

    • 太棒了!解决方案对我有用。非常感谢弗拉基米尔!
    猜你喜欢
    • 2017-04-07
    • 2018-08-24
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多