Last Updated: February 25, 2016
·
15.69K
· alisaifee

doing an apt-get update in ansible only if a condition is met

I ran into this problem recently where certain images that I would spin up would not have an updated apt cache and would fail to install certain packages. My knee jerk solution was to add an 'always-run' initialisation command

task:
 - name: update apt cache 
    apt: >
        update_cache=yes 

However, this quickly became an annoying overhead.

The stat module coupled with register came in handy.

pre_tasks:
  - name: check apt last update
    stat: path=/var/cache/apt
    register: apt_cache_stat
  - name: update apt if needed
    apt: update_cache=yes
    when: ansible_date_time.epoch|float - apt_cache_stat.stat.mtime > 60*60*12

In the above example I'm only updating the cache if it hadn't been modified since the last 12 hours. You can you choose your own threshold.

1 Response
Add your response

Just FYI, there is now a convenient cache_valid_time parameter for the apt module:

Example:

Only run "update_cache=yes" if the last one is more than more than 3600 seconds ago

- apt: update_cache=yes cache_valid_time=3600

From:
http://www.ansibleworks.com/docs/modules.html

over 1 year ago ·