Execute task for specific host.

Hello all!
I have playbook with following parts:

`
vars:
servers:

  • { address: “192.168.122.12”, role: “upstream” }
  • { address: “192.168.122.13”, role: “downstream” }
  • { address: “192.168.122.14”, role: “downstream” }
    task:
  • name: Task
    command: “/usr/sbin/somecommand”
    `

How I can execute task only on upstream or downstream servers? Any help appreciated.

P.S. I try following part, but it doesn’t work:
`
task:

  • name: Task
    command: “/usr/sbin/somecommand”
    when: “servers.role == upstream”

`

And got error:

fatal: [vm12-centos7] => error while evaluating conditional: servers.role == upstream
fatal: [vm13-centos7] => error while evaluating conditional: servers.role == upstream

fatal: [vm14-centos7] => error while evaluating conditional: servers.role == upstream

​try this:

when: servers.role ==​
​ ​
"
​​
​upstream"

Hi Alexey,

You do not need to quote a whole string here, could you try

when: servers.role == "upstream"

-- Best, Igor

IMHO, it's better to work with groups in this scenario:

# inventory
[downstream]
192.168.122.12
192.168.122.14

[upstream]
192.168.122.12

You can either define multiple plays targeting each group with a set of
tasks/roles:

# playbook

Yes, I am tried use quotes, and this not working.

Eventually I rewrote playbook using groups and include statements for tasks, and it works fine. But, in the current circumstances I’m not quite satisfied, I need to make a single file playbook. Yes, I know it’s not quite right and not a best practice )))

Alexey,

The easiest way to do this is to use hostvars in your inventory and set a “role” variable for each host. Then, in your task you could be:

tasks:

  • name: Task
    command: “/usr/bin/somecommand”
    when: role == “upstream”

Alternatively, if you want to set the variables here, this would work (tested):

Thanks, it’s good for me!