Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, 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 __metaclass__ = type
9
10 ANSIBLE_METADATA = {
11 'metadata_version': '1.1',
12 "status": ['deprecated'],
13 'supported_by': 'community'
14 }
15
16 DOCUMENTATION = r'''
17 ---
18 module: meraki_mx_vlan
19 short_description: Manage VLANs in the Meraki cloud
20 description:
21 - Create, edit, query, or delete VLANs in a Meraki environment.
22 notes:
23 - Meraki's API will return an error if VLANs aren't enabled on a network. VLANs are returned properly if VLANs are enabled on a network.
24 - Some of the options are likely only used for developers within Meraki.
25 - Meraki's API defaults to networks having VLAN support disabled and there is no way to enable VLANs support in the API. VLAN support must be enabled manually.
26 deprecated:
27 removed_in: '3.0.0'
28 why: Updated modules released with increased functionality
29 alternative: cisco.meraki.networks_appliance_vlans
30 options:
31 state:
32 description:
33 - Specifies whether object should be queried, created/modified, or removed.
34 choices: [absent, present, query]
35 default: query
36 type: str
37 net_name:
38 description:
39 - Name of network which VLAN is in or should be in.
40 aliases: [network]
41 type: str
42 net_id:
43 description:
44 - ID of network which VLAN is in or should be in.
45 type: str
46 vlan_id:
47 description:
48 - ID number of VLAN.
49 - ID should be between 1-4096.
50 type: int
51 name:
52 description:
53 - Name of VLAN.
54 aliases: [vlan_name]
55 type: str
56 subnet:
57 description:
58 - CIDR notation of network subnet.
59 type: str
60 appliance_ip:
61 description:
62 - IP address of appliance.
63 - Address must be within subnet specified in C(subnet) parameter.
64 type: str
65 dns_nameservers:
66 description:
67 - Semi-colon delimited list of DNS IP addresses.
68 - Specify one of the following options for preprogrammed DNS entries opendns, google_dns, upstream_dns
69 type: str
70 reserved_ip_range:
71 description:
72 - IP address ranges which should be reserve and not distributed via DHCP.
73 type: list
74 elements: dict
75 suboptions:
76 start:
77 description: First IP address of reserved IP address range, inclusive.
78 type: str
79 end:
80 description: Last IP address of reserved IP address range, inclusive.
81 type: str
82 comment:
83 description: Description of IP addresses reservation
84 type: str
85 vpn_nat_subnet:
86 description:
87 - The translated VPN subnet if VPN and VPN subnet translation are enabled on the VLAN.
88 type: str
89 fixed_ip_assignments:
90 description:
91 - Static IP address assignments to be distributed via DHCP by MAC address.
92 type: list
93 elements: dict
94 suboptions:
95 mac:
96 description: MAC address for fixed IP assignment binding.
97 type: str
98 ip:
99 description: IP address for fixed IP assignment binding.
100 type: str
101 name:
102 description: Descriptive name of IP assignment binding.
103 type: str
104 dhcp_handling:
105 description:
106 - How to handle DHCP packets on network.
107 type: str
108 choices: ['Run a DHCP server',
109 'Relay DHCP to another server',
110 'Do not respond to DHCP requests',
111 'none',
112 'server',
113 'relay']
114 dhcp_relay_server_ips:
115 description:
116 - IP addresses to forward DHCP packets to.
117 type: list
118 elements: str
119 dhcp_lease_time:
120 description:
121 - DHCP lease timer setting
122 type: str
123 choices: ['30 minutes',
124 '1 hour',
125 '4 hours',
126 '12 hours',
127 '1 day',
128 '1 week']
129 dhcp_boot_options_enabled:
130 description:
131 - Enable DHCP boot options
132 type: bool
133 dhcp_boot_next_server:
134 description:
135 - DHCP boot option to direct boot clients to the server to load boot file from.
136 type: str
137 dhcp_boot_filename:
138 description:
139 - Filename to boot from for DHCP boot
140 type: str
141 dhcp_options:
142 description:
143 - List of DHCP option values
144 type: list
145 elements: dict
146 suboptions:
147 code:
148 description:
149 - DHCP option number.
150 type: int
151 type:
152 description:
153 - Type of value for DHCP option.
154 type: str
155 choices: ['text', 'ip', 'hex', 'integer']
156 value:
157 description:
158 - Value for DHCP option.
159 type: str
160 author:
161 - Kevin Breit (@kbreit)
162 extends_documentation_fragment: cisco.meraki.meraki
163 '''
164
165 EXAMPLES = r'''
166 - name: Query all VLANs in a network.
167 meraki_vlan:
168 auth_key: abc12345
169 org_name: YourOrg
170 net_name: YourNet
171 state: query
172 delegate_to: localhost
173
174 - name: Query information about a single VLAN by ID.
175 meraki_vlan:
176 auth_key: abc12345
177 org_name: YourOrg
178 net_name: YourNet
179 vlan_id: 2
180 state: query
181 delegate_to: localhost
182
183 - name: Create a VLAN.
184 meraki_vlan:
185 auth_key: abc12345
186 org_name: YourOrg
187 net_name: YourNet
188 state: present
189 vlan_id: 2
190 name: TestVLAN
191 subnet: 192.0.1.0/24
192 appliance_ip: 192.0.1.1
193 delegate_to: localhost
194
195 - name: Update a VLAN.
196 meraki_vlan:
197 auth_key: abc12345
198 org_name: YourOrg
199 net_name: YourNet
200 state: present
201 vlan_id: 2
202 name: TestVLAN
203 subnet: 192.0.1.0/24
204 appliance_ip: 192.168.250.2
205 fixed_ip_assignments:
206 - mac: "13:37:de:ad:be:ef"
207 ip: 192.168.250.10
208 name: fixed_ip
209 reserved_ip_range:
210 - start: 192.168.250.10
211 end: 192.168.250.20
212 comment: reserved_range
213 dns_nameservers: opendns
214 delegate_to: localhost
215
216 - name: Enable DHCP on VLAN with options
217 meraki_vlan:
218 auth_key: abc123
219 state: present
220 org_name: YourOrg
221 net_name: YourNet
222 vlan_id: 2
223 name: TestVLAN
224 subnet: 192.168.250.0/24
225 appliance_ip: 192.168.250.2
226 dhcp_handling: server
227 dhcp_lease_time: 1 hour
228 dhcp_boot_options_enabled: false
229 dhcp_options:
230 - code: 5
231 type: ip
232 value: 192.0.1.1
233 delegate_to: localhost
234
235 - name: Delete a VLAN.
236 meraki_vlan:
237 auth_key: abc12345
238 org_name: YourOrg
239 net_name: YourNet
240 state: absent
241 vlan_id: 2
242 delegate_to: localhost
243 '''
244
245 RETURN = r'''
246
247 response:
248 description: Information about the organization which was created or modified
249 returned: success
250 type: complex
251 contains:
252 appliance_ip:
253 description: IP address of Meraki appliance in the VLAN
254 returned: success
255 type: str
256 sample: 192.0.1.1
257 dnsnamservers:
258 description: IP address or Meraki defined DNS servers which VLAN should use by default
259 returned: success
260 type: str
261 sample: upstream_dns
262 fixed_ip_assignments:
263 description: List of MAC addresses which have IP addresses assigned.
264 returned: success
265 type: complex
266 contains:
267 macaddress:
268 description: MAC address which has IP address assigned to it. Key value is the actual MAC address.
269 returned: success
270 type: complex
271 contains:
272 ip:
273 description: IP address which is assigned to the MAC address.
274 returned: success
275 type: str
276 sample: 192.0.1.4
277 name:
278 description: Descriptive name for binding.
279 returned: success
280 type: str
281 sample: fixed_ip
282 reserved_ip_ranges:
283 description: List of IP address ranges which are reserved for static assignment.
284 returned: success
285 type: complex
286 contains:
287 comment:
288 description: Description for IP address reservation.
289 returned: success
290 type: str
291 sample: reserved_range
292 end:
293 description: Last IP address in reservation range.
294 returned: success
295 type: str
296 sample: 192.0.1.10
297 start:
298 description: First IP address in reservation range.
299 returned: success
300 type: str
301 sample: 192.0.1.5
302 id:
303 description: VLAN ID number.
304 returned: success
305 type: int
306 sample: 2
307 name:
308 description: Descriptive name of VLAN.
309 returned: success
310 type: str
311 sample: TestVLAN
312 networkId:
313 description: ID number of Meraki network which VLAN is associated to.
314 returned: success
315 type: str
316 sample: N_12345
317 subnet:
318 description: CIDR notation IP subnet of VLAN.
319 returned: success
320 type: str
321 sample: "192.0.1.0/24"
322 dhcp_handling:
323 description: Status of DHCP server on VLAN.
324 returned: success
325 type: str
326 sample: Run a DHCP server
327 dhcp_lease_time:
328 description: DHCP lease time when server is active.
329 returned: success
330 type: str
331 sample: 1 day
332 dhcp_boot_options_enabled:
333 description: Whether DHCP boot options are enabled.
334 returned: success
335 type: bool
336 sample: false
337 dhcp_boot_next_server:
338 description: DHCP boot option to direct boot clients to the server to load the boot file from.
339 returned: success
340 type: str
341 sample: 192.0.1.2
342 dhcp_boot_filename:
343 description: Filename for boot file.
344 returned: success
345 type: str
346 sample: boot.txt
347 dhcp_options:
348 description: DHCP options.
349 returned: success
350 type: complex
351 contains:
352 code:
353 description:
354 - Code for DHCP option.
355 - Integer between 2 and 254.
356 returned: success
357 type: int
358 sample: 43
359 type:
360 description:
361 - Type for DHCP option.
362 - Choices are C(text), C(ip), C(hex), C(integer).
363 returned: success
364 type: str
365 sample: text
366 value:
367 description: Value for the DHCP option.
368 returned: success
369 type: str
370 sample: 192.0.1.2
371 '''
372
373 from ansible.module_utils.basic import AnsibleModule
374 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec
375 import json
376
377
378 def fixed_ip_factory(meraki, data):
379 fixed_ips = dict()
380 for item in data:
381 fixed_ips[item['mac']] = {'ip': item['ip'], 'name': item['name']}
382 return fixed_ips
383
384
385 def get_vlans(meraki, net_id):
386 path = meraki.construct_path('get_all', net_id=net_id)
387 return meraki.request(path, method='GET')
388
389
390 # TODO: Allow method to return actual item if True to reduce number of calls needed
391 def is_vlan_valid(meraki, net_id, vlan_id):
392 vlans = get_vlans(meraki, net_id)
393 for vlan in vlans:
394 if vlan_id == vlan['id']:
395 return True
396 return False
397
398
399 def construct_payload(meraki):
400 payload = {'id': meraki.params['vlan_id'],
401 'name': meraki.params['name'],
402 'subnet': meraki.params['subnet'],
403 'applianceIp': meraki.params['appliance_ip'],
404 }
405 if meraki.params['dns_nameservers']:
406 if meraki.params['dns_nameservers'] not in ('opendns', 'google_dns', 'upstream_dns'):
407 payload['dnsNameservers'] = format_dns(meraki.params['dns_nameservers'])
408 else:
409 payload['dnsNameservers'] = meraki.params['dns_nameservers']
410 if meraki.params['fixed_ip_assignments']:
411 payload['fixedIpAssignments'] = fixed_ip_factory(meraki, meraki.params['fixed_ip_assignments'])
412 if meraki.params['reserved_ip_range']:
413 payload['reservedIpRanges'] = meraki.params['reserved_ip_range']
414 if meraki.params['vpn_nat_subnet']:
415 payload['vpnNatSubnet'] = meraki.params['vpn_nat_subnet']
416 if meraki.params['dhcp_handling']:
417 payload['dhcpHandling'] = normalize_dhcp_handling(meraki.params['dhcp_handling'])
418 if meraki.params['dhcp_relay_server_ips']:
419 payload['dhcpRelayServerIps'] = meraki.params['dhcp_relay_server_ips']
420 if meraki.params['dhcp_lease_time']:
421 payload['dhcpLeaseTime'] = meraki.params['dhcp_lease_time']
422 if meraki.params['dhcp_boot_options_enabled']:
423 payload['dhcpBootOptionsEnabled'] = meraki.params['dhcp_boot_options_enabled']
424 if meraki.params['dhcp_boot_next_server']:
425 payload['dhcpBootNextServer'] = meraki.params['dhcp_boot_next_server']
426 if meraki.params['dhcp_boot_filename']:
427 payload['dhcpBootFilename'] = meraki.params['dhcp_boot_filename']
428 if meraki.params['dhcp_options']:
429 payload['dhcpOptions'] = meraki.params['dhcp_options']
430 # if meraki.params['dhcp_handling']:
431 # meraki.fail_json(payload)
432
433 return payload
434
435
436 def format_dns(nameservers):
437 return nameservers.replace(';', '\n')
438
439
440 def normalize_dhcp_handling(parameter):
441 if parameter == 'none':
442 return 'Do not respond to DHCP requests'
443 elif parameter == 'server':
444 return 'Run a DHCP server'
445 elif parameter == 'relay':
446 return 'Relay DHCP to another server'
447
448
449 def main():
450 # define the available arguments/parameters that a user can pass to
451 # the module
452
453 fixed_ip_arg_spec = dict(mac=dict(type='str'),
454 ip=dict(type='str'),
455 name=dict(type='str'),
456 )
457
458 reserved_ip_arg_spec = dict(start=dict(type='str'),
459 end=dict(type='str'),
460 comment=dict(type='str'),
461 )
462
463 dhcp_options_arg_spec = dict(code=dict(type='int'),
464 type=dict(type='str', choices=['text', 'ip', 'hex', 'integer']),
465 value=dict(type='str'),
466 )
467
468 argument_spec = meraki_argument_spec()
469 argument_spec.update(state=dict(type='str', choices=['absent', 'present', 'query'], default='query'),
470 net_name=dict(type='str', aliases=['network']),
471 net_id=dict(type='str'),
472 vlan_id=dict(type='int'),
473 name=dict(type='str', aliases=['vlan_name']),
474 subnet=dict(type='str'),
475 appliance_ip=dict(type='str'),
476 fixed_ip_assignments=dict(type='list', default=None, elements='dict', options=fixed_ip_arg_spec),
477 reserved_ip_range=dict(type='list', default=None, elements='dict', options=reserved_ip_arg_spec),
478 vpn_nat_subnet=dict(type='str'),
479 dns_nameservers=dict(type='str'),
480 dhcp_handling=dict(type='str', choices=['Run a DHCP server',
481 'Relay DHCP to another server',
482 'Do not respond to DHCP requests',
483 'none',
484 'server',
485 'relay'],
486 ),
487 dhcp_relay_server_ips=dict(type='list', default=None, elements='str'),
488 dhcp_lease_time=dict(type='str', choices=['30 minutes',
489 '1 hour',
490 '4 hours',
491 '12 hours',
492 '1 day',
493 '1 week']),
494 dhcp_boot_options_enabled=dict(type='bool'),
495 dhcp_boot_next_server=dict(type='str'),
496 dhcp_boot_filename=dict(type='str'),
497 dhcp_options=dict(type='list', default=None, elements='dict', options=dhcp_options_arg_spec),
498 )
499
500 # the AnsibleModule object will be our abstraction working with Ansible
501 # this includes instantiation, a couple of common attr would be the
502 # args/params passed to the execution, as well as if the module
503 # supports check mode
504 module = AnsibleModule(argument_spec=argument_spec,
505 supports_check_mode=True,
506 )
507 meraki = MerakiModule(module, function='vlan')
508
509 meraki.params['follow_redirects'] = 'all'
510
511 query_urls = {'vlan': '/networks/{net_id}/appliance/vlans'}
512 query_url = {'vlan': '/networks/{net_id}/appliance/vlans/{vlan_id}'}
513 create_url = {'vlan': '/networks/{net_id}/appliance/vlans'}
514 update_url = {'vlan': '/networks/{net_id}/appliance/vlans/'}
515 delete_url = {'vlan': '/networks/{net_id}/appliance/vlans/'}
516
517 meraki.url_catalog['get_all'].update(query_urls)
518 meraki.url_catalog['get_one'].update(query_url)
519 meraki.url_catalog['create'] = create_url
520 meraki.url_catalog['update'] = update_url
521 meraki.url_catalog['delete'] = delete_url
522
523 payload = None
524
525 org_id = meraki.params['org_id']
526 if org_id is None:
527 org_id = meraki.get_org_id(meraki.params['org_name'])
528 net_id = meraki.params['net_id']
529 if net_id is None:
530 nets = meraki.get_nets(org_id=org_id)
531 net_id = meraki.get_net_id(net_name=meraki.params['net_name'], data=nets)
532
533 if meraki.params['state'] == 'query':
534 if not meraki.params['vlan_id']:
535 meraki.result['data'] = get_vlans(meraki, net_id)
536 else:
537 path = meraki.construct_path('get_one', net_id=net_id, custom={'vlan_id': meraki.params['vlan_id']})
538 response = meraki.request(path, method='GET')
539 meraki.result['data'] = response
540 elif meraki.params['state'] == 'present':
541 payload = construct_payload(meraki)
542 if is_vlan_valid(meraki, net_id, meraki.params['vlan_id']) is False: # Create new VLAN
543 if meraki.module.check_mode is True:
544 meraki.result['data'] = payload
545 meraki.result['changed'] = True
546 meraki.exit_json(**meraki.result)
547 path = meraki.construct_path('create', net_id=net_id)
548 response = meraki.request(path, method='POST', payload=json.dumps(payload))
549 meraki.result['changed'] = True
550 meraki.result['data'] = response
551 else: # Update existing VLAN
552 path = meraki.construct_path('get_one', net_id=net_id, custom={'vlan_id': meraki.params['vlan_id']})
553 original = meraki.request(path, method='GET')
554 ignored = ['networkId']
555 if meraki.is_update_required(original, payload, optional_ignore=ignored):
556 meraki.generate_diff(original, payload)
557 if meraki.module.check_mode is True:
558 original.update(payload)
559 meraki.result['changed'] = True
560 meraki.result['data'] = original
561 meraki.exit_json(**meraki.result)
562 path = meraki.construct_path('update', net_id=net_id) + str(meraki.params['vlan_id'])
563 response = meraki.request(path, method='PUT', payload=json.dumps(payload))
564 meraki.result['changed'] = True
565 meraki.result['data'] = response
566 meraki.generate_diff(original, response)
567 else:
568 if meraki.module.check_mode is True:
569 meraki.result['data'] = original
570 meraki.exit_json(**meraki.result)
571 meraki.result['data'] = original
572 elif meraki.params['state'] == 'absent':
573 if is_vlan_valid(meraki, net_id, meraki.params['vlan_id']):
574 if meraki.module.check_mode is True:
575 meraki.result['data'] = {}
576 meraki.result['changed'] = True
577 meraki.exit_json(**meraki.result)
578 path = meraki.construct_path('delete', net_id=net_id) + str(meraki.params['vlan_id'])
579 response = meraki.request(path, 'DELETE')
580 meraki.result['changed'] = True
581 meraki.result['data'] = response
582
583 # in the event of a successful module execution, you will want to
584 # simple AnsibleModule.exit_json(), passing the key/value results
585 meraki.exit_json(**meraki.result)
586
587
588 if __name__ == '__main__':
589 main()