在 regex_replace 的替换字符串中使用 ansible 变量 [英] Use ansible variable in replace string for regex_replace
问题描述
我想通过在 /auto
前面加上 _sw_table
来从 files
生成一个新列表到每个元素.虽然我可以通过在 map
中将新字符串作为参数显式提及到 regex_replace
来做到这一点,但我想使用变量来实现相同的效果.以下工作:
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
输出:
$ 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"
]
}
如何在对 map
的调用中使用变量 top_dir
和 extra
来获得相同的结果?
How can I use the variables top_dir
and extra
in the call to map
to get the same result?
推荐答案
你可以在 Jinja2 中使用字符串连接:
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.
这篇关于在 regex_replace 的替换字符串中使用 ansible 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!