Debian Codegraph @

lib/ansible/plugins/inventory/host_list.py

raw
1 # Copyright (c) 2017 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 DOCUMENTATION = r"""
7 name: host_list
8 version_added: "2.4"
9 short_description: Parses a 'host list' string
10 description:
11 - Parses a host list string as a comma separated values of hosts
12 - This plugin only applies to inventory strings that are not paths and contain a comma.
13 """
14
15 EXAMPLES = r"""
16 # define 2 hosts in command line
17 # ansible -i '10.10.2.6, 10.10.2.4' -m ping all
18
19 # DNS resolvable names
20 # ansible -i 'host1.example.com, host2' -m user -a 'name=me state=absent' all
21
22 # just use localhost
23 # ansible-playbook -i 'localhost,' play.yml -c local
24 """
25
26 import os
27
28 from ansible.errors import AnsibleError, AnsibleParserError
29 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
30 from ansible.parsing.utils.addresses import parse_address
31 from ansible.plugins.inventory import BaseInventoryPlugin
32
33
34 class InventoryModule(BaseInventoryPlugin):
35
36 NAME = 'host_list'
37
38 # host_list does not set vars, so needs no special trust assistance from the inventory API
39
40 def verify_file(self, host_list):
41
42 valid = False
43 b_path = to_bytes(host_list, errors='surrogate_or_strict')
44 if not os.path.exists(b_path) and ',' in host_list:
45 valid = True
46 return valid
47
48 def parse(self, inventory, loader, host_list, cache=True):
49 """ parses the inventory file """
50
51 super(InventoryModule, self).parse(inventory, loader, host_list)
52
53 try:
54 for h in host_list.split(','):
55 h = h.strip()
56 if h:
57 try:
58 (host, port) = parse_address(h, allow_ranges=False)
59 except AnsibleError as e:
60 self.display.vvv("Unable to parse address from hostname, leaving unchanged: %s" % to_text(e))
61 host = h
62 port = None
63
64 if host not in self.inventory.hosts:
65 self.inventory.add_host(host, group='ungrouped', port=port)
66 except Exception as e:
67 raise AnsibleParserError("Invalid data from string, could not parse: %s" % to_native(e))