11

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.

ConstantFun
  • 243
  • 1
  • 2
  • 8

3 Answers3

13

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
Vladimir Botka
  • 3,791
  • 6
  • 17
5

Here is how to do it:

ansible-playbook ./your_playbook --limit "host1,host2,host3,host4"
Vitaly Evodin
  • 51
  • 1
  • 1
3

I was spacing out and at the time I totally thought I could just list out all the hosts inline and ansible-playbook would understand.

I fixed my issue by simply adding -l before each host name in the command.

(I realize this might not be a 'best practice')

My final command looked something like:

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

ConstantFun
  • 243
  • 1
  • 2
  • 8
  • 3
    You can also use a single `-l` and [separate the hosts with a `,` or a `:`](https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html#common-patterns). – Gerald Schneider Aug 25 '20 at 06:31