Debian Codegraph @

ansible_collections/cisco/meraki/plugins/modules/meraki_network.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, 2019 Kevin Breit (@kbreit) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["deprecated"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 author:
19 - Kevin Breit (@kbreit)
20 deprecated:
21 alternative: cisco.meraki.networks
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Allows for creation, management, and visibility into networks within Meraki.
26 extends_documentation_fragment: cisco.meraki.meraki
27 module: meraki_network
28 options:
29 copy_from_network_id:
30 description:
31 - New network inherits properties from this network ID.
32 - Other provided parameters will override the copied configuration.
33 - Type which must match this network's type exactly.
34 type: str
35 enable_vlans:
36 description:
37 - Boolean value specifying whether VLANs should be supported on a network.
38 - Requires C(net_name) or C(net_id) to be specified.
39 type: bool
40 local_status_page_enabled:
41 description: '- This no longer works and will likely be moved to a separate module.
42 - Enables the local device status pages (U[my.meraki.com](my.meraki.com), U[ap.meraki.com](ap.meraki.com),
43 U[switch.meraki.com](switch.meraki.com), U[wired.meraki.com](wired.meraki.com)).
44 - Only can be specified on its own or with C(remote_status_page_enabled). '
45 type: bool
46 net_id:
47 description:
48 - ID number of a network.
49 type: str
50 net_name:
51 aliases:
52 - name
53 - network
54 description:
55 - Name of a network.
56 type: str
57 remote_status_page_enabled:
58 description:
59 - This no longer works and will likely be moved to a separate module.
60 - Enables access to the device status page (U(http://device LAN IP)).
61 - Can only be set if C(local_status_page_enabled:) is set to C(yes).
62 - Only can be specified on its own or with C(local_status_page_enabled).
63 type: bool
64 state:
65 choices:
66 - absent
67 - present
68 - query
69 default: present
70 description:
71 - Create or modify an organization.
72 type: str
73 tags:
74 description:
75 - List of tags to assign to network.
76 - C(tags) name conflicts with the tags parameter in Ansible. Indentation problems
77 may cause unexpected behaviors.
78 - Ansible 2.8 converts this to a list from a comma separated list.
79 elements: str
80 type: list
81 timezone:
82 description:
83 - Timezone associated to network.
84 - See U(https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for a
85 list of valid timezones.
86 type: str
87 type:
88 aliases:
89 - net_type
90 choices:
91 - appliance
92 - switch
93 - wireless
94 - sensor
95 - systemsManager
96 - camera
97 - cellularGateway
98 description:
99 - Type of network device network manages.
100 - Required when creating a network.
101 - As of Ansible 2.8, C(combined) type is no longer accepted.
102 - As of Ansible 2.8, changes to this parameter are no longer idempotent.
103 elements: str
104 type: list
105 short_description: Manage networks in the Meraki cloud
106 """
107
108 EXAMPLES = r"""
109 - delegate_to: localhost
110 block:
111 - name: List all networks associated to the YourOrg organization
112 meraki_network:
113 auth_key: abc12345
114 state: query
115 org_name: YourOrg
116 - name: Query network named MyNet in the YourOrg organization
117 meraki_network:
118 auth_key: abc12345
119 state: query
120 org_name: YourOrg
121 net_name: MyNet
122 - name: Create network named MyNet in the YourOrg organization
123 meraki_network:
124 auth_key: abc12345
125 state: present
126 org_name: YourOrg
127 net_name: MyNet
128 type: switch
129 timezone: America/Chicago
130 tags: production, chicago
131 - name: Create combined network named MyNet in the YourOrg organization
132 meraki_network:
133 auth_key: abc12345
134 state: present
135 org_name: YourOrg
136 net_name: MyNet
137 type:
138 - switch
139 - appliance
140 timezone: America/Chicago
141 tags: production, chicago
142 - name: Create new network based on an existing network
143 meraki_network:
144 auth_key: abc12345
145 state: present
146 org_name: YourOrg
147 net_name: MyNet
148 type:
149 - switch
150 - appliance
151 copy_from_network_id: N_1234
152 - name: Enable VLANs on a network
153 meraki_network:
154 auth_key: abc12345
155 state: query
156 org_name: YourOrg
157 net_name: MyNet
158 enable_vlans: true
159 - name: Modify local status page enabled state
160 meraki_network:
161 auth_key: abc12345
162 state: query
163 org_name: YourOrg
164 net_name: MyNet
165 local_status_page_enabled: true
166 """
167
168 RETURN = r"""
169 data:
170 description: Information about the created or manipulated object.
171 returned: info
172 type: complex
173 contains:
174 id:
175 description: Identification string of network.
176 returned: success
177 type: str
178 sample: N_12345
179 name:
180 description: Written name of network.
181 returned: success
182 type: str
183 sample: YourNet
184 organization_id:
185 description: Organization ID which owns the network.
186 returned: success
187 type: str
188 sample: 0987654321
189 tags:
190 description: Space delimited tags assigned to network.
191 returned: success
192 type: list
193 sample: ['production']
194 time_zone:
195 description: Timezone where network resides.
196 returned: success
197 type: str
198 sample: America/Chicago
199 type:
200 description: Functional type of network.
201 returned: success
202 type: list
203 sample: ['switch']
204 local_status_page_enabled:
205 description: States whether U(my.meraki.com) and other device portals should be enabled.
206 returned: success
207 type: bool
208 sample: true
209 remote_status_page_enabled:
210 description: Enables access to the device status page.
211 returned: success
212 type: bool
213 sample: true
214 """
215
216 from ansible.module_utils.basic import AnsibleModule, json
217 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
218 MerakiModule,
219 meraki_argument_spec,
220 )
221
222
223 def is_net_valid(data, net_name=None, net_id=None):
224 if net_name is None and net_id is None:
225 return False
226 for n in data:
227 if net_name:
228 if n["name"] == net_name:
229 return True
230 elif net_id:
231 if n["id"] == net_id:
232 return True
233 return False
234
235
236 def get_network_settings(meraki, net_id):
237 path = meraki.construct_path("get_settings", net_id=net_id)
238 response = meraki.request(path, method="GET")
239 return response
240
241
242 def main():
243
244 # define the available arguments/parameters that a user can pass to
245 # the module
246
247 argument_spec = meraki_argument_spec()
248 argument_spec.update(
249 net_id=dict(type="str"),
250 type=dict(
251 type="list",
252 elements="str",
253 choices=[
254 "wireless",
255 "switch",
256 "appliance",
257 "sensor",
258 "systemsManager",
259 "camera",
260 "cellularGateway",
261 ],
262 aliases=["net_type"],
263 ),
264 tags=dict(type="list", elements="str"),
265 timezone=dict(type="str"),
266 net_name=dict(type="str", aliases=["name", "network"]),
267 state=dict(
268 type="str", choices=["present", "query", "absent"], default="present"
269 ),
270 enable_vlans=dict(type="bool"),
271 local_status_page_enabled=dict(type="bool"),
272 remote_status_page_enabled=dict(type="bool"),
273 copy_from_network_id=dict(type="str"),
274 )
275
276 # the AnsibleModule object will be our abstraction working with Ansible
277 # this includes instantiation, a couple of common attr would be the
278 # args/params passed to the execution, as well as if the module
279 # supports check mode
280 module = AnsibleModule(
281 argument_spec=argument_spec,
282 supports_check_mode=True,
283 )
284
285 meraki = MerakiModule(module, function="network")
286 module.params["follow_redirects"] = "all"
287 payload = None
288
289 create_urls = {"network": "/organizations/{org_id}/networks"}
290 update_urls = {"network": "/networks/{net_id}"}
291 delete_urls = {"network": "/networks/{net_id}"}
292 update_settings_urls = {"network": "/networks/{net_id}/settings"}
293 get_settings_urls = {"network": "/networks/{net_id}/settings"}
294 enable_vlans_urls = {"network": "/networks/{net_id}/appliance/vlans/settings"}
295 get_vlan_status_urls = {"network": "/networks/{net_id}/appliance/vlans/settings"}
296 meraki.url_catalog["create"] = create_urls
297 meraki.url_catalog["update"] = update_urls
298 meraki.url_catalog["update_settings"] = update_settings_urls
299 meraki.url_catalog["get_settings"] = get_settings_urls
300 meraki.url_catalog["delete"] = delete_urls
301 meraki.url_catalog["enable_vlans"] = enable_vlans_urls
302 meraki.url_catalog["status_vlans"] = get_vlan_status_urls
303
304 if not meraki.params["org_name"] and not meraki.params["org_id"]:
305 meraki.fail_json(msg="org_name or org_id parameters are required")
306 if meraki.params["state"] != "query":
307 if not meraki.params["net_name"] and not meraki.params["net_id"]:
308 meraki.fail_json(
309 msg="net_name or net_id is required for present or absent states"
310 )
311 if meraki.params["net_name"] and meraki.params["net_id"]:
312 meraki.fail_json(msg="net_name and net_id are mutually exclusive")
313 if not meraki.params["net_name"] and not meraki.params["net_id"]:
314 if meraki.params["enable_vlans"]:
315 meraki.fail_json(
316 msg="The parameter 'enable_vlans' requires 'net_name' or 'net_id' to be specified"
317 )
318 if (
319 meraki.params["local_status_page_enabled"] is False
320 and meraki.params["remote_status_page_enabled"] is True
321 ):
322 meraki.fail_json(
323 msg="local_status_page_enabled must be true when setting remote_status_page_enabled"
324 )
325
326 # Construct payload
327 if meraki.params["state"] == "present":
328 payload = dict()
329 if meraki.params["net_name"]:
330 payload["name"] = meraki.params["net_name"]
331 if meraki.params["type"]:
332 payload["productTypes"] = meraki.params["type"]
333 if meraki.params["tags"]:
334 payload["tags"] = meraki.params["tags"]
335 if meraki.params["timezone"]:
336 payload["timeZone"] = meraki.params["timezone"]
337 if meraki.params["local_status_page_enabled"] is not None:
338 payload["localStatusPageEnabled"] = meraki.params[
339 "local_status_page_enabled"
340 ]
341 if meraki.params["remote_status_page_enabled"] is not None:
342 payload["remoteStatusPageEnabled"] = meraki.params[
343 "remote_status_page_enabled"
344 ]
345 if meraki.params["copy_from_network_id"] is not None:
346 payload["copyFromNetworkId"] = meraki.params["copy_from_network_id"]
347
348 # manipulate or modify the state as needed (this is going to be the
349 # part where your module will do what it needs to do)
350
351 org_id = meraki.params["org_id"]
352 if not org_id:
353 org_id = meraki.get_org_id(meraki.params["org_name"])
354 nets = meraki.get_nets(org_id=org_id)
355 net_id = meraki.params["net_id"]
356 net_exists = False
357 if net_id is not None:
358 if is_net_valid(nets, net_id=net_id) is False:
359 meraki.fail_json(msg="Network specified by net_id does not exist.")
360 net_exists = True
361 elif meraki.params["net_name"]:
362 if is_net_valid(nets, net_name=meraki.params["net_name"]) is True:
363 net_id = meraki.get_net_id(net_name=meraki.params["net_name"], data=nets)
364 net_exists = True
365
366 if meraki.params["state"] == "query":
367 if not meraki.params["net_name"] and not meraki.params["net_id"]:
368 meraki.result["data"] = nets
369 elif meraki.params["net_name"] or meraki.params["net_id"] is not None:
370 if (
371 meraki.params["local_status_page_enabled"] is not None
372 or meraki.params["remote_status_page_enabled"] is not None
373 ):
374 meraki.result["data"] = get_network_settings(meraki, net_id)
375 meraki.exit_json(**meraki.result)
376 else:
377 meraki.result["data"] = meraki.get_net(
378 meraki.params["org_name"], net_name=meraki.params["net_name"], data=nets, net_id=meraki.params["net_id"],
379 )
380 meraki.exit_json(**meraki.result)
381 elif meraki.params["state"] == "present":
382 if net_exists is False: # Network needs to be created
383 if "type" not in meraki.params or meraki.params["type"] is None:
384 meraki.fail_json(
385 msg="type parameter is required when creating a network."
386 )
387 if meraki.check_mode is True:
388 data = payload
389 data["id"] = "N_12345"
390 data["organization_id"] = org_id
391 meraki.result["data"] = data
392 meraki.result["changed"] = True
393 meraki.exit_json(**meraki.result)
394 path = meraki.construct_path("create", org_id=org_id)
395 r = meraki.request(path, method="POST", payload=json.dumps(payload))
396 if meraki.status == 201:
397 meraki.result["data"] = r
398 meraki.result["changed"] = True
399 else: # Network exists, make changes
400 if meraki.params["enable_vlans"] is not None: # Modify VLANs configuration
401 status_path = meraki.construct_path("status_vlans", net_id=net_id)
402 status = meraki.request(status_path, method="GET")
403 payload = {"vlansEnabled": meraki.params["enable_vlans"]}
404 if meraki.is_update_required(status, payload):
405 if meraki.check_mode is True:
406 data = {
407 "vlansEnabled": meraki.params["enable_vlans"],
408 "network_id": net_id,
409 }
410 meraki.result["data"] = data
411 meraki.result["changed"] = True
412 meraki.exit_json(**meraki.result)
413 path = meraki.construct_path("enable_vlans", net_id=net_id)
414 r = meraki.request(path, method="PUT", payload=json.dumps(payload))
415 if meraki.status == 200:
416 meraki.result["data"] = r
417 meraki.result["changed"] = True
418 meraki.exit_json(**meraki.result)
419 else:
420 meraki.result["data"] = status
421 meraki.exit_json(**meraki.result)
422 elif (
423 meraki.params["local_status_page_enabled"] is not None
424 or meraki.params["remote_status_page_enabled"] is not None
425 ):
426 path = meraki.construct_path("get_settings", net_id=net_id)
427 original = meraki.request(path, method="GET")
428 payload = {}
429 if meraki.params["local_status_page_enabled"] is not None:
430 payload["localStatusPageEnabled"] = meraki.params[
431 "local_status_page_enabled"
432 ]
433 if meraki.params["remote_status_page_enabled"] is not None:
434 payload["remoteStatusPageEnabled"] = meraki.params[
435 "remote_status_page_enabled"
436 ]
437 if meraki.is_update_required(original, payload):
438 if meraki.check_mode is True:
439 original.update(payload)
440 meraki.result["data"] = original
441 meraki.result["changed"] = True
442 meraki.exit_json(**meraki.result)
443 path = meraki.construct_path("update_settings", net_id=net_id)
444 response = meraki.request(
445 path, method="PUT", payload=json.dumps(payload)
446 )
447 meraki.result["data"] = response
448 meraki.result["changed"] = True
449 meraki.exit_json(**meraki.result)
450 else:
451 meraki.result["data"] = original
452 meraki.exit_json(**meraki.result)
453 net = meraki.get_net(meraki.params["org_name"], net_id=net_id, data=nets)
454 if meraki.is_update_required(net, payload):
455 if meraki.check_mode is True:
456 data = net
457 net.update(payload)
458 meraki.result["data"] = net
459 meraki.result["changed"] = True
460 meraki.exit_json(**meraki.result)
461 path = meraki.construct_path("update", net_id=net_id)
462 r = meraki.request(path, method="PUT", payload=json.dumps(payload))
463 if meraki.status == 200:
464 meraki.result["data"] = r
465 meraki.result["changed"] = True
466 else:
467 meraki.result["data"] = net
468 elif meraki.params["state"] == "absent":
469 if is_net_valid(nets, net_id=net_id) is True:
470 if meraki.check_mode is True:
471 meraki.result["data"] = {}
472 meraki.result["changed"] = True
473 meraki.exit_json(**meraki.result)
474 path = meraki.construct_path("delete", net_id=net_id)
475 r = meraki.request(path, method="DELETE")
476 if meraki.status == 204:
477 meraki.result["changed"] = True
478
479 # in the event of a successful module execution, you will want to
480 # simple AnsibleModule.exit_json(), passing the key/value results
481 meraki.exit_json(**meraki.result)
482
483
484 if __name__ == "__main__":
485 main()