Search code examples
ansibleansible-inventoryansible-template

How to use ansible template module with variable receiving value from hostvars?


In templates/config.py:

{% if env_value == 'Dev' %}
  {% set x = {{hostvars['ces_dev']['ansible_host']}} %}
{% else %}
  {% set x = {{hostvars['ces_demo']['ansible_host']}} %}
{% endif %} 

API_CONFIG = {
    'api_email_url': 'http://{{x}}:8080/api/users/mail',
}

In host inventory:

ces_dev    ansible_ssh_private_key=<path>   ansible_host=a.b.c.d

ces_demo   ansible_ssh_private_key=<path>   ansible_host=x.y.z.w

Expected output, if condition is met:

API_CONFIG = {
        'api_email_url': 'http://a.b.c.d:8080/api/users/mail',
    }

I am getting an error: "msg": "AnsibleError: template error while templating string: expected token 'colon', got '}'

How to resolve this and get the desired output?


Solution

  • I cracked the expected output myself, with several try-hit-error method. The solution is:

    API_CONFIG = {
        {% if env_value == 'Dev' %}
        'api_email_url': 'http://{{hostvars['ces_dev']['ansible_host']}}:8080/api/users/mail',
        'api_token_url': 'http://{{hostvars['ces_dev']['ansible_host']}}:8080/api/app/',
        {% else %}
        'api_email_url': 'http://{{hostvars['ces_demo']['ansible_host']}}:8080/api/users/mail',
        'api_token_url': 'http://{{hostvars['ces_demo']['ansible_host']}}:8080/api/app/',
        {% endif %} 
    }