Debian Codegraph @

ansible_collections/cisco/aci/plugins/inventory/aci_inventory_system.py

raw
1 # Copyright (c) 2025 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 absolute_import, division, print_function
5
6 __metaclass__ = type
7
8 DOCUMENTATION = r"""
9 name: aci_inventory_system
10 short_description: Cisco ACI inventory plugin
11 extends_documentation_fragment:
12 - cisco.aci.aci
13 - constructed
14 description:
15 - Query details from APIC
16 - Gets details on all spines and leafs behind the controller.
17 - Requires a YAML configuration file whose name ends with 'cisco_aci.(yml|yaml)'
18 """
19
20 EXAMPLES = """
21 ---
22 # Generate dynamic inventory of every device
23 plugin: cisco.aci.aci_inventory_system
24 host: 192.168.1.90
25 username: admin
26 password: PASSWORD
27 validate_certs: false
28
29 # (Optional) Generate inventory and put devices into groups based on role: spine, leaf, controller
30 keyed_groups:
31 - prefix: role
32 key: role
33
34 # (Optional) Generate inventory and use the compose variables to define how we want to connect
35 compose:
36 ansible_connection: "'ansible.netcommon.httpapi'"
37 ansible_network_os: "'cisco.aci.aci'"
38 ansible_host: "'192.168.1.90'"
39 """
40
41 import atexit
42 import time
43 import tempfile
44 import shutil
45 import typing as t
46 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
47 from ansible_collections.cisco.aci.plugins.module_utils.aci import (
48 ACIModule,
49 aci_argument_spec,
50 )
51 from ansible_collections.cisco.aci.plugins.module_utils.constants import (
52 RESERVED_ANSIBLE_INVENTORY_KEYS,
53 MOCKED_CONSTRUCTED_INVENTORY_ARGUMENT_SPEC,
54 )
55 from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
56 from ansible.module_utils.common.text.converters import to_native
57 from ansible.errors import AnsibleError
58 from ansible.utils.display import Display
59
60
61 display = Display()
62
63
64 class MockAnsibleModule(object):
65 def __init__(self, argument_spec, parameters):
66 """Mock AnsibleModule
67
68 This is needed in order to use the aci methods which assume to be working
69 with a module only.
70 """
71
72 self._socket_path = None
73 self._debug = False
74 self._diff = False
75 self._tmpdir = None
76 self.check_mode = False
77 self.params = dict()
78
79 validator = ArgumentSpecValidator(argument_spec)
80 result = validator.validate(parameters)
81
82 if result.error_messages:
83 self.warn("Validation failed: {0}".format(", ".join(result.error_messages)))
84
85 self.params = result.validated_parameters
86
87 @property
88 def tmpdir(self):
89 if self._tmpdir is None:
90 basefile = "ansible-moduletmp-%s-" % time.time()
91 try:
92 tmpdir = tempfile.mkdtemp(prefix=basefile)
93 except (OSError, IOError) as e:
94 self.fail_json(msg="Failed to create remote module tmp path with prefix %s: %s" % (basefile, to_native(e)))
95 atexit.register(shutil.rmtree, tmpdir)
96 self._tmpdir = tmpdir
97
98 return self._tmpdir
99
100 def warn(self, warning):
101 display.vvv(warning)
102
103 def fail_json(self, msg, **kwargs) -> t.NoReturn:
104 raise AnsibleError(msg)
105
106
107 class InventoryModule(BaseInventoryPlugin, Constructable):
108
109 NAME = "cisco.aci.aci_inventory_system"
110
111 def verify_file(self, path):
112 """return true/false if this is possibly a valid file for this plugin to consume"""
113 valid = False
114 if super(InventoryModule, self).verify_file(path):
115 # base class verifies that file exists and is readable by current user
116 if path.endswith(("cisco_aci.yaml", "cisco_aci.yml")):
117 valid = True
118 return valid
119
120 def parse(self, inventory, loader, path, cache=True):
121
122 # call base method to ensure properties are available for use with other helper methods
123 super(InventoryModule, self).parse(inventory, loader, path, cache)
124
125 # this method will parse 'common format' inventory sources and
126 # update any options declared in DOCUMENTATION as needed
127 config = self._read_config_data(path)
128
129 argument_spec = aci_argument_spec()
130
131 # Avoid argument spec validation warnings for plugin options
132 # Options are retrieved from the constructed plugin docs, see below links for more information:
133 # - https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/inventory/constructed.py
134 # - https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/doc_fragments/constructed.py
135 argument_spec.update(MOCKED_CONSTRUCTED_INVENTORY_ARGUMENT_SPEC)
136
137 module = MockAnsibleModule(
138 argument_spec=argument_spec,
139 parameters=config,
140 )
141
142 aci = ACIModule(module)
143 aci.construct_url(root_class=dict(aci_class="topSystem"))
144
145 aci.get_existing()
146
147 # parse data and create inventory objects:
148 for device in aci.existing:
149 attributes = device.get("topSystem", {}).get("attributes", {})
150 if attributes.get("name"):
151 self.add_host(
152 attributes.get("name"),
153 # replace the reserved Ansible inventory keys from host topSystem attributes
154 {RESERVED_ANSIBLE_INVENTORY_KEYS.get(key, key): value for key, value in attributes.items()},
155 )
156
157 def add_host(self, hostname, host_vars):
158 self.inventory.add_host(hostname, group="all")
159
160 if host_vars.get("oobMgmtAddr", "0.0.0.0") != "0.0.0.0":
161 self.inventory.set_variable(hostname, "ansible_host", host_vars.get("oobMgmtAddr"))
162 elif host_vars.get("inbMgmtAddr", "0.0.0.0") != "0.0.0.0":
163 self.inventory.set_variable(hostname, "ansible_host", host_vars.get("inbMgmtAddr"))
164 else:
165 self.inventory.set_variable(hostname, "ansible_host", host_vars.get("address"))
166
167 for var_name, var_value in host_vars.items():
168 self.inventory.set_variable(hostname, var_name, var_value)
169
170 strict = self.get_option("strict")
171
172 # Add variables created by the user's Jinja2 expressions to the host
173 self._set_composite_vars(self.get_option("compose"), host_vars, hostname, strict=True)
174
175 # Create user-defined groups using variables and Jinja2 conditionals
176 self._add_host_to_composed_groups(self.get_option("groups"), host_vars, hostname, strict=strict)
177 self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host_vars, hostname, strict=strict)