Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/inventory/ome_inventory.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #
4 # Dell OpenManage Ansible Modules
5 # Version 7.4.0
6 # Copyright (C) 2022-2023 Dell Inc. or its subsidiaries. All Rights Reserved.
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 #
10
11 from __future__ import (absolute_import, division, print_function)
12 __metaclass__ = type
13
14
15 DOCUMENTATION = """
16 ---
17 name: ome_inventory
18 short_description: Group inventory plugin on OpenManage Enterprise.
19 description: This plugin allows to retrieve inventory hosts from groups on OpenManage Enterprise.
20 version_added: "7.1.0"
21 options:
22 hostname:
23 description:
24 - OpenManage Enterprise or OpenManage Enterprise Modular IP address or hostname.
25 - If the value is not specified in the task, the value of environment variable C(OME_HOSTNAME) will be used instead.
26 env:
27 - name: OME_HOSTNAME
28 type: str
29 required: true
30 username:
31 description:
32 - OpenManage Enterprise or OpenManage Enterprise Modular username.
33 - If the value is not specified in the task, the value of environment variable C(OME_USERNAME) will be used instead.
34 env:
35 - name: OME_USERNAME
36 type: str
37 required: true
38 password:
39 description:
40 - OpenManage Enterprise or OpenManage Enterprise Modular password.
41 - If the value is not specified in the task, the value of environment variable C(OME_PASSWORD) will be used instead.
42 env:
43 - name: OME_PASSWORD
44 type: str
45 required: true
46 port:
47 description:
48 - OpenManage Enterprise or OpenManage Enterprise Modular HTTPS port.
49 - If the value is not specified in the task, the value of environment variable C(OME_PORT) will be used instead.
50 type: int
51 default: 443
52 validate_certs:
53 description:
54 - If C(false), the SSL certificates will not be validated.
55 - Configure C(false) only on personally controlled sites where self-signed certificates are used.
56 - Prior to collection version C(5.0.0), the I(validate_certs) is C(false) by default.
57 type: bool
58 default: true
59 ca_path:
60 description:
61 - The Privacy Enhanced Mail (PEM) file that contains a CA certificate to be used for the validation.
62 type: path
63 timeout:
64 description: The socket level timeout in seconds.
65 type: int
66 default: 30
67 ome_group_name:
68 description: Group name.
69 type: str
70 required: false
71 host_vars:
72 description: To include host related variables in the inventory source.
73 type: dict
74 required: false
75 group_vars:
76 description: To include group variables in the inventory source.
77 type: dict
78 required: false
79 requirements:
80 - "python >= 3.9.6"
81 author:
82 - "Felix Stephen (@felixs88)"
83 notes:
84 - Run this plugin on a system that has direct access to Dell OpenManage Enterprise.
85 """
86
87 import re
88
89 from ansible.plugins.inventory import BaseInventoryPlugin
90 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME
91 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import get_all_data_with_pagination
92
93 GROUP_API = "GroupService/Groups"
94
95
96 class InventoryModule(BaseInventoryPlugin):
97
98 NAME = "dellemc.openmanage.ome_inventory"
99
100 def __init__(self):
101 super(InventoryModule, self).__init__()
102 self.config = None
103
104 def _get_connection_resp(self):
105 port = self.get_option("port") if "port" in self.config else 443
106 validate_certs = self.get_option("validate_certs") if "validate_certs" in self.config else False
107 module_params = {"hostname": self.get_option("hostname"), "username": self.get_option("username"),
108 "password": self.get_option("password"), "port": port, "validate_certs": validate_certs}
109 if "ca_path" in self.config:
110 module_params.update({"ca_path": self.get_option("ca_path")})
111 with RestOME(module_params, req_session=True) as ome:
112 all_group_data = get_all_data_with_pagination(ome, GROUP_API)
113 return all_group_data
114
115 @staticmethod
116 def _to_safe_group_name(name):
117 safe = re.sub(r'\W', '_', name)
118 safe = re.sub(r'^[^A-Za-z_]+', '', safe)
119 return safe or '_'
120
121 def _set_host_vars(self, host_ip, device_info):
122 self.inventory.set_variable(host_ip, "idrac_ip", host_ip)
123 self.inventory.set_variable(host_ip, "baseuri", host_ip)
124 self.inventory.set_variable(host_ip, "hostname", host_ip)
125 for key, val in device_info.items():
126 self.inventory.set_variable(host_ip, key, val)
127 if "host_vars" in self.config:
128 host_vars = self.get_option("host_vars")
129 for key, val in dict(host_vars).items():
130 self.inventory.set_variable(host_ip, key, val)
131
132 def _set_group_vars(self, group):
133 group = self._to_safe_group_name(group)
134 self.inventory.add_group(group)
135 if "group_vars" in self.config:
136 group_vars = self.get_option("group_vars")
137 if group in dict(group_vars):
138 for key, val in dict(dict(group_vars)[group]).items():
139 self.inventory.set_variable(group, key, val)
140
141 def _get_device_host(self, mgmt):
142 device_info = {
143 "Model": mgmt.get("Model", ""),
144 "ServiceTag": mgmt.get("DeviceServiceTag", ""),
145 "OSName": mgmt.get("DeviceName", ""),
146 }
147 mgmt_entry = mgmt["DeviceManagement"][0]
148 device_info["iDracName"] = mgmt_entry.get("DnsName", "")
149 profiles = mgmt_entry.get("ManagementProfile", [])
150 device_info["iDracVersion"] = profiles[0].get("Version", "") if profiles else ""
151 if len(mgmt["DeviceManagement"]) == 1 and mgmt_entry["NetworkAddress"].startswith("["):
152 dev_ip = mgmt_entry["NetworkAddress"][1:-1]
153 elif len(mgmt["DeviceManagement"]) == 2 and mgmt_entry["NetworkAddress"].startswith("["):
154 dev_ip = mgmt["DeviceManagement"][1]["NetworkAddress"]
155 else:
156 dev_ip = mgmt_entry["NetworkAddress"]
157 return dev_ip, device_info
158
159 def _get_all_devices(self, device_uri):
160 device_host = []
161 device_host_uri = device_uri.strip("/api/")
162 port = self.get_option("port") if "port" in self.config else 443
163 validate_certs = self.get_option("validate_certs") if "validate_certs" in self.config else False
164 module_params = {
165 "hostname": self.get_option("hostname"),
166 "username": self.get_option("username"),
167 "password": self.get_option("password"),
168 "port": port,
169 "validate_certs": validate_certs}
170 if "ca_path" in self.config:
171 module_params.update({"ca_path": self.get_option("ca_path")})
172 with RestOME(module_params, req_session=True) as ome:
173 device_resp = get_all_data_with_pagination(ome, device_host_uri)
174 device_data = device_resp.get("report_list", [])
175 if device_data is not None:
176 for mgmt in device_data:
177 if (len(mgmt["DeviceManagement"]) != 0):
178 device_host.append(self._get_device_host(mgmt))
179 return device_host # list of (ip, device_info) tuples
180
181 def _set_child_group(self, group_data):
182 port = self.get_option("port") if "port" in self.config else 443
183 validate_certs = self.get_option("validate_certs") if "validate_certs" in self.config else False
184 module_params = {"hostname": self.get_option("hostname"), "username": self.get_option("username"),
185 "password": self.get_option("password"), "port": port, "validate_certs": validate_certs}
186 if "ca_path" in self.config:
187 module_params.update({"ca_path": self.get_option("ca_path")})
188 with RestOME(module_params, req_session=True) as ome:
189 for gdata in group_data:
190 group_name = gdata["Name"]
191 subgroup_uri = gdata["[email protected]"].strip("/api/")
192 sub_group = get_all_data_with_pagination(ome, subgroup_uri)
193 gdata = sub_group.get("report_list", [])
194 if gdata:
195 self._add_group_data(gdata)
196 self._add_child_group_data(group_name, gdata)
197
198 def _add_child_group_data(self, group_name, gdata):
199 group_name = self._to_safe_group_name(group_name)
200 for child_name in gdata:
201 self.inventory.add_child(group_name, self._to_safe_group_name(child_name["Name"]))
202
203 def _add_group_data(self, group_data):
204 visible_gdata = list(filter(lambda d: d.get("Visible") in [False], group_data))
205 if visible_gdata:
206 for gp in visible_gdata:
207 group_data.remove(gp)
208 for gdata in group_data:
209 safe_name = self._to_safe_group_name(gdata["Name"])
210 self._set_group_vars(gdata["Name"])
211 devices = self._get_all_devices(gdata["[email protected]"])
212 for host_ip, device_info in devices:
213 self.inventory.add_host(host=host_ip, group=safe_name)
214 self._set_host_vars(host_ip, device_info)
215 self._set_child_group(group_data)
216
217 def _populate(self, all_group_data):
218 group_data = all_group_data.get("report_list", [])
219 group_name = str(self.get_option("ome_group_name")) if "ome_group_name" in self.config else None
220 if group_name is not None:
221 group_data = list(filter(lambda d: d.get("Name").lower() in [group_name.lower()], group_data))
222 elif group_name is None:
223 group_data = list(filter(lambda d: d.get("Name") in ["All Devices"], group_data))
224 self._add_group_data(group_data)
225
226 def parse(self, inventory, loader, path, cache=True):
227 super(InventoryModule, self).parse(inventory, loader, path, cache)
228 self.config = self._read_config_data(path)
229 all_group_data = self._get_connection_resp()
230 self._populate(all_group_data)