PageRenderTime 29ms CodeModel.GetById 16ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/ansible/runner/action_plugins/group_by.py

https://github.com/ajanthanm/ansible
Python | 106 lines | 63 code | 18 blank | 25 comment | 29 complexity | 7fe0a2eacb86fa9b6e0508f438148bfc MD5 | raw file
  1# Copyright 2012, Jeroen Hoekx <jeroen@hoekx.be>
  2#
  3# This file is part of Ansible
  4#
  5# Ansible is free software: you can redistribute it and/or modify
  6# it under the terms of the GNU General Public License as published by
  7# the Free Software Foundation, either version 3 of the License, or
  8# (at your option) any later version.
  9#
 10# Ansible is distributed in the hope that it will be useful,
 11# but WITHOUT ANY WARRANTY; without even the implied warranty of
 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13# GNU General Public License for more details.
 14#
 15# You should have received a copy of the GNU General Public License
 16# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
 17
 18import ansible
 19
 20from ansible.callbacks import vv
 21from ansible.errors import AnsibleError as ae
 22from ansible.runner.return_data import ReturnData
 23from ansible.utils import parse_kv, check_conditional
 24import ansible.utils.template as template
 25
 26class ActionModule(object):
 27    ''' Create inventory groups based on variables '''
 28
 29    ### We need to be able to modify the inventory
 30    BYPASS_HOST_LOOP = True
 31    TRANSFERS_FILES = False
 32
 33    def __init__(self, runner):
 34        self.runner = runner
 35
 36    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
 37
 38        # the group_by module does not need to pay attention to check mode.
 39        # it always runs.
 40
 41        # module_args and complex_args have already been templated for the first host.
 42        # Use them here only to check that a key argument is provided.
 43        args = {}
 44        if complex_args:
 45            args.update(complex_args)
 46        args.update(parse_kv(module_args))
 47        if not 'key' in args:
 48            raise ae("'key' is a required argument.")
 49
 50        vv("created 'group_by' ActionModule: key=%s"%(args['key']))
 51
 52        inventory = self.runner.inventory
 53
 54        result = {'changed': False}
 55
 56        ### find all groups
 57        groups = {}
 58
 59        for host in self.runner.host_set:
 60            data = {}
 61            data.update(inject)
 62            data.update(inject['hostvars'][host])
 63            conds = self.runner.conditional
 64            if type(conds) != list:
 65                conds = [ conds ]
 66            next_host = False
 67            for cond in conds:
 68                if not check_conditional(cond, self.runner.basedir, data, fail_on_undefined=self.runner.error_on_undefined_vars):
 69                    next_host = True
 70                    break
 71            if next_host:
 72                continue
 73
 74            # Template original module_args and complex_args from runner for each host.
 75            host_module_args = template.template(self.runner.basedir, self.runner.module_args, data)
 76            host_complex_args = template.template(self.runner.basedir, self.runner.complex_args, data)
 77            host_args  = {}
 78            if host_complex_args:
 79                host_args.update(host_complex_args)
 80            host_args.update(parse_kv(host_module_args))
 81
 82            group_name = host_args['key']
 83            group_name = group_name.replace(' ','-')
 84            if group_name not in groups:
 85                groups[group_name] = []
 86            groups[group_name].append(host)
 87
 88        result['groups'] = groups
 89
 90        ### add to inventory
 91        for group, hosts in groups.items():
 92            inv_group = inventory.get_group(group)
 93            if not inv_group:
 94                inv_group = ansible.inventory.Group(name=group)
 95                inventory.add_group(inv_group)
 96            for host in hosts:
 97                if host in self.runner.inventory._vars_per_host:
 98                    del self.runner.inventory._vars_per_host[host]
 99                inv_host = inventory.get_host(host)
100                if not inv_host:
101                    inv_host = ansible.inventory.Host(name=host)
102                if inv_group not in inv_host.get_groups():
103                    result['changed'] = True
104                    inv_group.add_host(inv_host)
105
106        return ReturnData(conn=conn, comm_ok=True, result=result)