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