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
You only have the following options with the current version of Ansible:
- Specify the tags on the command line
- Use a variable instead of a tag to conditionally run tasks
- Split your webserver role into multiple roles and use role dependencies for the common tasks
This feature request has come up on the mailing list a few times and I haven't seen any indication from the dev team that it will be added as a new feature.
Best Answer
The reason you get an error is because you're accessing a variable that has never been set. You seem to be using the existance of the extra-var as an indication that you want composer install to run (i.e. you're never passing --extra-vars="composer-install=false"), so you could go with
is defined
:But the variables can be passed through filters, which can be useful for this case, because it still allows you to pass true/false while not defining the variable at all still works:
Some more on conditionals can be found here: http://docs.ansible.com/playbooks_conditionals.html
The jinja2 filters are very useful for more than one reason, so more on those here: http://docs.ansible.com/playbooks_variables.html#jinja2-filters
And finally the complete list of built-in jinja2 filters here: http://jinja.pocoo.org/docs/dev/templates/#builtin-filters