ansible 条件模板

ansible conditional templates

我想在 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, "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"}

这是一个最小的例子:

file_1:变量

---
isCondition: True

file_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

file_4:库存

[examplecluster:children]
examplecluster_mn01

[mn01:children]
examplecluster_mn01

[examplecluster_mn01]
localhost ansible_connection=local

file_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'

你尝试了吗?

{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}