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