Use Ansible facts in an Ansible ad-hoc command

Mitch picture Mitch · Apr 7, 2016 · Viewed 7.9k times · Source

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.

Answer

shaps picture shaps · Apr 8, 2016

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.