Ansible-playbook –limit more than one host

ansibleansible-playbook

For various reasons/limitations I cannot make new groups in the inventory file and need to use --limit/-l to specify the hosts.

I was told to do something like:

ansible-playbook -i /path/to/my/inventory/file.ini -l server.1.com server.2.com my-playbook.yml --check --diff

This was throwing an error:

ERROR! the playbook: server.2.com could not be found

From the Ansible Documentation on this subject I found that you could use a separate file to list all the hosts you want to limit.
Something like:

ansible-playbook -i /path/to/my/inventory/file.ini -l @list-to-limit.txt my-playbook.yml

However, I need to do it all inline without creating an additional file.

Best Answer

The same Common patters apply to the command-line option -l. Quoting the note:

"You can use either a comma (,) or a colon (:) to separate a list of hosts. The comma is preferred when dealing with ranges and IPv6 addresses."

For example, given the inventory

shell> cat hosts
[webservers]
test_01
test_02

[dbservers]
test_03
test_04

and the playbook

shell> cat pb.yml 
- hosts: all
  tasks:
    - debug:
        var: inventory_hostname

The various host's patterns work as expected. For example

  1. All hosts in webservers plus all hosts in dbservers
shell> ansible-playbook -i hosts pb.yml -l webservers:dbservers
...
ok: [test_01] => 
  inventory_hostname: test_01
ok: [test_02] => 
  inventory_hostname: test_02
ok: [test_03] => 
  inventory_hostname: test_03
ok: [test_04] => 
  inventory_hostname: test_04
  1. The hosts test_02 and test_04
shell> ansible-playbook -i hosts pb.yml  -l test_02,test_04

ok: [test_02] => 
  inventory_hostname: test_02
ok: [test_04] => 
  inventory_hostname: test_04
  1. All hosts in webservers except the host test_02
shell> ansible-playbook -i hosts pb.yml  -l webservers:\!test_02

  inventory_hostname: test_01