Mike Rossi
Mike Rossi

Reputation: 25

Ansible var jinja2 template

I've been trying to reference a variable in Ansible but each time I receive an error.

yaml var file has:

nodes:
  barni:
    - { name: 'LoginGraceTime', value: '2m'}
    - { name: 'MaxSessions', value: '6'}
    - { name: 'ChallengeResponseAuthentication', value: 'yes'}

where barni is the "hostname -s". I need something dynamic in the sshd_config.j2 template to match the hostname in the variable. Template works fine if I specify node.barni.sshdextra but what I need is for 'barni' to be replaced dynamically with the short name of the server name.

{% for item in node.barni.sshdextra %}
{{ item.name }} {{ item.value }}
{% endfor %}

In tasks I can reference the short hostname using hostname_mounts: "{{hostname_shortname.replace('-','')} hostname_shortname: "{{inventory_hostname.split('.')[0]}} in the variable def file

- name: nfs - edit - remove nfs lines from /etc/fstab
  command: sed -i '/nfs/d' /etc/fstab
  ignore_errors: yes
  when: "'{{inventory_hostname}}'.startswith('{{hostname_mounts}}')"
  tags: [ nfs ]

Upvotes: 2

Views: 2065

Answers (1)

udondan
udondan

Reputation: 60079

First let's make sure you understand the concept of Ansibles host_vars.

If you have a file host_vars/barni.yml (though the full name not the shortname is used) with the contents:

nodes:
  - { name: 'LoginGraceTime', value: '2m'}
  - { name: 'MaxSessions', value: '6'}
  - { name: 'ChallengeResponseAuthentication', value: 'yes'}

...you simply could loop over the nodes then. host_vars and group_vars usually are used to solve this kind of situation where you have different configuration for different hosts or sets of host.

But I agree there are situations where this is uncomfortable - and to finally answer your question: You can use the variable inventory_hostname_short to get the shortname of the host:

{% for item in node[inventory_hostname_short].sshdextra %}
{{ item.name }} {{ item.value }}
{% endfor %}

Upvotes: 2

Related Questions