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. TomDV says:

    Just what I needed.

  2. 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.

  3. 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. Enrique Zanardi says:

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

  5. Tim Stoop says:

    What would that file represent? The time it updated last?

  6. 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.

  7. Tim Stoop says:

    That’s strange, it works for us this way…

Leave a Reply

Kumina helps companies innovate with the power of open source software. As specialists in managed IT operations since 2007, our mission is simple: building and managing the perfectly tailored technical infrastructures that allow our clients to thrive.

With fully managed solutions, we help our customers unlock the full potential of the cloud and Kubernetes. Our team also supports organisations with IT consulting and Kubernetes training courses. Learn more about our services or get in touch, we would love to hear about your business and projects.