Reputation: 1160
I want to generate a new list from files
by prepending /auto
and appending _sw_table
to each element. While I can do this by explicitly mentioning the new strings as args to regex_replace
in map
, I want to achieve the same using variables. The following works:
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
my_lst: []
top_dir: /auto
extra: sw_table
files: ['/etc/passwd', '/etc/group']
- set_fact:
my_lst: "{{ files | map('regex_replace', '(.*)', '/auto\\1_sw_table') | list }}"
- debug: var=my_lst
Output:
$ ansible-playbook -i localhost, ./test.yaml
PLAY [localhost] **************************************************************************************************
TASK [set_fact] ***************************************************************************************************
ok: [localhost]
TASK [set_fact] ***************************************************************************************************
ok: [localhost]
TASK [debug] ******************************************************************************************************
ok: [localhost] => {
"my_lst": [
"/auto/etc/passwd_sw_table",
"/auto/etc/group_sw_table"
]
}
How can I use the variables top_dir
and extra
in the call to map
to get the same result?
Upvotes: 2
Views: 12636
Reputation: 2625
You can use string concatenation in Jinja2:
- set_fact:
my_lst: "{{ files | map('regex_replace', '(^.*$)', top_dir + '\\1' + extra) | list }}"
Do take note of the updated regex pattern that I used. I had different results to your output above, and needed to update the pattern.
Upvotes: 8