Use of host and group variables in hosts patterns

I am trying to use a host variable (actually a group variable) in a
"hosts:" pattern in a playbook, but without success. Is this supposed to
work?

The use case is this: I want to write a playbook that is invoked by
passing an extra var named "target" in the command-line. The "target"
actually denotes the name of a ganeti-based cluster of virtualization
nodes, let's name it "mycluster.example.org". In the inventory there is
a group named "mycluster.example.org", which has two children groups
named "mycluster.example.org_nodes" (for ganeti nodes) and
"mycluster.example.org_instances" (for ganeti instances):

[mycluster.example.org:children]
mycluster.example.org_nodes
mycluster.example.org_instances

[mycluster.example.org_nodes]
node1.mycluster.example.org
node2.mycluster.example.org

The playbook has two plays. The first play must be run against the
master node and the other must be run against all other nodes (except
master). The master node is defined in a group variable of
"mycluster.example.org" group. So, I am trying for the first play the
following hosts pattern in the playbook, but it does not work:

- hosts: {{ hostvars[groups[target + '_nodes'][0]]['master_node'] }}

I am not sure, but it seems that hostvars/groups variables are not
available for use in hosts patterns.

it is not supposed to work at all. ​which host or group would it look at to set the hosts?

you might want to look at group_by to do dynamic groups based on variables that can be used in subsequent plays (in same run).

I actually got to workaround this by making the assumption that the first node in the “mycluster.example.org” group is the master node. So, the following hosts patterns work: Nevertheless, I think it would not hurt a feature addition to support host/group vars in the hosts patterns. It would not be something that we should suggest to users, but perhaps it would come handy in some scenarios that involve data-driven host matches. What do you think?

Oops, I actually meant “mycluster.example.org_nodes” group.

you used groups, which is allowed, what you cannot use is the ‘master_node’ variable, and that will never work.

you can have a play with group_by on ‘master_node’, that creates groups for the other 2