Turns out it is possible to enter a host name directly into the playbook, so running the playbook with hosts: imac-2.local
will work fine. But it's kind of clunky.
A better solution might be defining the playbook's hosts using a variable, then passing in a specific host address via --extra-vars
:
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
Running the playbook:
ansible-playbook user.yml --extra-vars "target=imac-2.local"
If {{ target }}
isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. Overall, this seems like a much safer way to construct a potentially destructive playbook.
Playbook targeting a single host:
$ ansible-playbook user.yml --extra-vars "target=imac-2.local" --list-hosts
playbook: user.yml
play #1 (imac-2.local): host count=1
imac-2.local
Playbook with a group of hosts:
$ ansible-playbook user.yml --extra-vars "target=office" --list-hosts
playbook: user.yml
play #1 (office): host count=3
imac-1.local
imac-2.local
imac-3.local
Forgetting to define hosts is safe!
$ ansible-playbook user.yml --list-hosts
playbook: user.yml
play #1 ({{target}}): host count=0
Vagrantfile is just a plain ruby file, so you can generate inventory file from it:
File.open('ansible/hosts/vagrant' ,'w') do |f|
f.write "[default]\n"
f.write "#{VAGRANT_NETWORK_IP} ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key\n"
end
By default vagrant box starts with name "default", so I usually limit ansible-managed hosts to vagrant's one (you can set ansible.limit = "default").
If you want to have several vagrant boxes with one inventory, you can define that boxes in one Vagrantfile and generate inventory for it.
Best Answer
Due to the fact that I answered this in 2014, I have updated my answer to account for more recent versions of ansible.
Yes, you can do it at the host/inventory level (Which became possible on newer ansible versions) or global level:
inventory:
Add the following.
host:
Add the following.
hosts/inventory options will work with connection type
ssh
and notparamiko
. Some people may strongly argue that inventory and hosts is more secure because the scope is more limited.global:
Ansible User Guide - Host Key Checking
You can do it either in the
/etc/ansible/ansible.cfg
or~/.ansible.cfg
file:Or you can setup and env variable (this might not work on newer ansible versions):