Skip to content

Instantly share code, notes, and snippets.

@b0bu
Last active June 3, 2021 09:47
Show Gist options
  • Save b0bu/10fc8124a93683a43477cf9c972d673c to your computer and use it in GitHub Desktop.
Save b0bu/10fc8124a93683a43477cf9c972d673c to your computer and use it in GitHub Desktop.
conditionally gather facts in ansible

Fact gathering can take a long time, especially on centos/rhel boxes and especially on proxies where your open file limit might be high. 2-3 minutes or longer. If I have a play that's only supposed to run some of the time based on a combination or when: or tag: statements but I need that play to gather facts it can slow down / gather facts at the wrong play. This if anything, gives the illusion that that play is actually doing something when it's not even supposed to be running. When your automation runs in a pipelines and no ones watching it you want to make sure that the feedback and logging is as clean as possible. I.e. what ran was all that was supposed to run in the way it was supposed to be ran.

You can gather facts on a certain play based on whether the tag that runs that plays tasks was provided to the ansible engine. Now this play won't gather facts and won't log as having done anything unless keepalived is explicitly provided on the command line. Gathering of facts will fall through to subsequent plays where it's meant to happen.

- hosts: haproxy
  gather_facts: "{{ true if ('keepalived' in ansible_run_tags) else false }}"
  remote_user: root
  name: Configure keepalived
  tasks:
    - import_role: 
        name: keepalived
      vars:
        keepalived_frontend_check: "/usr/bin/pgrep keepalived"
      tags: ["never", "keepalived", "new"]
    - set_fact:
        keepalived_was_run: true
      tags: ["never", "keepalived", "new"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment