Debian Codegraph @

lib/ansible/plugins/lookup/inventory_hostnames.py

raw
1 # (c) 2012, Michael DeHaan <[email protected]>
2 # (c) 2013, Steven Dossett <[email protected]>
3 # (c) 2017 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 DOCUMENTATION = """
9 name: inventory_hostnames
10 author:
11 - Michael DeHaan
12 - Steven Dossett (!UNKNOWN) <[email protected]>
13 version_added: "1.3"
14 short_description: list of inventory hosts matching a host pattern
15 description:
16 - "This lookup understands 'host patterns' as used by the C(hosts:) keyword in plays
17 and can return a list of matching hosts from inventory"
18 notes:
19 - this is only worth for 'hostname patterns' it is easier to loop over the group/group_names variables otherwise.
20 """
21
22 EXAMPLES = """
23 - name: show all the hosts matching the pattern, i.e. all but the group www
24 ansible.builtin.debug:
25 msg: "{{ item }}"
26 with_inventory_hostnames:
27 - all:!www
28 """
29
30 RETURN = """
31 _hostnames:
32 description: list of hostnames that matched the host pattern in inventory
33 type: list
34 """
35
36 from ansible.errors import AnsibleError
37 from ansible.inventory.manager import InventoryManager
38 from ansible.plugins.lookup import LookupBase
39
40
41 class LookupModule(LookupBase):
42 def run(self, terms, variables=None, **kwargs):
43 manager = InventoryManager(self._loader, parse=False)
44 for group, hosts in variables['groups'].items():
45 manager.add_group(group)
46 for host in hosts:
47 manager.add_host(host, group=group)
48
49 try:
50 return [h.name for h in manager.get_hosts(pattern=terms)]
51 except AnsibleError:
52 return []