0

I want to speed-up ansible playbook execution by avoiding to call some sections that do not have to be called more often than once a day or so.

I know that facts are supposed to allow us to implement this but it seems almost impossible to find some basic example of: setting a fact, reading it and doing something if this it has a specific value, setting a default value for a fact.

- name: "do system update"
  shell: echo "did it!"
- set_fact:
    os_is_updated: true

If my impression or facts are nothing else than variables that can be saved, loaded and caches between executions?

Let's assume hat ansible.cfg is already configured to enable fact caching for two hours.

[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_timeout = 7200
fact_caching_connection = /tmp/facts_cache
techraf
  • 64,883
  • 27
  • 193
  • 198
sorin
  • 161,544
  • 178
  • 535
  • 806

1 Answers1

0

By its nature as a workstation CLI tool, Ansible doesn't have any built-in persistence mechanism (pretty much by design). There are some fact caching plugins that will use external stores (eg, Redis, jsonfile), but I'm not generally a fan.

If you want to persist stuff like that between runs yourself on the target machine(s), you can store them as local facts in /etc/ansible/facts.d (or an arbitrary location if you call setup yourself), and they'll come back from gather_facts under the ansible_local dictionary var. Assuming you're running on a *nix-flavored platform, something like:

- hosts: myhosts
  tasks:
  - name: do update no more than every 24h
    shell: echo "doing updates..."
    when: (lookup('pipe', 'date +%s') | int) - (ansible_local.last_update_run | default(0) | int) > 86400
    register: update_result

  - name: ensure /etc/ansible/facts.d exists
    become: yes
    file:
      path: /etc/ansible/facts.d
      state: directory

  - name: persist last_update_run
    become: yes
    copy:
      dest: /etc/ansible/facts.d/last_update_run.fact
      content: "{{ lookup('pipe', 'date +%s') }}"
    when: not update_result | skipped

Obviously the facts.d dir existence stuff is setup boilerplate, but I wanted to show you a fully-working sample.

nitzmahone
  • 13,720
  • 2
  • 36
  • 39
  • Sorry if I was not clear but I assumed that I do already have the caching configured, so what I am looking is for an example of "do x if x was not already done in the last 2 hours (caching timeout). – sorin Apr 13 '16 at 19:33
  • For some reason, set_fact is explicitly not persisted to a fact cache (not sure why). https://github.com/ansible/ansible/blob/26209342a28ad70775fa303035a12f4ff77c5f2e/lib/ansible/plugins/strategy/__init__.py#L328 – nitzmahone Apr 13 '16 at 23:09