How to run apt update and upgrade via Ansible shell

I wouldn't recommend using shell for this, as Ansible has the apt module designed for just this purpose. I've detailed using apt below.

In a playbook, you can update and upgrade like so:

- name: Update and upgrade apt packages
  become: true
  apt:
    upgrade: yes
    update_cache: yes
    cache_valid_time: 86400 #One day

The cache_valid_time value can be omitted. Its purpose from the docs:

Update the apt cache if its older than the cache_valid_time. This option is set in seconds.

So it's good to include if you don't want to update the cache when it has only recently been updated.

To do this as an ad-hoc command you can run:

$ ansible all -m apt -a "upgrade=yes update_cache=yes cache_valid_time=86400" --become

ad-hoc commands are described in detail here

Note that I am using --become and become: true. This is an example of typical privilege escalation through Ansible. You use -u user and -K (ask for privilege escalation password). Use whichever works for you, this is just to show you the most common form.


Just to add a flavor on the answer. This one is an executable playbook in all the hosts specified in your inventory file.

- hosts: all
  become: yes
  tasks:
  - name: Update and upgrade apt packages
    apt:
      upgrade: yes
      update_cache: yes
      cache_valid_time: 86400 

Using Ubuntu 16.04, I did a little adjustement:

- name: Update and upgrade apt packages
  become: true
  apt:
    update_cache: yes
    upgrade: 'yes'

I juste put the upgrade yes between apostrophe to avoid un annoying warning:

[WARNING]: The value True (type bool) in a string field was converted to u'True' (type string). If this does
not look like what you expect, quote the entire value to ensure it does not change.

I would like just to comment into the original answer, but no permission, yet...

Ref: The value True (type bool) in a string field was converted to u'True' (type string)