Reputation: 43
I have a local txt file called file-names.txt that contains a list of filenames
file1.txt
file2.txt
file3.txt
In my ansible-playbook I'm registering the file contents of file-name.txt using the slurp module.
And setting a fact named files_names
.
tasks:
- name: Getting the file
ansible.builtin.slurp:
src: file-name.txt
register: file_names
- name: Saving the file names
set_fact:
file_name_list: "{{ (file_name['content] | b64decode | trim ).split('\r\n') }}"
I want the file_name_list
fact to be a list just containing the file names. but some how split function is not able to remove the '\r'
from the file names and I get the following results
ok: [localhost] => {
"ansible_facts":{
"file_name_list": [
"file1.txt\r",
"file2.txt\r",
"file3.txt"
]
},
"changed": false
}
How can I remove the carriage return '\r'
from each element of the array so that file_name_list
looks like
ok: [localhost] => {
"ansible_facts":{
"file_name_list": [
"file1.txt",
"file2.txt",
"file3.txt"
]
},
"changed": false
}
PS: file-name.txt was made on a Windows machine, that's why there is a carriage return included in each line.
Upvotes: 1
Views: 2178
Reputation: 750
How to remove the line breaker character '\n' from the result of lookup() module in Ansible?
"{{ some_string| regex_replace('[\\r\\n]+','\n') }}"
Upvotes: 0
Reputation: 7340
So the trim
filter seems to be removing the final \r
from the list of files on file3.txt
. So instead of using trim
before splitting, we can trim each item
after splitting the filenames with \r
.
Something like below should do the trick:
- name: saving the file names
set_fact:
filename_list: "{{ filename_list|default([]) + [ item|trim ] }}"
with_items: "{{ (filenames.content|b64decode).split('\r') }}"
- name: show the filenames
debug:
var: filename_list
This should produce:
ok: [localhost] => {
"filename_list": [
"file1.txt",
"file2.txt",
"file3.txt"
]
}
Upvotes: 2