Trying to setup ubuntu security patching only

from the command line in ubuntu i can run:

apt list --upgradable | grep security | cut -d/ -f1 | xargs sudo apt-get install -y

but the ansible I have is :


  • hosts: all
    become: true
    become_user: root
    tasks:
    • name: Update apt repo and cache on all Debian/Ubuntu boxes
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600

    • name: Upgrade all packages on servers
      apt: upgrade=dist force_apt_get=yes

    • name: Check if a reboot is needed on all servers
      register: reboot_required_file
      stat: path=/var/run/reboot-required get_checksum=no

    • name: Reboot the box if kernel updated
      reboot:
      msg: “Reboot initiated by Ansible for kernel updates”
      connect_timeout: 5
      reboot_timeout: 300
      pre_reboot_delay: 0
      post_reboot_delay: 30
      test_command: uptime
      when: reboot_required_file.stat.exists

how should I modify :

apt: update_cache=yes force_apt_get=yes cache_valid_time=3600

I think I might have to use
shell: apt list --upgradable | grep security | cut -d/ -f1 | xargs sudo apt-get install -y

instead of that apt: task does that make sense?

A long time ago, I remember reading that Ansible makes simple things hard and hard things simple. This kind of reminds me of that :slight_smile:

Modules are great for reducing the maintenance burden on you/your team and providing an easy interface for more complicated checks. When a module doesnt meet your needs, you have two options:

  1. Write a new module or open a PR to update an existing module
  2. Use the shell/command module

I think your approach is great, given the constraints you’ve found. There is one change I would suggest though. I would use the shell module to get the list of packages, and then pass that into the apt module. That way, you get the best of both worlds. Something like this (I didnt test it):

- name: Get security patches
  ansible.builtin.shell: apt list --upgradable | grep security | cut -d/ -f1
  changed_when: false
  register: _security_pkg_list

- name: Update
  ansible.builtin.apt:
    name: "{{ _security_pkg_list.stdout_lines }}"
....

hmmm is there a command that I can use to write _security_pkg_list out to a file?

like

  • name: write to file
    shell: echo “{{ _security_pkg_list.stdout_lines }}” | /root/{{ inventory_hostname }}.txt

You can use ansible.builtin.copy with content like so:

- name: Use copy module to write the stdout_lines
  ansible.builtin.copy:
    content: "{{ _security_pkg_list.stdout_lines }}"
    dest: "/root/{{ inventory_hostname }}.txt"
    owner: root
    group: root
1 Like