sorin
sorin

Reputation: 170758

How can I use ansible facts in order to skip execution of some sections?

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

Upvotes: 0

Views: 891

Answers (1)

nitzmahone
nitzmahone

Reputation: 13950

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.

Upvotes: 0

Related Questions