jinja2 conditional help

51 views
Skip to first unread message

Dimitri Yioulos

unread,
Nov 27, 2023, 9:10:55 AM11/27/23
to Ansible Project
Good day, all.

I've created a simple package update playbook, which also creates a report of updated packages:

- hosts: mytesthosts
  gather_facts: false
  become: yes

  tasks:
    - name: install all updates
      yum:
        name: '*'
        update_cache: yes
        state: latest
    - name: List updated packages
      shell: rpm -qa --last | grep "$(date +%a\ %d\ %b\ %Y)" |cut -f 1 -d " "|sort -n
      register: result
      tags:
        - lsupdates
    - debug:
        msg: "{{ result.stdout_lines }}"
      tags:
        - prupdates

    - local_action:
        module: copy
        content: |
          {% set t1 = now().strftime("%m/%d/%Y") %}
          {% for host in ansible_play_hosts %}
          {{ host }}:

          The following packages were updated on {{ t1 }}

          {{ hostvars[host]['result']['stdout'] }}


          {% endfor -%}
        dest: "/home/dyioulos/updates.txt"
      run_once: yes
      tags:
        - report


This does almost exactly what I want it to. The report looks like this:

test1:

The following packages were updated on 11/27/2023

alternatives-1.24-1.el9.x86_64
apr-util-1.6.1-23.el9.x86_64
apr-util-bdb-1.6.1-23.el9.x86_64
~

test2:

The following packages were updated on 11/27/2023

Note that there were no updates applied to test2. I'd like that to be reflected in the report, so that after "The following packages ...", it says "None". I would guess this requires if-then language in the inline jinja2. My searche for, and attempts at, a solution have been unsuccessful.

Your help, as always, would be appreciated.


Will McDonald

unread,
Nov 27, 2023, 10:10:21 AM11/27/23
to ansible...@googlegroups.com
I haven't tested this but does something like:

          {{ hostvars[host]['result']['stdout']|default("None", true) }}

Give the output you need?

cf:


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/eed79255-29d0-49c5-88e5-9b06577933a2n%40googlegroups.com.

Dimitri Yioulos

unread,
Nov 27, 2023, 10:25:57 AM11/27/23
to Ansible Project
Will, worked perfectly - thanks!
Reply all
Reply to author
Forward
0 new messages