Debian Codegraph @

ansible_collections/cisco/meraki/plugins/inventory/meraki.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2024, Cisco Systems
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import (absolute_import, division, print_function)
6 __metaclass__ = type
7
8 DOCUMENTATION = r"""
9 name: meraki
10 author:
11 - Nilashish Chakraborty (@NilashishC)
12 short_description: Ansible dynamic inventory plugin for Cisco Meraki devices.
13 requirements:
14 - meraki
15 extends_documentation_fragment:
16 - constructed
17 description:
18 - Build inventories using the Cisco Meraki API.
19 - Uses a YAML configuration file cisco_meraki.[yml|yaml].
20 options:
21 meraki_org_id:
22 description:
23 - The organization ID to fetch the networks and devices from.
24 type: str
25 required: true
26 meraki_api_key:
27 description:
28 - meraki_api_key (string), API key generated in dashboard; can also be set as an environment variable MERAKI_DASHBOARD_API_KEY
29 type: str
30 meraki_base_url:
31 description:
32 - meraki_base_url (string), preceding all endpoint resources
33 type: str
34 default: https://api.meraki.com/api/v1
35 meraki_single_request_timeout:
36 description:
37 - meraki_single_request_timeout (integer), maximum number of seconds for each API call
38 type: int
39 default: 60
40 meraki_certificate_path:
41 description:
42 - meraki_certificate_path (string), path for TLS/SSL certificate verification if behind local proxy
43 type: str
44 default: ''
45 meraki_requests_proxy:
46 description:
47 - meraki_requests_proxy (string), proxy server and port, if needed, for HTTPS
48 type: str
49 default: ''
50 meraki_wait_on_rate_limit:
51 description:
52 - meraki_wait_on_rate_limit (boolean), retry if 429 rate limit error encountered?
53 type: bool
54 default: true
55 meraki_nginx_429_retry_wait_time:
56 description:
57 - meraki_nginx_429_retry_wait_time (integer), Nginx 429 retry wait time
58 type: int
59 default: 60
60 meraki_action_batch_retry_wait_time:
61 description:
62 - meraki_action_batch_retry_wait_time (integer), action batch concurrency error retry wait time
63 type: int
64 default: 60
65 meraki_retry_4xx_error:
66 description:
67 - meraki_retry_4xx_error (boolean), retry if encountering other 4XX error (besides 429)?
68 type: bool
69 default: false
70 meraki_retry_4xx_error_wait_time:
71 description:
72 - meraki_retry_4xx_error_wait_time (integer), other 4XX error retry wait time
73 type: int
74 default: 60
75 meraki_maximum_retries:
76 description:
77 - meraki_maximum_retries (integer), retry up to this many times when encountering 429s or other server-side errors
78 type: int
79 default: 2
80 meraki_output_log:
81 description:
82 - meraki_output_log (boolean), create an output log file?
83 type: bool
84 default: true
85 meraki_log_file_prefix:
86 description:
87 - meraki_log_file_prefix (string), log file name appended with date and timestamp
88 type: str
89 default: meraki_api_
90 meraki_log_path:
91 description:
92 - log_path (string), path to output log; by default, working directory of script if not specified
93 type: str
94 default: ''
95 meraki_print_console:
96 description:
97 - meraki_print_console (boolean), print logging output to console?
98 type: bool
99 default: true
100 meraki_suppress_logging:
101 description:
102 - meraki_suppress_logging (boolean), disable all logging? you're on your own then!
103 type: bool
104 default: false
105 meraki_simulate:
106 description:
107 - meraki_simulate (boolean), simulate POST/PUT/DELETE calls to prevent changes?
108 type: bool
109 default: false
110 meraki_be_geo_id:
111 description:
112 - meraki_be_geo_id (string), optional partner identifier for API usage tracking; can also be set as an environment variable BE_GEO_ID
113 type: str
114 default: ''
115 meraki_use_iterator_for_get_pages:
116 description:
117 - meraki_use_iterator_for_get_pages (boolean), list* methods will return an iterator with each object instead of a complete list with all items
118 type: bool
119 default: false
120 meraki_inherit_logging_config:
121 description:
122 - meraki_inherit_logging_config (boolean), Inherits your own logger instance
123 type: bool
124 default: false
125 """
126
127 EXAMPLES = r"""
128 # cisco_meraki.yml
129 ---
130 plugin: cisco.meraki.meraki
131 meraki_api_key: "<enter Meraki API key or set the MERAKI_DASHBOARD_API_KEY env var>"
132 meraki_org_id: "<enter Meraki Org ID>"
133 keyed_groups:
134 # group devices based on network ID
135 - prefix: meraki_network_id
136 key: network_id
137 # group devices based on network name
138 - prefix: meraki_network
139 key: network
140 # group devices based on device type
141 - prefix: meraki_device_type
142 key: device_type
143 # group devices based on meraki device tag
144 - prefix: meraki_tag
145 key: tags
146 """
147
148 from ansible_collections.cisco.meraki.plugins.plugin_utils.meraki import (
149 MERAKI,
150 meraki_argument_spec,
151 )
152 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
153 from ansible.module_utils.common.text.converters import to_native, to_text
154 from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
155 from ansible.errors import AnsibleError
156
157
158 meraki_argument_spec = meraki_argument_spec()
159 meraki_argument_spec.update(
160 dict(meraki_org_id=dict(type="str", required=True)))
161
162
163 class InventoryModule(BaseInventoryPlugin, Constructable):
164 NAME = "cisco.meraki.meraki"
165
166 def verify_file(self, path):
167 """return true/false if this is possibly a valid file for this plugin to consume"""
168 valid = False
169 if super(InventoryModule, self).verify_file(path):
170 # base class verifies that file exists and is readable by current user
171 if path.endswith(("cisco_meraki.yaml", "cisco_meraki.yml")):
172 valid = True
173 return valid
174
175 def _build_network_map(self, dashboard, org_id):
176 """Build a dictionary mapping network ID to network names."""
177 network_map = {}
178 networks = dashboard.exec_meraki(
179 family="organizations",
180 function="getOrganizationNetworks",
181 params={"organizationId": org_id, "total_pages": "all"}
182 )
183 for network in networks:
184 network_map[network["id"]] = to_text(network.get("name", ""))
185
186 return network_map
187
188 def _validate_argspec(self, parameters):
189 "Validate the inventory plugin argspec."
190 argspec_validator = ArgumentSpecValidator(meraki_argument_spec)
191 result = argspec_validator.validate(parameters)
192
193 if result.error_messages:
194 raise AnsibleError(
195 f"Validation failed: {', '.join(result.error_messages)}")
196
197 return result.validated_parameters
198
199 def parse(self, inventory, loader, path, cache=True):
200 """Talk to the Meraki API and build the inventory."""
201
202 # call base method to ensure properties are available for use with other helper methods
203 super(InventoryModule, self).parse(inventory, loader, path, cache)
204
205 config = self._read_config_data(path)
206 meraki_connect_config = {
207 k: config[k] for k in config if k in meraki_argument_spec
208 }
209
210 validated_config = self._validate_argspec(
211 parameters=meraki_connect_config)
212
213 meraki_org_id = validated_config.pop("meraki_org_id")
214
215 strict = self.get_option("strict")
216
217 dashboard = MERAKI(params=validated_config)
218
219 try:
220 devices = dashboard.exec_meraki(
221 family="organizations",
222 function="getOrganizationDevices",
223 params={"organizationId": meraki_org_id, "total_pages": "all"},
224 )
225 if devices:
226 network_map = self._build_network_map(dashboard, meraki_org_id)
227
228 for device in devices:
229 hostname = device.get("name")
230 if not hostname:
231 self.display.warning(
232 f"No name set for device with MAC {device['mac']}"
233 )
234 hostname = device["mac"]
235 self.inventory.add_host(hostname, group="all")
236
237 if device.get("networkId"):
238 self.inventory.set_variable(
239 hostname, "network_id", device["networkId"]
240 )
241 self.inventory.set_variable(
242 hostname, "network", network_map[device["networkId"]]
243 )
244 else:
245 self.display.vvvv(
246 f"Device {hostname} is not associated with a network."
247 )
248
249 if device.get("lanIp"):
250 self.inventory.set_variable(
251 hostname, "ansible_host", device["lanIp"]
252 )
253 else:
254 self.display.warning(
255 f"No lanIp found for device with {hostname}."
256 " The `ansible_host` variable will not be set for this host."
257 )
258
259 self.inventory.set_variable(
260 hostname, "device_type", device["model"]
261 )
262
263 self.inventory.set_variable(
264 hostname, "ansible_product_serial", device["serial"]
265 )
266 self.inventory.set_variable(
267 hostname, "macaddress", device["mac"])
268
269 # Add variables created by the user's Jinja2 expressions to the host
270 self._set_composite_vars(self.get_option(
271 "compose"), device, hostname, strict=True)
272
273 # Create user-defined groups using variables and Jinja2 conditionals
274 self._add_host_to_composed_groups(self.get_option(
275 "groups"), device, hostname, strict=strict)
276 # Add the host to the keyed groups
277 self._add_host_to_keyed_groups(
278 keys=self.get_option("keyed_groups"),
279 variables=device,
280 host=hostname,
281 strict=strict,
282 )
283 except Exception as e:
284 raise AnsibleError(
285 f"Failed to get devices from Meraki API: {to_native(e)}")