How to avoid two or several hosts reading the same value when using loops in Ansible?

59 Views Asked by At

I have this playbook:

---
- hosts: all
  tasks:
    - command: echo {{ item }}
      with_items: [ item1forhost1, item2forhost2]

This results in:

TASK [command] *****************************************************************
changed: [host1] => (item=item1forhost1)
changed: [host2] => (item=item1forhost1)
changed: [host1] => (item=item2forhost2)
changed: [host2] => (item=item2forhost2)

Every host is reading the same line, where as I want host1 to read itemfforhost1 and host2 to read item2forhost2. How can this be done? I'm looking for something like this:

TASK [command] *****************************************************************
changed: [host1] => (item=item1forhost1)
changed: [host2] => (item=item2forhost2)
1

There are 1 best solutions below

0
On

Following up on @techraf’s solution, here is what you can do. In your ansible directory, create a directory called host_vars. Underneath that directory, create two files called host1.yml and host2.yml. In host1.yml put:

---
echo_value: itemforhost1

And in host2.yml put:

---
echo_value: itemforhost2

Now in your playbook, you can write:

---
- hosts: all
  tasks:
    - command: echo {{ echo_value }}