问题描述
我的用例如下:
我有一个模板文件,我想从该模板创建2个不同的文件,变量由每个文件使用一组不同的变量。
I have a template file, and I would like to create 2 different files from that template, with the variables being filled by a different set of variables for each file.
例如,假设我要对包含以下行的文件进行模板化:
For example, lets say I want to template the file containing the line:
mkdir -p {{myTemplateVariable}}
我想找到一种适当的方法来获取由 File1和 File2填充的变量。像这样的东西:
I would like to find a proper way to get this variable filled by "File1" and "File2". Something like :
- name: template test 1
template:
src=myTemplateFile
dest=result1
- name: template test 2
template:
src=myTemplateFile
dest=result2
在这里我可以为第一个模板指定要使用的变量为a = File1,为第二个模板指定b = File2。
where I could specify for the first templating that the variable to use is a = "File1" and for the second, b = "File2".
推荐答案
对于Ansible 2.x:
For Ansible 2.x:
- name: template test
template:
src: myTemplateFile
dest: result1
vars:
myTemplateVariable: File1
- name: template test
template:
src: myTemplateFile
dest: result2
vars:
myTemplateVariable: File2
对于Ansible 1.x:
For Ansible 1.x:
不幸的是,模板
模块不支持向其传递变量,该变量可以在tem内部使用。盘子。有一个,但被拒绝了。
Unfortunately the template
module does not support passing variables to it, which can be used inside the template. There was a feature request but it was rejected.
我可以想到两种解决方法:
I can think of two workarounds:
1。 Include
include
语句支持传递变量。因此,您可以将 template
任务放在一个额外的文件中,并使用适当的参数将其包含两次:
The include
statement supports passing variables. So you could have your template
task inside an extra file and include it twice with appropriate parameters:
my_include.yml :
my_include.yml:
- name: template test
template:
src=myTemplateFile
dest=destination
main.yml:
- include: my_include.yml destination=result1 myTemplateVariable=File1
- include: my_include.yml destination=result2 myTemplateVariable=File2
2。重新定义myTemplateVariable
另一种方法是在每个模板
之前简单地重新定义myTemplateVariable。
Another way would be to simply re-define myTemplateVariable right before every template
task.
- set_fact:
myTemplateVariable: File1
- name: template test 1
template:
src=myTemplateFile
dest=result1
- set_fact:
myTemplateVariable: File2
- name: template test 2
template:
src=myTemplateFile
dest=result2
这篇关于如何使用具有不同变量集的模板模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!