Make it easy to discover which groups a server belongs to
User story
As someone developing a Rex task I would like to find out which groups a server is in so I can make decisions based on its group membership
For one service I run, I want to generate different configuration files based on the groups the server belongs to. I have written code to do this, but it's horrid. As far as I can tell, Rex doesn't currently provide a better approach.
Describe the solution you'd like
In my task, I'd like to call something like connection->server->groups or perhaps groups_for($hostname) which returns a list of the groups the server belongs to. Alternatively, it might be easier to run something like server_is_in_group($hostname) which would return a boolean.
Describe alternatives you've considered
My current code calls keys %Rex::Group::groups to get a list of all groups that exist. I feel bad that I depend on an undocumented private variable. I then call get_group_object() and get_servers() from the undocumented Rex::Group module, which also feels awkward.
Additional context
As well as messing about in Rex's internals, my current approach is inefficient as it walks across data structures associated with groups, instead of using data structures that focus on groups. I only work with a few tens of hosts, but if I had thousands, repeatedly iterating over group-centric data structures might slow Rex down.
Hmm, this sounds like a duplicate of #537. Which was resolved on #595 by adding the exact same connection->server->groups interface (and a connection->server->group alias for the same).
Could you try using that, and see if it fits your purposes, please? It might be the case that we can convert this into a "docs needed" bug.
Those commands don't list all groups that a server belongs to. I created the following Rexfile:
use strict;
use warnings;
use Rex;
group mygroup => qw( X Y Z );
group another => qw( X Y Z );
task example => sub {
my @group = connection->server->groups;
use Data::Dumper;
warn Dumper \@group;
};
I replaced X, Y and Z with three hosts I have SSH access to. Then I ran rex -G mygroup example which reported for each of the three servers:
$VAR1 = [
'mygroup'
];
I want to know all the groups a server belongs to, not just the one I'm currently deploying to.