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
- name: update apt cache
However, this quickly became an annoying overhead.
stat module coupled with
register came in handy.
- name: check apt last update
- name: update apt if needed
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.