Complex host patterns

Hi All

When working with host patterns, is it possible to craft one that says “must be in group X and must be in either group Y, W and Z”?

e.g. host must be in group “webserver” but it must also be in either group dc1, dc2 or dc3.

I can see how to check that webserver is part of dc1 (webserver,&dc1) but not sure how to build it with multiple “OR” on the “AND” (something like “webserver,&(dc1,dc2,dc3)” is what I’m looking for but it doesn’t work)

Cheers
Gonz

There is an example in the doc (you posted the link).

webservers:dbservers:&staging
The above configuration means “all machines in the groups ‘webservers’ and ‘dbservers’ are to be managed if they are in the group ‘staging’ also, …

Not quite. How about “all machines in the groups webservers and dbservers are to be managed only if they are part of staging OR qa”?

Put the dc1, dc2 and dc3 group in a group called dc and then you can use

  webserver:&dc

You’re trying to do it backwards. Build the union of your other groups and do the intersection with webserver.

&webserver,dc1,dc2,dc3

Thanks, good suggestion. I suppose there’s no way to say “must be webserver OR dbserver AND in (dc1 OR dc2 OR dc3)”?

  • Gonz

I’d like to be able to do this on the fly so creating a custom group like that is not ideal.

  • Gonz

Not in a host pattern. no. If you can’t do it in the inventory, you can do it with a dynamic group:

`

  • hosts: localhost
    gather_facts: false
    tasks:

  • add_host:
    name: “{{ item }}”
    groups: target_hosts
    when: hostvars[item].group_names | intersect([‘dc1’, ‘dc2’, ‘dc3’])
    loop: “{{ groups.webserver | union(groups.dbserver) }}”

  • hosts: target_hosts
    tasks:

  • command: /bin/true

`

Thanks for that! Very useful.

  • Gonz