ansible list items should be replaced when meeting criteria

Viewed 48

I have got an ansible problem where I have to change the items of a list in some cases. Imagine, if there is the string "apple0" and another digit from 0 to 9 the list element should be appended by the string T2. If there is any other element, lets say banana or peach, it should stay as it is.

---
- 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}}"

suggested output:

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

For example

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

gives

  fruit2:
  - banana
  - apple05T2
  - apple04T2
  - peach

The next option is to map the filter regex_replace. For example, the task below gives the same result

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