Search code examples
ansibleansible-2.xansible-inventory

Unable to select a particular host from inventory file in ansible


I went through a tutorial to transfer files between two servers directly using synchronize command and I am trying to transfer a file from source to destination where source will have 1 server and destination will have multiple servers in the inventory file as seen below:

[source]
server_1

[destination]
server_2
server_3
server_4

and based on a specific condition, I will select which server I will "synchronize push" to transfer the file. But I tried many methods to extract the server but I am unable to even pick a host:

-hosts: "{{ groups['destination'][0] }}"

-hosts: "{{destination.0}}"

-hosts: "{{destination[0]}}"

Those all throw me the below error:

The offending line appears to be:

  • hosts: "{{ destination }}"
    ^ here

We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance:

with_items:
  - {{ foo }}

Should be written as:

with_items:
  - "{{ foo }}"

How do I select the destination server from inventory file in ansible playbook?


Solution

  • I think you are trying to use Inventory group [destination] in playbook.

    hosts: "{{ destination }}" ^ here

    This should be without bracket instead of.

    hosts: destination

    And if you want to run on specific match host then

    hosts: destination[2:3]

    Also you can use delegate if you want to run task to specific host.

    delegate_to: {{ hostname }}