Skip to content

Instantly share code, notes, and snippets.

@corny
Created August 11, 2015 23:35
Show Gist options
  • Save corny/1563378d459d74f8a696 to your computer and use it in GitHub Desktop.
Save corny/1563378d459d74f8a696 to your computer and use it in GitHub Desktop.
Ansible playbook that uses apt to upgrade packages and remove/purge unneeded packages
---
- hosts: all
environment:
LC_ALL: C
LANG: C
tasks:
- name: Update APT package cache
apt: update_cache=yes cache_valid_time=600
- name: Upgrade APT to the latest packages
apt: upgrade=dist
register: apt_result
- name: Autoremove unused packages
command: apt-get -y autoremove
register: apt_result
changed_when: "'packages will be REMOVED' in apt_result.stdout"
- name: Purge residual kernel packages
shell: apt-get remove -y --purge $(dpkg -l | grep "^rc\s*linux-image-" | awk '{print $2}' | tr '\n' ' ')
register: apt_result
changed_when: "'packages will be REMOVED' in apt_result.stdout"
@pakair
Copy link

pakair commented Feb 6, 2019

do I need to add sudo somewhere since I get permission issues ...

fatal: [bionic]: FAILED! => {"changed": false, "cmd": "apt-get update", "failed": true, "msg": "E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)\nE: Unable to lock directory /var/lib/apt/lists/\nW: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)\nW: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)", "rc": 100, "stderr": "E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)\nE: Unable to lock directory /var/lib/apt/lists/\nW: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)\nW: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)\n", "stdout": "Reading package lists...\n", "stdout_lines": ["Reading package lists..."]}

this is my first attempt with ansible so I'm less than a newbie :)

@Pmarva
Copy link

Pmarva commented Sep 27, 2019

if you are using non root account and want to do privilege escalation to root then you need to add
become: yes
become_user: root

to the apt-upgrade.yml file and when you execute script ad -K to the command: _ansible-playbook apt-upgrade.yml -K _ it will ask password then.

Another option is directly ssh as root or save root password to the protected place. Then also all hosts need to have same passwords

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment