Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
Mitch Avatar asked Apr 07 '16 19:04

Mitch


People also ask

How do you use ansible facts?

Using the Ansible playbook To access the variables from Ansible facts in the Ansible playbook, we need to use the actual name without using the ansible keyword. The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts.

Why we need ad hoc ansible commands scenario where you have used ansible ad hoc command?

Use cases for ad hoc tasks. ad hoc tasks can be used to reboot servers, copy files, manage packages and users, and much more. You can use any Ansible module in an ad hoc task. ad hoc tasks, like playbooks, use a declarative model, calculating and executing the actions required to reach a specified final state.


1 Answers

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.

like image 155
shaps Avatar answered Sep 18 '22 14:09

shaps