Sarang Sangram
Sarang Sangram

Reputation: 71

Using commands in Ansible Jinja template

I am trying to create a jinja2 template which will use conditioning to check the server location and then push the changes to the server accordingly.

In my template file below I tried to run command and check if it meets the expected location .


config.j2

{% if `hostname -s|cut -c 1-2` == "ny" -%}

options timeout:1 attempts:2

search us.xyz.com 

nameserver 1.1.3.2  
nameserver 1.2.3.4

{% elif `hostname -s|cut -c 1-2` == "au" -%}
options timeout:1 attempts:2
search us.xyz.com 
nameserver 1.1.3.9 

nameserver 1.2.3.8

{% endif %}

Its throwing error as :

"msg": "AnsibleError: template error while templating string: unexpected char u'`'

Does the jinja template allows using system commands or not at all ? Any suggestion or lead will be helpful !

Upvotes: 1

Views: 2438

Answers (1)

techraf
techraf

Reputation: 68439

Does the jinja template allows using system commands or not at all?

No, it doesn't.

Not only there is no such syntax, but templating would be executed on local machine, so hostname in your example would always resolve to the control machine's name.

But there is no reason to do it at all, just use Ansible in the following way:

{% if ansible_hostname[0:2] == "ny" -%}

Upvotes: 3

Related Questions