ansibleansible-role

ansible : replace line in file with new values depending of original values


With loop or other, I can't see how to use the replace or inline module to achieve that.

The orinal file contains this line

goals first_goal + second_goal

I only want to modify the line starting with goals (with leading spaces or not)
With these possible values : A, B, C, D, E, F

For example

goals C + F

My role needs to replace this line with these correspondances (the first letter matching is just to simplify my example) :

A -> always
B -> back
C -> car
D -> dance
E -> even
F -> fast

So, for this example, the converted file will contains the line :

goals car + fast

(option+ if possible : several single letters can lead to the same value, e.g. A -> always , V -> always, Z -> always)

Here things are voluntarily limited, I have many more value possibles.
What would be the best way to do this ? Thank you.


Solution

  • Ansible does not seem to well buffer the first line replacement when a regex alternation is used, but it works with 2 tasks, one for each regexp :

    tasks:
        - name: Replace goal left
          ansible.builtin.replace:
            path: "{{ file_dir_path }}/replace_goal.txt"
            regexp: '^(\s*goals\s+){{ item.key | regex_escape}}\s*(\+*.*)'
            replace: '\1 {{ item.value }} \2'
          loop: "{{ goals | dict2items }}"
        - name: Replace goal right
          ansible.builtin.replace:
            path: "{{ file_dir_path }}/replace_goal.txt"
            regexp: '^(\s*goals\s+\S+\s*\+)\s*{{ item.key | regex_escape}}(.*)'
            replace: '\1 {{ item.value }} \2'
          loop: "{{ goals | dict2items }}"