简体   繁体   中英

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.

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

Or, to minimize the code, 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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM