4

我想在 ansibles jinja 模板中有一个简单的 if else 条件。对于普通蟒蛇

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:剧本.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_name=examplecluster'

4

1 回答 1

13

你试过了吗?

{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}
于 2017-02-09T15:51:48.827 回答