|
| 1 | +# Copyright (c) 2019 StackHPC Ltd. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | + |
| 16 | +from ansible import errors |
| 17 | +import jinja2 |
| 18 | +import re |
| 19 | + |
| 20 | +# Pattern to match a hostname with numerical ending |
| 21 | +pattern = re.compile("^(.*\D(?=\d))(\d+)$") |
| 22 | + |
| 23 | +def _get_hostvar(context, var_name, inventory_hostname=None): |
| 24 | + if inventory_hostname is None: |
| 25 | + namespace = context |
| 26 | + else: |
| 27 | + if inventory_hostname not in context['hostvars']: |
| 28 | + raise errors.AnsibleFilterError( |
| 29 | + "Inventory hostname '%s' not in hostvars" % inventory_hostname) |
| 30 | + namespace = context["hostvars"][inventory_hostname] |
| 31 | + return namespace.get(var_name) |
| 32 | + |
| 33 | +@jinja2.contextfilter |
| 34 | +def group_hosts(context, group_names): |
| 35 | + return {g:_group_hosts(context["groups"].get(g, [])) for g in sorted(group_names)} |
| 36 | + |
| 37 | +def _group_hosts(hosts): |
| 38 | + results = {} |
| 39 | + unmatchable = [] |
| 40 | + for v in hosts: |
| 41 | + m = pattern.match(v) |
| 42 | + if m: |
| 43 | + prefix, suffix = m.groups() |
| 44 | + r = results.setdefault(prefix, []) |
| 45 | + r.append(int(suffix)) |
| 46 | + else: |
| 47 | + unmatchable.append(v) |
| 48 | + return ['{}[{}]'.format(k, _group_numbers(v)) for k, v in results.iteritems()] + unmatchable |
| 49 | + |
| 50 | +def _group_numbers(numbers): |
| 51 | + units = [] |
| 52 | + prev = min(numbers) |
| 53 | + for v in sorted(numbers): |
| 54 | + if v == prev + 1: |
| 55 | + units[-1].append(v) |
| 56 | + else: |
| 57 | + units.append([v]) |
| 58 | + prev = v |
| 59 | + return ','.join(['{}-{}'.format(u[0], u[-1]) if len(u) > 1 else str(u[0]) for u in units]) |
| 60 | + |
| 61 | +class FilterModule(object): |
| 62 | + |
| 63 | + def filters(self): |
| 64 | + return { |
| 65 | + 'group_hosts': group_hosts |
| 66 | + } |
0 commit comments