22

How to run Ansible without hosts file?

just like:

$ ansible --"Some Options" IP  -a 'uptime'
slm
  • 15,396
  • 12
  • 109
  • 124
xiaoxiaoguo
  • 333
  • 1
  • 2
  • 8

4 Answers4

36

you can do like this:

ansible all -i "<hostname-or-ip>," -a 'uptime'

Note the , at the end of the IP address, or it will be considered a hosts inventory filename.

Here is an example for reference:

ansible all -i "192.168.33.100," -a 'uptime'

192.168.33.100 | SUCCESS | rc=0 >>
 12:05:10 up 10 min,  1 user,  load average: 0.46, 0.23, 0.08
haridsv
  • 9,065
  • 4
  • 62
  • 65
Arbab Nazar
  • 22,378
  • 10
  • 76
  • 82
8

Hosts can be given to ansible using three ways

  • Using inventory path in ansible.cfg which is /etc/ansible/host by default

  • Using hosts file

     ansible -i /tmp/hosts -a 'uptime' all
    
  • Using hosts ip as comma separated host list. Take care of the comma in the end of the list

     ansible -i "192.168.1.16,192.168.1.80:2222," -a 'uptime' all
    

From ansible --help you can get -i option description

-i INVENTORY, --inventory-file=INVENTORY
                    specify inventory host path
                    (default=/etc/ansible/hosts) or comma separated host
                    list.
slm
  • 15,396
  • 12
  • 109
  • 124
Nasr
  • 2,482
  • 4
  • 26
  • 31
0

If you want run playbook at once or some more and not whole list, you can try with -l|--limit "your.node.local"

ansible-playbook -i inventory.hosts --limit your.node.local user.yml
cray
  • 145
  • 6
0

Both the answers here have most of what you need but in order to SSH to a remote host you need to tell ansible what user to SSH as, especially if it's different on the system you're running ansible from and the remote targets.

For example, I have 4 RPi4 systems with Ubuntu 20.04 on them. To access them with an Ansiible ad-hoc command:

$ ansible -i "k8s-02a,k8s-02b,k8s-02c,pi-vpn," -a uptime all -u ubuntu
pi-vpn | CHANGED | rc=0 >>
 12:47:26 up  7:52,  1 user,  load average: 0.14, 0.14, 0.10
k8s-02c | CHANGED | rc=0 >>
 12:47:27 up  7:58,  1 user,  load average: 0.06, 0.10, 0.09
k8s-02a | CHANGED | rc=0 >>
 12:47:27 up  7:58,  1 user,  load average: 0.43, 0.50, 0.47
k8s-02b | CHANGED | rc=0 >>
 12:47:27 up  7:58,  1 user,  load average: 0.08, 0.06, 0.04

Here I'm providing a list of my hostnames to -i and also directing ansible to use the username ubuntu.

NOTE: My ansible version:

$ ansible --version | grep ^ans
ansible 2.9.11
slm
  • 15,396
  • 12
  • 109
  • 124