| 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 = """ |
| 7 |
name: yaml |
| 8 |
version_added: "2.4" |
| 9 |
short_description: Uses a specific YAML file as an inventory source. |
| 10 |
description: |
| 11 |
- "YAML-based inventory, should start with the C(all) group and contain hosts/vars/children entries." |
| 12 |
- Host entries can have sub-entries defined, which will be treated as variables. |
| 13 |
- Vars entries are normal group vars. |
| 14 |
- "Children are 'child groups', which can also have their own vars/hosts/children and so on." |
| 15 |
- File MUST have a valid extension, defined in configuration. |
| 16 |
notes: |
| 17 |
- If you want to set vars for the C(all) group inside the inventory file, the C(all) group must be the first entry in the file. |
| 18 |
- Enabled in configuration by default. |
| 19 |
options: |
| 20 |
yaml_extensions: |
| 21 |
description: list of 'valid' extensions for files containing YAML |
| 22 |
type: list |
| 23 |
elements: string |
| 24 |
default: ['.yaml', '.yml', '.json'] |
| 25 |
env: |
| 26 |
- name: ANSIBLE_YAML_FILENAME_EXT |
| 27 |
- name: ANSIBLE_INVENTORY_PLUGIN_EXTS |
| 28 |
ini: |
| 29 |
- key: yaml_valid_extensions |
| 30 |
section: defaults |
| 31 |
- section: inventory_plugin_yaml |
| 32 |
key: yaml_valid_extensions |
| 33 |
|
| 34 |
""" |
| 35 |
EXAMPLES = """ |
| 36 |
all: # keys must be unique, i.e. only one 'hosts' per group |
| 37 |
hosts: |
| 38 |
test1: |
| 39 |
test2: |
| 40 |
host_var: value |
| 41 |
vars: |
| 42 |
group_all_var: value |
| 43 |
children: # key order does not matter, indentation does |
| 44 |
other_group: |
| 45 |
children: |
| 46 |
group_x: |
| 47 |
hosts: |
| 48 |
test5 # Note that one machine will work without a colon |
| 49 |
#group_x: |
| 50 |
# hosts: |
| 51 |
# test5 # But this won't |
| 52 |
# test7 # |
| 53 |
group_y: |
| 54 |
hosts: |
| 55 |
test6: # So always use a colon |
| 56 |
vars: |
| 57 |
g2_var2: value3 |
| 58 |
hosts: |
| 59 |
test4: |
| 60 |
ansible_host: 127.0.0.1 |
| 61 |
last_group: |
| 62 |
hosts: |
| 63 |
test1 # same host as above, additional group membership |
| 64 |
vars: |
| 65 |
group_last_var: value |
| 66 |
""" |
| 67 |
|
| 68 |
import os |
| 69 |
|
| 70 |
from collections.abc import MutableMapping |
| 71 |
|
| 72 |
from ansible.errors import AnsibleError, AnsibleParserError |
| 73 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 74 |
from ansible.plugins.inventory import BaseFileInventoryPlugin |
| 75 |
|
| 76 |
NoneType = type(None) |
| 77 |
|
| 78 |
|
| 79 |
class InventoryModule(BaseFileInventoryPlugin): |
| 80 |
|
| 81 |
NAME = 'yaml' |
| 82 |
|
| 83 |
# implicit trust behavior is already added by the YAML parser invoked by the loader |
| 84 |
|
| 85 |
def __init__(self): |
| 86 |
|
| 87 |
super(InventoryModule, self).__init__() |
| 88 |
|
| 89 |
def verify_file(self, path): |
| 90 |
|
| 91 |
valid = False |
| 92 |
if super(InventoryModule, self).verify_file(path): |
| 93 |
file_name, ext = os.path.splitext(path) |
| 94 |
if not ext or ext in self.get_option('yaml_extensions'): |
| 95 |
valid = True |
| 96 |
return valid |
| 97 |
|
| 98 |
def parse(self, inventory, loader, path, cache=True): |
| 99 |
""" parses the inventory file """ |
| 100 |
|
| 101 |
super(InventoryModule, self).parse(inventory, loader, path) |
| 102 |
self.set_options() |
| 103 |
|
| 104 |
try: |
| 105 |
data = self.loader.load_from_file(path, cache='none', trusted_as_template=True) |
| 106 |
except Exception as e: |
| 107 |
raise AnsibleParserError(e) |
| 108 |
|
| 109 |
if not data: |
| 110 |
raise AnsibleParserError('Parsed empty YAML file') |
| 111 |
elif not isinstance(data, MutableMapping): |
| 112 |
raise AnsibleParserError('YAML inventory has invalid structure, it should be a dictionary, got: %s' % type(data)) |
| 113 |
elif data.get('plugin'): |
| 114 |
raise AnsibleParserError('Plugin configuration YAML file, not YAML inventory') |
| 115 |
|
| 116 |
# We expect top level keys to correspond to groups, iterate over them |
| 117 |
# to get host, vars and subgroups (which we iterate over recursively) |
| 118 |
if isinstance(data, MutableMapping): |
| 119 |
for group_name in data: |
| 120 |
self._parse_group(group_name, data[group_name]) |
| 121 |
else: |
| 122 |
raise AnsibleParserError("Invalid data from file, expected dictionary and got:\n\n%s" % to_native(data)) |
| 123 |
|
| 124 |
def _parse_group(self, group, group_data): |
| 125 |
|
| 126 |
if isinstance(group_data, (MutableMapping, NoneType)): # type: ignore[misc] |
| 127 |
|
| 128 |
try: |
| 129 |
group = self.inventory.add_group(group) |
| 130 |
except AnsibleError as e: |
| 131 |
raise AnsibleParserError("Unable to add group %s: %s" % (group, to_text(e))) |
| 132 |
|
| 133 |
if group_data is not None: |
| 134 |
# make sure they are dicts |
| 135 |
for section in ['vars', 'children', 'hosts']: |
| 136 |
if section in group_data: |
| 137 |
# convert strings to dicts as these are allowed |
| 138 |
if isinstance(group_data[section], str): |
| 139 |
group_data[section] = {group_data[section]: None} |
| 140 |
|
| 141 |
if not isinstance(group_data[section], (MutableMapping, NoneType)): # type: ignore[misc] |
| 142 |
raise AnsibleParserError('Invalid "%s" entry for "%s" group, requires a dictionary, found "%s" instead.' % |
| 143 |
(section, group, type(group_data[section]))) |
| 144 |
|
| 145 |
for key in group_data: |
| 146 |
|
| 147 |
if not isinstance(group_data[key], (MutableMapping, NoneType)): # type: ignore[misc] |
| 148 |
self.display.warning('Skipping key (%s) in group (%s) as it is not a mapping, it is a %s' % (key, group, type(group_data[key]))) |
| 149 |
continue |
| 150 |
|
| 151 |
if isinstance(group_data[key], NoneType): # type: ignore[misc] |
| 152 |
self.display.vvv('Skipping empty key (%s) in group (%s)' % (key, group)) |
| 153 |
elif key == 'vars': |
| 154 |
for var in group_data[key]: |
| 155 |
self.inventory.set_variable(group, var, group_data[key][var]) |
| 156 |
elif key == 'children': |
| 157 |
for subgroup in group_data[key]: |
| 158 |
subgroup = self._parse_group(subgroup, group_data[key][subgroup]) |
| 159 |
self.inventory.add_child(group, subgroup) |
| 160 |
|
| 161 |
elif key == 'hosts': |
| 162 |
for host_pattern in group_data[key]: |
| 163 |
hosts, port = self._parse_host(host_pattern) |
| 164 |
self._populate_host_vars(hosts, group_data[key][host_pattern] or {}, group, port) |
| 165 |
else: |
| 166 |
self.display.warning('Skipping unexpected key (%s) in group (%s), only "vars", "children" and "hosts" are valid' % (key, group)) |
| 167 |
|
| 168 |
else: |
| 169 |
self.display.warning("Skipping '%s' as this is not a valid group definition" % group) |
| 170 |
|
| 171 |
return group |
| 172 |
|
| 173 |
def _parse_host(self, host_pattern): |
| 174 |
""" |
| 175 |
Each host key can be a pattern, try to process it and add variables as needed |
| 176 |
""" |
| 177 |
try: |
| 178 |
(hostnames, port) = self._expand_hostpattern(host_pattern) |
| 179 |
except TypeError: |
| 180 |
raise AnsibleParserError( |
| 181 |
f"Host pattern {host_pattern} must be a string. Enclose integers/floats in quotation marks." |
| 182 |
) |
| 183 |
return hostnames, port |