Reputation: 5720
I want to append attribute to a file, instead of replacing or setting it on a new line.
Content of file:
PATH = "/a/path"
The variable which attributes has to append in the file:
"{{ key.values() | map(attribute='hi') | list | join(' ') }}"
The output of the variable is:
/hi1 /hi2 /hi3
Trying to append with lineinfile
, but the parameter insertafter
places the attributes on a new line, instead of the same line.
- lineinfile:
dest: /file
state: present
insertafter: 'PATH = "'
line: "{{ mounts.values() | map(attribute='mountpoint') | list | join(' ') }}"
Expected result:
PATH = "/a/path /hi1 /h2 /hi3"
Actual result:
PATH = "/a/path"
/hi1 /hi2 /hi3
Receiving syntax errors if I use the method described here: Ansible: insert a single word on an existing line in a file
Which module should I use for this particular use case?
Using Ansible v2.1.2.0
The backrefs option gives the same result, which is not expected:
- lineinfile:
dest: /file
backrefs: yes
regexp: 'PATH = "'
line: "{{ key.values() | map(attribute='hi') | list | join(' ') }}"
Upvotes: 1
Views: 5904
Reputation: 5720
Thanks for helping @Mir. Final solution:
- lineinfile:
dest: /file
backrefs: yes
regexp: '(^PATH\s+\=\s+)(?:")([\w+\s/]+)(?<!{{ hi }})(?:")'
line: '\1"\2 {{ hi }}"'
Where hi
is the variable.
Upvotes: 2
Reputation: 1613
Lineinfile module has the backrefs option that goes in pair with the regexp option and allows you to match an existing line and change only parts of it.
Something like (not tested)
- lineinfile:
[...]
regexp: ^PATH = "(.*)"$
line: PATH="\1 {{ your_variable_here}}"
backrefs: yes
Is probably what you need.
Upvotes: 0