Using "short lived facts" and caching, Eg. ansible_uptime_seconds

I’m currently using ansible_uptime_seconds however that gives an old cached value a lot more than I’d expect it to (Eg. reboot the server, and then run some task on the server to register a variable but ansible_uptime_seconds is still from before the reboot).

I assume this is a known feature of facts, due to caching. And that’s probably fine for most facts, as most of my facts don’t change OS/ip/etc

But there are a few times where I’d really like these “can change more often” facts to be updated, and AFAICS the only workaround is to run the playbooks with --flush-cache?

Is there a better way to say “make sure this fact is accurate”?

Do people solve the problem by not using facts for these kinds of problems (Eg. parse /proc/uptime or uptime cmd output directly, and store that in a variable)?

Version: ansible core 2.14.18

Note that you can explicitly run the ansible.bulitin.setup module restricted to certain facts to update these. ansible_uptime_seconds seems to be part of hardware, so specifying gather_subset=[!all, !min, hardware] and filter=[uptime_seconds] updates only that value.

You can see this with: ansible localhost -m setup -a 'gather_subset=!all,!min,hardware filter=uptime_seconds' - it will only give you the uptime.

You can also ‘clear facts’, but this is not fine grained.

As far as I can see this still uses the cache, like having gather_facts: true which I was using (but not for everything). Also not sure of the exact syntax, but the obvious one blows up when I run ansible-playbook on it ;).

It does not. Cached facts only prevent automatic running of gather_facts when DEFAULT_GATHERING=smart, they have no effect on explicit fact gathering in a task. See I don't understand gather_subset - #12 by flowerysong

1 Like

Thanks, that post you linked to should also solve the syntax problems I was having.