Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible conditional templates

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'

like image 291
Georg Heiler Avatar asked Dec 10 '22 12:12

Georg Heiler


1 Answers

Did you try?

{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}
like image 129
Tomasz Swider Avatar answered Dec 13 '22 23:12

Tomasz Swider