Python 可分解条件模板
我想在ansibles jinja模板中有一个简单的if-else条件。对于普通pythonPython 可分解条件模板,python,ansible,jinja2,ansible-2.x,ansible-template,Python,Ansible,Jinja2,Ansible 2.x,Ansible Template,我想在ansibles jinja模板中有一个简单的if-else条件。对于普通python cluster_name+'A' if isCondition is True else cluster_name +'B' 如果定义了以下变量,则效果很好: isSingleNode = True cluster_name = 'example' 在ansible中,我看到以下错误: fatal: [localhost]: FAILED! => {"changed": false, "fai
cluster_name+'A' if isCondition is True else cluster_name +'B'
如果定义了以下变量,则效果很好:
isSingleNode = True
cluster_name = 'example'
在ansible中,我看到以下错误:
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleError: template error while templating string: no test named 'True'. String: {\n\n \"key\" : \"{{ groups[cluster_name+'_mn01' if isSingleNode is True else cluster_name + '_mn02'] }}\"\n}\n"}
下面是一个简单的例子:
文件1:变量
---
isCondition: True
文件2:playbook.yml
---
- hosts: all
tasks:
- include_vars: variables
- debug: msg=" condition is {{ isCondition }} with cluster_name {{ cluster_name }}"
- name: copy file
template: src="bare_cluster.bp.j2" dest={{ cluster_name }}_blueprint.json backup=yes
文件4:库存
[examplecluster:children]
examplecluster_mn01
[mn01:children]
examplecluster_mn01
[examplecluster_mn01]
localhost ansible_connection=local
文件_5:bare_cluster.bp.j2
{
"key" : "{{ groups[cluster_name+'_mn01' if isSingleNode is True else cluster_name + '_mn02'] }}"
}
执行最小示例的命令是ansible playbook-i inventory playbook.yml-e'cluster\u name=examplecluster'
您尝试过吗
{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}
@请解释原因。您不能用jinja2表达式编写任意python代码。