Search code examples
ansibleyamlansible-2.xansible-inventory

How to use host variables in when condition in ansible playbook


I am trying to execute my task only when the host name has the variable servers=admin.

I am trying to execute the below playbook but I am facing an error.
I am trying this because it is similar to something which works for me like inventory_hostname in groups['production']. I would like to run the task only when the server variable has admin in it.

My host file:

[production]
host1 servers=admin,server1
host2 servers=server2
host3 servers=admin,server3
host4 servers=server4
host5 servers=server5
host6 servers=admin,server6

My task:

- name: run cmd
  shell: hostname
  register: op
  when:
    - inventory_hostvars in servers['admin']

My task should run only on host1, host3 and host6.


Solution

  • servers is a variable containing a string that you declare on each host. If you run a taks on e.g host3 it will be equal to admin,server3. The conditional you are looking for is

    when: "'admin' in servers"
    # or
    when: servers is search('admin')
    

    Now, I think you are simply reinventing the wheel since you can achieve this much more easily and clearly with groups as you pointed out yourself. The above solution would make it harder for example to get a list of all servers having admin somewhere in the servers variable compared to just addressing a group name.

    my_admin_servers: "{{ groups['prod'] | map('extract', hostvars) | selectattr('servers', 'search', 'admin') | map(attribute='inventory_hostname') | list }}"
    

    This is how I would do it:

    Your inventory

    [production]
    host1
    host2
    host3
    host4
    host5
    host6
    
    [admin]
    host1
    host3
    host6
    

    And your new conditional:

    when: inventory_hostname in groups['admin']