ansible conditional templates
Asked Answered
D

1

6

I want to have a simple if else condition in ansibles jinja templates. For plain python

cluster_name+'A' if isCondition is True else cluster_name +'B'

wors great if the following variables are defined:

isSingleNode = True
cluster_name = 'example'

In ansible I see the following error:

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"}

Here is a minimal example:

file_1: variables

---
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: inventory

[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'] }}"
}

command to execute the minimal example is ansible-playbook -i inventory playbook.yml -e 'cluster_name=examplecluster'

Dill answered 9/2, 2017 at 15:43 Comment(2)
@downvoter please explain why.Dill
You can't write arbitrary python code in jinja2 expression.Ramble
P
17

Did you try?

{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}
Pantechnicon answered 9/2, 2017 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.