sherri
sherri

Reputation: 461

replace multiple patterns with multiple values in ansible

I am using regex_replace filter in ansible. i can make it work, but its really cumbersome . This is how i am doing

- set_fact:
    variable: "{{ value | regex_replace("84","89") | regex_replace("76","78") | regex_replace("45","23"}}"

Is there a way, i can pipe regex_replace one time and replace multiple patterns with multiple values.

Upvotes: 3

Views: 9490

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68254

Q: "Can I pipe regex_replace one time and replace multiple patterns with multiple values?"

A: No. It's not possible. But, you can do it in a loop. For example,

  vars:

    my_var: ABCDEFGH

  tasks:

    - set_fact:
        my_var: "{{ my_var|regex_replace(item.regex, item.replace) }}"
      loop:
        - {regex: 'A', replace: '1'}
        - {regex: 'C', replace: '3'}
        - {regex: 'E', replace: '5'}
    - debug:
        var: my_var

gives

    my_var: 1B3D5FGH

You can minimize the code. For example, the task below gives the same result

    - set_fact:
        my_var: "{{ my_var|regex_replace(item.0, item.1) }}"
      loop:
        - ['A', '1']
        - ['C', '3']
        - ['E', '5']

Q: "Can we make this not take the replaced value as an input for the next loop item?"

A: Yes. We can. The better structure in this case is a dictionary. For example,

    my_var: AB1
    regrep:
      'A': '1'
      '1': 'C'

The expected result is '1BC'. We don't want the first character replaced with 'C'. The Jinja expression below gives what you want

    - set_fact:
        my_var: |
          {% for x in  my_var %}
          {% if x in regrep %}
          {{ regrep[x] }}
          {%- else %}
          {{ x }}
          {%- endif %}
          {%- endfor %}

Upvotes: 7

Related Questions