I have a variable, which is a list as below:
"test_list": [
"some text here",
"server1",
"command1 parameter1",
"path/to/command2 parameter2 server1_202012",
"some more text",
"New backup file is server1_202019"
]
I am trying to extract the substring server1_202019
which is at the end of the line that starts with New backup file...
. There is only one line like this and I've tried below option to get the substring.
- set_fact:
test_name: "{{ test_list | select('^New backup file is (.+)$','\\1') }}"
and the output I've received is:
"test_name": "<generator object _select_or_reject at 0x3fe5b40>"
I've tried below code also, but failed.
- set_fact:
test_name: "{{ test_list | regex_search('^New backup file is (.+)$','\\1') }}"
The error is:
"msg": "Unexpected templating type error occurred on ({{ test_list | regex_search('^New backup file is (.+)$','\\\\1') }}): ..... expected string or buffer"
Could somebody please suggest how I can get the output as below:
"test_name": "server1_202019"
The ansible version I'm using is 2.9
Thanks
Select the item from the list and then use regex_replace
. For example
- set_fact:
test_name: "{{ test_list|
select('regex', my_regex)|
first|
regex_replace(my_regex, my_replace) }}"
vars:
my_regex: '^New backup file is (.*)$'
my_replace: '\1'
- debug:
var: test_name
give
"test_name": "server1_202019"