Ansible - actions BEFORE gathering facts

21,192

Solution 1

Gathering facts is equivalent to running the setup module. You can manually gather facts by running it. It's not documented, but simply add a task like this:

- name: Gathering facts
  setup:

In combination with gather_facts: no on playbook level the facts will only be fetched when above task is executed.

Both in an example playbook:

- hosts: all
  gather_facts: no
  tasks:

    - name: Some task executed before gathering facts
      # whatever task you want to run

    - name: Gathering facts
      setup:

Solution 2

Something like this should work:

- hosts: my_hosts
  gather_facts: no

  tasks:
      - name: wait for SSH to respond on all hosts
        local_action: wait_for port=22

      - name: gather facts
        setup:

      - continue with my tasks...

The wait_for will execute locally on your ansible host, waiting for the servers to respond on port 22, then the setup module will perform fact gathering, after which you can do whatever else you need to do.

Solution 3

I was trying to figure out how to provision a host from ec2, wait for ssh to come up, and then run my playbook against it. Which is basically the same use case as you have. I ended up with the following:

- name: Provision App Server from Amazon
  hosts: localhost
  gather_facts: False
  tasks:  
    # ####  call ec2 provisioning tasks here  ####
    - name: Add new instance to host group
      add_host: hostname="{{item.private_ip}}" groupname="appServer"
      with_items: ec2.instances

- name: Configure App Server
  hosts: appServer
  remote_user: ubuntu
  gather_facts: True
  tasks:  ----configuration tasks here----

I think the ansible terminology is that I have two plays in a playbook, each operating on a different group of hosts (localhost, and the appServer group)

Share:
21,192
silverdr
Author by

silverdr

Updated on March 21, 2020

Comments

  • silverdr
    silverdr about 4 years

    Does anyone know how to do something (like wait for port / boot of the managed node) BEFORE gathering facts? I know I can turn gathering facts off

    gather_facts: no
    

    and THEN wait for port but what if I need the facts while also still need to wait until the node boots up?