ansible conditional templates

17,489

Did you try?

{% if isCondition %} {{ cluster_name }} A {% else %} {{ cluster_name }} B {% endif %}
Share:
17,489
Georg Heiler
Author by

Georg Heiler

I am a Ph.D. candidate at the Vienna University of Technology and Complexity Science Hub Vienna as well as a data scientist in the industry.

Updated on June 09, 2022

Comments

  • Georg Heiler
    Georg Heiler almost 2 years

    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'