在Ansible的Jinja2模板中,可以使用条件语句来根据不同的条件执行不同的操作。以下是一个使用条件语句的示例:
---
- name: Ansible Jinja2 Template with Condition
hosts: localhost
gather_facts: false
vars:
variable1: "value1"
variable2: "value2"
tasks:
- name: Create a file using Jinja2 template with condition
template:
src: template.j2
dest: /path/to/destination/file
when: variable1 == "value1"
- name: Create another file using Jinja2 template with condition
template:
src: template.j2
dest: /path/to/another/destination/file
when: variable2 == "value2"
在上面的示例中,我们使用了两个条件语句来决定是否执行模板任务。首先,我们定义了两个变量variable1
和variable2
,然后在任务中使用when
关键字来设置条件。
在模板文件template.j2
中,可以使用Jinja2的条件语句来根据条件生成不同的内容。以下是一个示例模板文件:
{% if variable1 == "value1" %}
This is content for the first file.
{% endif %}
{% if variable2 == "value2" %}
This is content for the second file.
{% endif %}
在这个模板文件中,我们使用了两个条件语句来决定是否生成不同的内容。根据条件的结果,模板将生成不同的内容到目标文件中。
请注意,条件语句中的变量使用了Jinja2的语法,如{{ variable1 }}
。在模板中,可以使用任何Jinja2支持的语法来处理条件和变量。
运行上述示例Playbook,将根据variable1
和variable2
的值决定是否创建相应的文件,并根据模板中的条件生成内容。