Filtering variables with a key value in ansible

Viewed 45

I have the following data structure in ansible

hosts:
  host-1:
    roles: [ 'master' ]
    index_ip: 2
    outline: false
  host-2:
    roles: [ 'backend' ]
    index_ip: 3
    outline: false
  host-3:
    roles: [ 'frontend' ]
    index_ip: 4
    outline: false
  host-4:
    roles: [ 'frontend' ]
    index_ip: 5
    outline: false

I need to get a list of hosts depending on the roles of the host.

Example: Get the hosts with roles 'master' which should result in [ 'host-1' ]

Example: Get the hosts with roles 'frontend' which should result in [ 'host-3', 'host-4' ]

I am new to ansible and find this difficult to do. Any easy way of filtering this?

The data is used to generate starturp files that will spawn processes over several hosts. Example:

central_supervisor:
  - hostlist: [ host-1 ]
    corelist: [ 0 ]

subsystem:
  - hostlist: [ host-2 ]
    sa_corelist: [0]
    app_corelist: [[1,2,3,4,5,6,7,8,9,10,17,18,19,20,21,22,23,24,25,26], [1,2,3,4,5,6,7,8,9,10,17,18,19,20,21,22,23,24,25,26]]

data_router:
  - hostlist: [ host-3, host-4 ]
    corelist_e: [16]
    corelist_c: [15,31]

data_processor:
  - hostlist: [ host-3, host-4 ]
    capabilities: all
    corelist_e: [16]
    corelist_c: [15,31]
1 Answers

I have made it in my jinja2 code instead

{% set frontends = [] %}
{% for hostname in item.hosts.keys() if 'frontend' in item.hosts[hostname].roles %}
   {{ frontends.append(hostname) }}
{% endfor %}
Related