Jinja2模板if/else语句



在jinja2模板文件中,我试图在服务器主机名中找到字符串,然后根据它找到的内容应用我想要的设置。这是我有的。这是有效的,但是,所有内容都得到了developmenthosts设置。

{% if 'dev' or 'tst' or 'test' or 'eng' in ansible_hostname %} {{ developmenthosts }} {% else %} {{ productionhosts }} {% endif %}

任何帮助将是伟大的,我是相当新的使用jinja2模板。

尝试以下操作,使用regex_search, if/else可以写成更短、更清晰的格式。

"{{ developmenthosts if ( ansible_hostname|regex_search('dev|tst|test|eng') ) else  productionhosts }}"

的例子:

---
- name: Sample playbook
connection: local
#  gather_facts: false
hosts: localhost
vars:
developmenthosts: MYDEVHOST
productionhosts: MYPRODHOST
tasks:
- debug:
msg: "{{ ansible_hostname }}"
- debug:
msg: "{{ developmenthosts if ( ansible_hostname |regex_search('dev|tst|test|eng') ) else  productionhosts }}"

最新更新