Puppet Tips&Tricks: Running apt-get update only when needed

A small example on how you can make apt-get update only run if a) the machine rebooted and b) something changed in /etc/apt. We use cron-apt to run an update every night, to keep the machine up-to-date, so this is really all we need. If you need to add a repository before you can install a package (say, you want to install a package from the Kumina Debian Repository), you can now do it in one puppet run, if you make sure your package resource depends on apt-get update. This is the code:

# Run apt-get update when anything beneath /etc/apt/ changes
exec { "apt-get update":
command => "/usr/bin/apt-get update",
onlyif => "/bin/sh -c '[ ! -f /var/cache/apt/pkgcache.bin ] || /usr/bin/find /etc/apt/* -cnewer /var/cache/apt/pkgcache.bin | /bin/grep . > /dev/null'",
}

Update aug 2 2011: Thanks to Enrique’s comment (see in the comments), we’ve made the script slightly prettier. Thanks Enrique!

Tags: , , , , , , ,


7 Responses to “Puppet Tips&Tricks: Running apt-get update only when needed”

  1. Ash says:

    I had to change command to:

    command => “/usr/bin/apt-get update && /usr/bin/touch /var/cache/apt/pkgcache.bin”,

    Otherwise it would keep wanting to run an apt-get update until a package was changed.

  2. Enrique Zanardi says:

    Also there’s /var/lib/apt/periodic/update-stamp for those that have set APT::Periodic::Update-Package-Lists

  3. Enrique Zanardi says:

    What about using /var/cache/apt/pkgcache.bin or/and /var/cache/apt/srcpkgcache.bin instead of /tmp/apt.update ? Those will be updated by “apt-get update” anytime there’s a change in the repositories, so if your sources list is newer than those, you must update.

    • Tim Stoop says:

      Hi Enrique,

      Thanks for that! I didn’t know about those files, but they are way better than our temp-file solution, of course. I’ll ammend the article.

  4. TomDV says:

    Awesome!
    Just what I needed.

Kumina designs, builds, operates and supports Kubernetes solutions that help companies thrive online. As Certified Kubernetes Service Partner, we know how to build real solutions.