'Ansible : display variable in jinja template

I have a playbook in order to run a shell command to count the number of updates.

I would like to display this result in a file but this result is false.

My playbook :

- name: Listing packages
  hosts: all
  gather_facts: false
  tasks:
    - name: Count number of updates
      shell: yum check-update | wc -l
      register: nbupdates

    - name: Display number of updates
      debug:
        var: nbupdates.stdout_lines

    - name: output to html file
      template:
        src: ./jinja/src/tpl_dashboard_update.j2
        dest: ./jinja/dst/dashboard_update.html
        force: yes
      delegate_to: localhost

My jinja template is this one:

{% for host in vars['play_hosts'] %}
{{ host | upper }} : we have {{ nbupdates.stdout_lines[0] }} updates
{% endfor %}

When I run the playbook, I always have the same number of updates for each server like if the loop is not working.

What I'm doing wrong?



Solution 1:[1]

There are a number of problems with your template.

  • vars is an undocumented internal variable with undesirable behaviour and should not be used.
  • Your use of vars is completely unnecessary, so you can just remove it instead of replacing it with the vars lookup.
  • play_hosts is deprecated and should not be used.
  • Your task should use run_once so that it only runs once, instead of once for each server.
  • You should use hostvars to access information about other hosts instead of always using the value for the current host.
    - name: output to html file
      template:
        src: ./jinja/src/tpl_dashboard_update.j2
        dest: ./jinja/dst/dashboard_update.html
        force: yes
      delegate_to: localhost
      run_once: true
{% for host in ansible_play_hosts %}
{{ host | upper }} : we have {{ hostvars[host].nbupdates.stdout_lines.0 }} updates
{% endfor %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flowerysong