Debian Codegraph @

lib/ansible/plugins/inventory/auto.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 = """
7 name: auto
8 author:
9 - Matt Davis (@nitzmahone)
10 version_added: "2.5"
11 short_description: Loads and executes an inventory plugin specified in a YAML config
12 description:
13 - By enabling the C(auto) inventory plugin, any YAML inventory config file with a
14 C(plugin) key at its root will automatically cause the named plugin to be loaded and executed with that
15 config. This effectively provides automatic enabling of all installed/accessible inventory plugins.
16 - To disable this behavior, remove C(auto) from the C(INVENTORY_ENABLED) config element.
17 """
18
19 EXAMPLES = """
20 # This plugin is not intended for direct use; it is a fallback mechanism for automatic enabling of
21 # all installed inventory plugins.
22 """
23
24 from ansible.errors import AnsibleParserError
25 from ansible.plugins.inventory import BaseInventoryPlugin
26 from ansible.plugins.loader import inventory_loader
27
28
29 class InventoryModule(BaseInventoryPlugin):
30
31 NAME = 'auto'
32
33 # no need to set trusted_by_default, since the consumers of this value will always consult the real plugin substituted during our parse()
34
35 def verify_file(self, path):
36 if not path.endswith('.yml') and not path.endswith('.yaml'):
37 return False
38 return super(InventoryModule, self).verify_file(path)
39
40 def parse(self, inventory, loader, path, cache=True):
41 config_data = loader.load_from_file(path, cache='none')
42
43 try:
44 plugin_name = config_data.get('plugin', None)
45 except AttributeError:
46 plugin_name = None
47
48 if not plugin_name:
49 raise AnsibleParserError("no root 'plugin' key found, '{0}' is not a valid YAML inventory plugin config file".format(path))
50
51 plugin = inventory_loader.get(plugin_name)
52
53 if not plugin:
54 raise AnsibleParserError("inventory config '{0}' specifies unknown plugin '{1}'".format(path, plugin_name))
55
56 if not plugin.verify_file(path):
57 raise AnsibleParserError("inventory source '{0}' could not be verified by inventory plugin '{1}'".format(path, plugin_name))
58
59 self.display.v("Using inventory plugin '{0}' to process inventory source '{1}'".format(plugin._load_name, path))
60
61 # unfortunate magic to swap the real plugin type we're proxying here into the inventory data API wrapper, so the wrapper can make the right compat
62 # decisions based on the metadata the real plugin provides instead of our metadata
63 inventory._target_plugin = plugin
64
65 plugin.parse(inventory, loader, path, cache=cache)
66 try:
67 plugin.update_cache_if_changed()
68 except AttributeError:
69 pass