Search code examples
ansibleansible-factsansible-ad-hoc

Use Ansible facts in an Ansible ad-hoc command


Is it possible to use what would normally be included in ansible_facts in an Ansible adhoc command?

For example, I have a file at /tmp/myFile on all of my servers and I'd like to do:

ansible all -i [inventory file] -m fetch -a "src=/tmp/myFile dest=myFile-[insert ansible_hostname here]"

Without having to make a whole playbook for it.


Solution

  • No you cannot refer to ansible facts in ansible cli. This is because when you run ansible ... -m fetch you are not getting the facts of the host(s) you are running on. The facts are gathered with setup module ( you can try that by doing ansible ... -m setup. Anyway, this can be addressed with a simple playbook like

    # file: fetchfile.yml
    - hosts: all 
      tasks:
        - fetch: src=/tmp/myFile dest=myFile-{{ inventory_hostname }}
    
    $ ansible-playbook -i [inventory_file] fetchfile.yml
    

    ansible-playbook runs the setup module implicitly, so you will have access to all the facts as variables.