| 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 |
from __future__ import annotations |
| 4 |
|
| 5 |
DOCUMENTATION = """ |
| 6 |
name: ini |
| 7 |
version_added: "2.4" |
| 8 |
short_description: Uses an Ansible INI file as inventory source. |
| 9 |
description: |
| 10 |
- INI file based inventory, sections are groups or group related with special C(:modifiers). |
| 11 |
- Entries in sections C([group_1]) are hosts, members of the group. |
| 12 |
- Hosts can have variables defined inline as key/value pairs separated by C(=). |
| 13 |
- The C(children) modifier indicates that the section contains groups. |
| 14 |
- The C(vars) modifier indicates that the section contains variables assigned to members of the group. |
| 15 |
- Anything found outside a section is considered an 'ungrouped' host. |
| 16 |
- Values passed in the INI format using the C(key=value) syntax are interpreted differently depending on where they are declared within your inventory. |
| 17 |
- When declared inline with the host, INI values are processed by Python's ast.literal_eval function |
| 18 |
(U(https://docs.python.org/3/library/ast.html#ast.literal_eval)) and interpreted as Python literal structures |
| 19 |
(strings, numbers, tuples, lists, dicts, booleans, None). If you want a number to be treated as a string, you must quote it. |
| 20 |
Host lines accept multiple C(key=value) parameters per line. |
| 21 |
Therefore they need a way to indicate that a space is part of a value rather than a separator. |
| 22 |
- When declared in a C(:vars) section, INI values are interpreted as strings. For example C(var=FALSE) would create a string equal to C(FALSE). |
| 23 |
Unlike host lines, C(:vars) sections accept only a single entry per line, so everything after the C(=) must be the value for the entry. |
| 24 |
- Do not rely on types set during definition, always make sure you specify type with a filter when needed when consuming the variable. |
| 25 |
- See the Examples for proper quoting to prevent changes to variable type. |
| 26 |
notes: |
| 27 |
- Enabled in configuration by default. |
| 28 |
- Consider switching to YAML format for inventory sources to avoid confusion on the actual type of a variable. |
| 29 |
The YAML inventory plugin processes variable values consistently and correctly. |
| 30 |
""" |
| 31 |
|
| 32 |
EXAMPLES = """# fmt: ini |
| 33 |
# Example 1 |
| 34 |
[web] |
| 35 |
host1 |
| 36 |
host2 ansible_port=222 # defined inline, interpreted as an integer |
| 37 |
|
| 38 |
[web:vars] |
| 39 |
http_port=8080 # all members of 'web' will inherit these |
| 40 |
myvar=23 # defined in a :vars section, interpreted as a string |
| 41 |
|
| 42 |
[web:children] # child groups will automatically add their hosts to parent group |
| 43 |
apache |
| 44 |
nginx |
| 45 |
|
| 46 |
[apache] |
| 47 |
tomcat1 |
| 48 |
tomcat2 myvar=34 # host specific vars override group vars |
| 49 |
tomcat3 mysecret="'03#pa33w0rd'" # proper quoting to prevent value changes |
| 50 |
|
| 51 |
[nginx] |
| 52 |
jenkins1 |
| 53 |
|
| 54 |
[nginx:vars] |
| 55 |
has_java = True # vars in child groups override same in parent |
| 56 |
|
| 57 |
[all:vars] |
| 58 |
has_java = False # 'all' is 'top' parent |
| 59 |
|
| 60 |
# Example 2 |
| 61 |
host1 # this is 'ungrouped' |
| 62 |
|
| 63 |
# both hosts have same IP but diff ports, also 'ungrouped' |
| 64 |
host2 ansible_host=127.0.0.1 ansible_port=44 |
| 65 |
host3 ansible_host=127.0.0.1 ansible_port=45 |
| 66 |
|
| 67 |
[g1] |
| 68 |
host4 |
| 69 |
|
| 70 |
[g2] |
| 71 |
host4 # same host as above, but member of 2 groups, will inherit vars from both |
| 72 |
# inventory hostnames are unique |
| 73 |
""" |
| 74 |
|
| 75 |
import ast |
| 76 |
import os |
| 77 |
import re |
| 78 |
import typing as t |
| 79 |
import warnings |
| 80 |
|
| 81 |
from ansible.inventory.group import to_safe_group_name |
| 82 |
from ansible.plugins.inventory import BaseFileInventoryPlugin |
| 83 |
|
| 84 |
from ansible.errors import AnsibleError, AnsibleParserError |
| 85 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 86 |
from ansible._internal._datatag._tags import Origin, TrustedAsTemplate |
| 87 |
from ansible.utils.shlex import shlex_split |
| 88 |
|
| 89 |
|
| 90 |
class InventoryModule(BaseFileInventoryPlugin): |
| 91 |
""" |
| 92 |
Takes an INI-format inventory file and builds a list of groups and subgroups |
| 93 |
with their associated hosts and variable settings. |
| 94 |
""" |
| 95 |
NAME = 'ini' |
| 96 |
_COMMENT_MARKERS = frozenset((u';', u'#')) |
| 97 |
b_COMMENT_MARKERS = frozenset((b';', b'#')) |
| 98 |
|
| 99 |
# template trust is applied internally to strings |
| 100 |
|
| 101 |
def __init__(self) -> None: |
| 102 |
|
| 103 |
super(InventoryModule, self).__init__() |
| 104 |
|
| 105 |
self.patterns: dict[str, re.Pattern] = {} |
| 106 |
self._origin: Origin | None = None |
| 107 |
|
| 108 |
def verify_file(self, path): |
| 109 |
# hardcode exclusion for TOML to prevent partial parsing of things we know we don't want |
| 110 |
return super().verify_file(path) and os.path.splitext(path)[1] != '.toml' |
| 111 |
|
| 112 |
def parse(self, inventory, loader, path: str, cache=True): |
| 113 |
|
| 114 |
super(InventoryModule, self).parse(inventory, loader, path) |
| 115 |
|
| 116 |
try: |
| 117 |
# Read in the hosts, groups, and variables defined in the inventory file. |
| 118 |
if self.loader: |
| 119 |
(b_data, private) = self.loader._get_file_contents(path) |
| 120 |
else: |
| 121 |
b_path = to_bytes(path, errors='surrogate_or_strict') |
| 122 |
with open(b_path, 'rb') as fh: |
| 123 |
b_data = fh.read() |
| 124 |
|
| 125 |
try: |
| 126 |
# Faster to do to_text once on a long string than many |
| 127 |
# times on smaller strings |
| 128 |
data = to_text(b_data, errors='surrogate_or_strict').splitlines() |
| 129 |
except UnicodeError: |
| 130 |
# Handle non-utf8 in comment lines: https://github.com/ansible/ansible/issues/17593 |
| 131 |
data = [] |
| 132 |
for line in b_data.splitlines(): |
| 133 |
if line and line[0] in self.b_COMMENT_MARKERS: |
| 134 |
# Replace is okay for comment lines |
| 135 |
# data.append(to_text(line, errors='surrogate_then_replace')) |
| 136 |
# Currently we only need these lines for accurate lineno in errors |
| 137 |
data.append(u'') |
| 138 |
else: |
| 139 |
# Non-comment lines still have to be valid uf-8 |
| 140 |
data.append(to_text(line, errors='surrogate_or_strict')) |
| 141 |
|
| 142 |
self._origin = Origin(path=path, line_num=0) |
| 143 |
|
| 144 |
try: |
| 145 |
self._parse(data) |
| 146 |
finally: |
| 147 |
self._origin = self._origin.replace(line_num=None) |
| 148 |
|
| 149 |
except Exception as ex: |
| 150 |
raise AnsibleParserError('Failed to parse inventory.', obj=self._origin) from ex |
| 151 |
|
| 152 |
def _raise_error(self, message): |
| 153 |
raise AnsibleError(message) |
| 154 |
|
| 155 |
def _parse(self, lines): |
| 156 |
""" |
| 157 |
Populates self.groups from the given array of lines. Raises an error on |
| 158 |
any parse failure. |
| 159 |
""" |
| 160 |
|
| 161 |
self._compile_patterns() |
| 162 |
|
| 163 |
# We behave as though the first line of the inventory is '[ungrouped]', |
| 164 |
# and begin to look for host definitions. We make a single pass through |
| 165 |
# each line of the inventory, building up self.groups and adding hosts, |
| 166 |
# subgroups, and setting variables as we go. |
| 167 |
|
| 168 |
pending_declarations = {} |
| 169 |
groupname = 'ungrouped' |
| 170 |
state = 'hosts' |
| 171 |
for line in lines: |
| 172 |
self._origin = self._origin.replace(line_num=self._origin.line_num + 1) |
| 173 |
|
| 174 |
line = line.strip() |
| 175 |
# Skip empty lines and comments |
| 176 |
if not line or line[0] in self._COMMENT_MARKERS: |
| 177 |
continue |
| 178 |
|
| 179 |
# Is this a [section] header? That tells us what group we're parsing |
| 180 |
# definitions for, and what kind of definitions to expect. |
| 181 |
|
| 182 |
m = self.patterns['section'].match(line) |
| 183 |
if m: |
| 184 |
(groupname, state) = m.groups() |
| 185 |
|
| 186 |
groupname = to_safe_group_name(groupname) |
| 187 |
|
| 188 |
state = state or 'hosts' |
| 189 |
if state not in ['hosts', 'children', 'vars']: |
| 190 |
title = ":".join(m.groups()) |
| 191 |
self._raise_error("Section [%s] has unknown type: %s" % (title, state)) |
| 192 |
|
| 193 |
# If we haven't seen this group before, we add a new Group. |
| 194 |
if groupname not in self.inventory.groups: |
| 195 |
# Either [groupname] or [groupname:children] is sufficient to declare a group, |
| 196 |
# but [groupname:vars] is allowed only if the # group is declared elsewhere. |
| 197 |
# We add the group anyway, but make a note in pending_declarations to check at the end. |
| 198 |
# |
| 199 |
# It's possible that a group is previously pending due to being defined as a child |
| 200 |
# group, in that case we simply pass so that the logic below to process pending |
| 201 |
# declarations will take the appropriate action for a pending child group instead of |
| 202 |
# incorrectly handling it as a var state pending declaration |
| 203 |
if state == 'vars' and groupname not in pending_declarations: |
| 204 |
pending_declarations[groupname] = dict(line=self._origin.line_num, state=state, name=groupname) |
| 205 |
|
| 206 |
self.inventory.add_group(groupname) |
| 207 |
|
| 208 |
# When we see a declaration that we've been waiting for, we process and delete. |
| 209 |
if groupname in pending_declarations and state != 'vars': |
| 210 |
if pending_declarations[groupname]['state'] == 'children': |
| 211 |
self._add_pending_children(groupname, pending_declarations) |
| 212 |
elif pending_declarations[groupname]['state'] == 'vars': |
| 213 |
del pending_declarations[groupname] |
| 214 |
|
| 215 |
continue |
| 216 |
elif line.startswith('[') and line.endswith(']'): |
| 217 |
self._raise_error("Invalid section entry: '%s'. Please make sure that there are no spaces" % line + " " + |
| 218 |
"in the section entry, and that there are no other invalid characters") |
| 219 |
|
| 220 |
# It's not a section, so the current state tells us what kind of |
| 221 |
# definition it must be. The individual parsers will raise an |
| 222 |
# error if we feed them something they can't digest. |
| 223 |
|
| 224 |
# [groupname] contains host definitions that must be added to |
| 225 |
# the current group. |
| 226 |
if state == 'hosts': |
| 227 |
hosts, port, variables = self._parse_host_definition(line) |
| 228 |
self._populate_host_vars(hosts, variables, groupname, port) |
| 229 |
|
| 230 |
# [groupname:vars] contains variable definitions that must be |
| 231 |
# applied to the current group. |
| 232 |
elif state == 'vars': |
| 233 |
(k, v) = self._parse_variable_definition(line) |
| 234 |
self.inventory.set_variable(groupname, k, v) |
| 235 |
|
| 236 |
# [groupname:children] contains subgroup names that must be |
| 237 |
# added as children of the current group. The subgroup names |
| 238 |
# must themselves be declared as groups, but as before, they |
| 239 |
# may only be declared later. |
| 240 |
elif state == 'children': |
| 241 |
child = self._parse_group_name(line) |
| 242 |
if child not in self.inventory.groups: |
| 243 |
if child not in pending_declarations: |
| 244 |
pending_declarations[child] = dict(line=self._origin.line_num, state=state, name=child, parents=[groupname]) |
| 245 |
else: |
| 246 |
pending_declarations[child]['parents'].append(groupname) |
| 247 |
else: |
| 248 |
self.inventory.add_child(groupname, child) |
| 249 |
else: |
| 250 |
# This can happen only if the state checker accepts a state that isn't handled above. |
| 251 |
self._raise_error("Entered unhandled state: %s" % (state)) |
| 252 |
|
| 253 |
# Any entries in pending_declarations not removed by a group declaration above mean that there was an unresolved reference. |
| 254 |
# We report only the first such error here. |
| 255 |
for g in pending_declarations: |
| 256 |
decl = pending_declarations[g] |
| 257 |
self._origin = self._origin.replace(line_num=decl['line']) |
| 258 |
if decl['state'] == 'vars': |
| 259 |
raise ValueError(f"Section [{decl['name']}:vars] not valid for undefined group {decl['name']!r}.") |
| 260 |
elif decl['state'] == 'children': |
| 261 |
raise ValueError(f"Section [{decl['parents'][-1]}:children] includes undefined group {decl['name']!r}.") |
| 262 |
|
| 263 |
def _add_pending_children(self, group, pending): |
| 264 |
for parent in pending[group]['parents']: |
| 265 |
self.inventory.add_child(parent, group) |
| 266 |
if parent in pending and pending[parent]['state'] == 'children': |
| 267 |
self._add_pending_children(parent, pending) |
| 268 |
del pending[group] |
| 269 |
|
| 270 |
def _parse_group_name(self, line): |
| 271 |
""" |
| 272 |
Takes a single line and tries to parse it as a group name. Returns the |
| 273 |
group name if successful, or raises an error. |
| 274 |
""" |
| 275 |
|
| 276 |
m = self.patterns['groupname'].match(line) |
| 277 |
if m: |
| 278 |
return m.group(1) |
| 279 |
|
| 280 |
self._raise_error("Expected group name, got: %s" % (line)) |
| 281 |
|
| 282 |
def _parse_variable_definition(self, line): |
| 283 |
""" |
| 284 |
Takes a string and tries to parse it as a variable definition. Returns |
| 285 |
the key and value if successful, or raises an error. |
| 286 |
""" |
| 287 |
|
| 288 |
# TODO: We parse variable assignments as a key (anything to the left of |
| 289 |
# an '='"), an '=', and a value (anything left) and leave the value to |
| 290 |
# _parse_value to sort out. We should be more systematic here about |
| 291 |
# defining what is acceptable, how quotes work, and so on. |
| 292 |
|
| 293 |
if '=' in line: |
| 294 |
(k, v) = [e.strip() for e in line.split("=", 1)] |
| 295 |
return (self._origin.tag(k), self._parse_value(v)) |
| 296 |
|
| 297 |
self._raise_error("Expected key=value, got: %s" % (line)) |
| 298 |
|
| 299 |
def _parse_host_definition(self, line): |
| 300 |
""" |
| 301 |
Takes a single line and tries to parse it as a host definition. Returns |
| 302 |
a list of Hosts if successful, or raises an error. |
| 303 |
""" |
| 304 |
|
| 305 |
# A host definition comprises (1) a non-whitespace hostname or range, |
| 306 |
# optionally followed by (2) a series of key="some value" assignments. |
| 307 |
# We ignore any trailing whitespace and/or comments. For example, here |
| 308 |
# are a series of host definitions in a group: |
| 309 |
# |
| 310 |
# [groupname] |
| 311 |
# alpha |
| 312 |
# beta:2345 user=admin # we'll tell shlex |
| 313 |
# gamma sudo=True user=root # to ignore comments |
| 314 |
|
| 315 |
try: |
| 316 |
tokens = shlex_split(line, comments=True) |
| 317 |
except ValueError as e: |
| 318 |
self._raise_error("Error parsing host definition '%s': %s" % (line, e)) |
| 319 |
|
| 320 |
(hostnames, port) = self._expand_hostpattern(tokens[0]) |
| 321 |
|
| 322 |
# Try to process anything remaining as a series of key=value pairs. |
| 323 |
variables = {} |
| 324 |
for t in tokens[1:]: |
| 325 |
if '=' not in t: |
| 326 |
self._raise_error("Expected key=value host variable assignment, got: %s" % (t)) |
| 327 |
(k, v) = t.split('=', 1) |
| 328 |
variables[self._origin.tag(k)] = self._parse_value(v) |
| 329 |
|
| 330 |
return hostnames, port, variables |
| 331 |
|
| 332 |
def _expand_hostpattern(self, hostpattern): |
| 333 |
""" |
| 334 |
do some extra checks over normal processing |
| 335 |
""" |
| 336 |
# specification? |
| 337 |
|
| 338 |
hostnames, port = super(InventoryModule, self)._expand_hostpattern(hostpattern) |
| 339 |
|
| 340 |
if hostpattern.strip().endswith(':') and port is None: |
| 341 |
raise AnsibleParserError("Invalid host pattern '%s' supplied, ending in ':' is not allowed, this character is reserved to provide a port." % |
| 342 |
hostpattern) |
| 343 |
for pattern in hostnames: |
| 344 |
# some YAML parsing prevention checks |
| 345 |
if pattern.strip() == '---': |
| 346 |
raise AnsibleParserError("Invalid host pattern '%s' supplied, '---' is normally a sign this is a YAML file." % hostpattern) |
| 347 |
|
| 348 |
return (hostnames, port) |
| 349 |
|
| 350 |
def _parse_recursive_coerce_types_and_tag(self, value: t.Any) -> t.Any: |
| 351 |
if isinstance(value, str): |
| 352 |
return TrustedAsTemplate().tag(self._origin.tag(value)) |
| 353 |
if isinstance(value, (list, tuple, set)): |
| 354 |
# NB: intentional coercion of tuple/set to list, deal with it |
| 355 |
return self._origin.tag([self._parse_recursive_coerce_types_and_tag(v) for v in value]) |
| 356 |
if isinstance(value, dict): |
| 357 |
# FIXME: enforce keys are strings |
| 358 |
return self._origin.tag({self._origin.tag(k): self._parse_recursive_coerce_types_and_tag(v) for k, v in value.items()}) |
| 359 |
|
| 360 |
if value is ...: # literal_eval parses ellipsis, but it's not a supported variable type |
| 361 |
value = TrustedAsTemplate().tag("...") |
| 362 |
|
| 363 |
if isinstance(value, complex): # convert unsupported variable types recognized by literal_eval back to str |
| 364 |
value = TrustedAsTemplate().tag(str(value)) |
| 365 |
|
| 366 |
value = to_text(value, nonstring='passthru', errors='surrogate_or_strict') |
| 367 |
|
| 368 |
return self._origin.tag(value) |
| 369 |
|
| 370 |
def _parse_value(self, v: str) -> t.Any: |
| 371 |
""" |
| 372 |
Attempt to transform the string value from an ini file into a basic python object |
| 373 |
(int, dict, list, unicode string, etc). |
| 374 |
""" |
| 375 |
try: |
| 376 |
with warnings.catch_warnings(): |
| 377 |
warnings.simplefilter("ignore", SyntaxWarning) |
| 378 |
v = ast.literal_eval(v) |
| 379 |
# Using explicit exceptions. |
| 380 |
# Likely a string that literal_eval does not like. We will then just set it. |
| 381 |
except ValueError: |
| 382 |
# For some reason this was thought to be malformed. |
| 383 |
pass |
| 384 |
except SyntaxError: |
| 385 |
# Is this a hash with an equals at the end? |
| 386 |
pass |
| 387 |
|
| 388 |
# this is mostly unnecessary, but prevents the (possible) case of bytes literals showing up in inventory |
| 389 |
return self._parse_recursive_coerce_types_and_tag(v) |
| 390 |
|
| 391 |
def _compile_patterns(self): |
| 392 |
""" |
| 393 |
Compiles the regular expressions required to parse the inventory and |
| 394 |
stores them in self.patterns. |
| 395 |
""" |
| 396 |
|
| 397 |
# Section names are square-bracketed expressions at the beginning of a |
| 398 |
# line, comprising (1) a group name optionally followed by (2) a tag |
| 399 |
# that specifies the contents of the section. We ignore any trailing |
| 400 |
# whitespace and/or comments. For example: |
| 401 |
# |
| 402 |
# [groupname] |
| 403 |
# [somegroup:vars] |
| 404 |
# [naughty:children] # only get coal in their stockings |
| 405 |
|
| 406 |
self.patterns['section'] = re.compile( |
| 407 |
to_text(r"""^\[ |
| 408 |
([^:\]\s]+) # group name (see groupname below) |
| 409 |
(?::(\w+))? # optional : and tag name |
| 410 |
\] |
| 411 |
\s* # ignore trailing whitespace |
| 412 |
(?:\#.*)? # and/or a comment till the |
| 413 |
$ # end of the line |
| 414 |
""", errors='surrogate_or_strict'), re.X |
| 415 |
) |
| 416 |
|
| 417 |
# FIXME: What are the real restrictions on group names, or rather, what |
| 418 |
# should they be? At the moment, they must be non-empty sequences of non |
| 419 |
# whitespace characters excluding ':' and ']', but we should define more |
| 420 |
# precise rules in order to support better diagnostics. |
| 421 |
|
| 422 |
self.patterns['groupname'] = re.compile( |
| 423 |
to_text(r"""^ |
| 424 |
([^:\]\s]+) |
| 425 |
\s* # ignore trailing whitespace |
| 426 |
(?:\#.*)? # and/or a comment till the |
| 427 |
$ # end of the line |
| 428 |
""", errors='surrogate_or_strict'), re.X |
| 429 |
) |