community.general/lib/ansible/inventory/group.py

78 lines
2.1 KiB
Python
Raw Normal View History

2012-05-05 20:37:28 +00:00
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
class Group(object):
''' a group of ansible hosts '''
2012-05-05 20:37:28 +00:00
__slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups' ]
2012-05-05 20:37:28 +00:00
def __init__(self, name=None):
2012-05-05 20:37:28 +00:00
self.name = name
self.hosts = []
self.vars = {}
self.child_groups = []
self.parent_groups = []
if self.name is None:
2012-07-15 13:32:47 +00:00
raise Exception("group name is required")
2012-05-05 20:37:28 +00:00
def add_child_group(self, group):
2012-05-05 20:37:28 +00:00
if self == group:
raise Exception("can't add group to itself")
self.child_groups.append(group)
group.parent_groups.append(self)
def add_host(self, host):
2012-05-05 20:37:28 +00:00
self.hosts.append(host)
host.add_group(self)
def set_variable(self, key, value):
2012-05-05 20:37:28 +00:00
self.vars[key] = value
def get_hosts(self):
2012-05-05 20:37:28 +00:00
hosts = []
for kid in self.child_groups:
hosts.extend(kid.get_hosts())
hosts.extend(self.hosts)
return hosts
2012-05-05 20:37:28 +00:00
def get_variables(self):
2012-05-05 20:37:28 +00:00
vars = {}
# FIXME: verify this variable override order is what we want
for ancestor in self.get_ancestors():
2012-07-15 13:32:47 +00:00
vars.update(ancestor.get_variables())
2012-05-05 20:37:28 +00:00
vars.update(self.vars)
return vars
def _get_ancestors(self):
2012-05-05 20:37:28 +00:00
results = {}
for g in self.parent_groups:
results[g.name] = g
results.update(g._get_ancestors())
return results
def get_ancestors(self):
return self._get_ancestors().values()