Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 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 __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_nat
19 short_description: Manage NAT rules in Meraki cloud
20 description:
21 - Allows for creation, management, and visibility of NAT rules (1:1, 1:many, port forwarding) within Meraki.
22
23 deprecated:
24 removed_in: '3.0.0'
25 why: Updated modules released with increased functionality
26 alternative: cisco.meraki.networks_appliance_firewall_one_to_many_nat_rules
27 options:
28 state:
29 description:
30 - Create or modify an organization.
31 choices: [present, query]
32 default: present
33 type: str
34 net_name:
35 description:
36 - Name of a network.
37 aliases: [name, network]
38 type: str
39 net_id:
40 description:
41 - ID number of a network.
42 type: str
43 org_id:
44 description:
45 - ID of organization associated to a network.
46 type: str
47 subset:
48 description:
49 - Specifies which NAT components to query.
50 choices: ['1:1', '1:many', all, port_forwarding]
51 default: all
52 type: list
53 elements: str
54 one_to_one:
55 description:
56 - List of 1:1 NAT rules.
57 type: list
58 elements: dict
59 suboptions:
60 name:
61 description:
62 - A descriptive name for the rule.
63 type: str
64 public_ip:
65 description:
66 - The IP address that will be used to access the internal resource from the WAN.
67 type: str
68 lan_ip:
69 description:
70 - The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN.
71 type: str
72 uplink:
73 description:
74 - The physical WAN interface on which the traffic will arrive.
75 choices: [both, internet1, internet2]
76 type: str
77 allowed_inbound:
78 description:
79 - The ports this mapping will provide access on, and the remote IPs that will be allowed access to the resource.
80 type: list
81 elements: dict
82 suboptions:
83 protocol:
84 description:
85 - Protocol to apply NAT rule to.
86 choices: [any, icmp-ping, tcp, udp]
87 type: str
88 default: any
89 destination_ports:
90 description:
91 - List of ports or port ranges that will be forwarded to the host on the LAN.
92 type: list
93 elements: str
94 allowed_ips:
95 description:
96 - ranges of WAN IP addresses that are allowed to make inbound connections on the specified ports or port ranges, or 'any'.
97 type: list
98 elements: str
99 one_to_many:
100 description:
101 - List of 1:many NAT rules.
102 type: list
103 elements: dict
104 suboptions:
105 public_ip:
106 description:
107 - The IP address that will be used to access the internal resource from the WAN.
108 type: str
109 uplink:
110 description:
111 - The physical WAN interface on which the traffic will arrive.
112 choices: [both, internet1, internet2]
113 type: str
114 port_rules:
115 description:
116 - List of associated port rules.
117 type: list
118 elements: dict
119 suboptions:
120 name:
121 description:
122 - A description of the rule.
123 type: str
124 protocol:
125 description:
126 - Protocol to apply NAT rule to.
127 choices: [tcp, udp]
128 type: str
129 public_port:
130 description:
131 - Destination port of the traffic that is arriving on the WAN.
132 type: str
133 local_ip:
134 description:
135 - Local IP address to which traffic will be forwarded.
136 type: str
137 local_port:
138 description:
139 - Destination port of the forwarded traffic that will be sent from the MX to the specified host on the LAN.
140 - If you simply wish to forward the traffic without translating the port, this should be the same as the Public port.
141 type: str
142 allowed_ips:
143 description:
144 - Remote IP addresses or ranges that are permitted to access the internal resource via this port forwarding rule, or 'any'.
145 type: list
146 elements: str
147 port_forwarding:
148 description:
149 - List of port forwarding rules.
150 type: list
151 elements: dict
152 suboptions:
153 name:
154 description:
155 - A descriptive name for the rule.
156 type: str
157 lan_ip:
158 description:
159 - The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN.
160 type: str
161 uplink:
162 description:
163 - The physical WAN interface on which the traffic will arrive.
164 choices: [both, internet1, internet2]
165 type: str
166 public_port:
167 description:
168 - A port or port ranges that will be forwarded to the host on the LAN.
169 type: int
170 local_port:
171 description:
172 - A port or port ranges that will receive the forwarded traffic from the WAN.
173 type: int
174 allowed_ips:
175 description:
176 - List of ranges of WAN IP addresses that are allowed to make inbound connections on the specified ports or port ranges (or any).
177 type: list
178 elements: str
179 protocol:
180 description:
181 - Protocol to forward traffic for.
182 choices: [tcp, udp]
183 type: str
184
185 author:
186 - Kevin Breit (@kbreit)
187 extends_documentation_fragment: cisco.meraki.meraki
188 '''
189
190 EXAMPLES = r'''
191 - name: Query all NAT rules
192 meraki_nat:
193 auth_key: abc123
194 org_name: YourOrg
195 net_name: YourNet
196 state: query
197 subset: all
198 delegate_to: localhost
199
200 - name: Query 1:1 NAT rules
201 meraki_nat:
202 auth_key: abc123
203 org_name: YourOrg
204 net_name: YourNet
205 state: query
206 subset: '1:1'
207 delegate_to: localhost
208
209 - name: Create 1:1 rule
210 meraki_nat:
211 auth_key: abc123
212 org_name: YourOrg
213 net_name: YourNet
214 state: present
215 one_to_one:
216 - name: Service behind NAT
217 public_ip: 1.2.1.2
218 lan_ip: 192.168.128.1
219 uplink: internet1
220 allowed_inbound:
221 - protocol: tcp
222 destination_ports:
223 - 80
224 allowed_ips:
225 - 10.10.10.10
226 delegate_to: localhost
227
228 - name: Create 1:many rule
229 meraki_nat:
230 auth_key: abc123
231 org_name: YourOrg
232 net_name: YourNet
233 state: present
234 one_to_many:
235 - public_ip: 1.1.1.1
236 uplink: internet1
237 port_rules:
238 - name: Test rule
239 protocol: tcp
240 public_port: 10
241 local_ip: 192.168.128.1
242 local_port: 11
243 allowed_ips:
244 - any
245 delegate_to: localhost
246
247 - name: Create port forwarding rule
248 meraki_nat:
249 auth_key: abc123
250 org_name: YourOrg
251 net_name: YourNet
252 state: present
253 port_forwarding:
254 - name: Test map
255 lan_ip: 192.168.128.1
256 uplink: both
257 protocol: tcp
258 allowed_ips:
259 - 1.1.1.1
260 public_port: 10
261 local_port: 11
262 delegate_to: localhost
263 '''
264
265 RETURN = r'''
266 data:
267 description: Information about the created or manipulated object.
268 returned: success
269 type: complex
270 contains:
271 one_to_one:
272 description: Information about 1:1 NAT object.
273 returned: success, when 1:1 NAT object is in task
274 type: complex
275 contains:
276 rules:
277 description: List of 1:1 NAT rules.
278 returned: success, when 1:1 NAT object is in task
279 type: complex
280 contains:
281 name:
282 description: Name of NAT object.
283 returned: success, when 1:1 NAT object is in task
284 type: str
285 example: Web server behind NAT
286 lanIp:
287 description: Local IP address to be mapped.
288 returned: success, when 1:1 NAT object is in task
289 type: str
290 example: 192.168.128.22
291 publicIp:
292 description: Public IP address to be mapped.
293 returned: success, when 1:1 NAT object is in task
294 type: str
295 example: 148.2.5.100
296 uplink:
297 description: Internet port where rule is applied.
298 returned: success, when 1:1 NAT object is in task
299 type: str
300 example: internet1
301 allowedInbound:
302 description: List of inbound forwarding rules.
303 returned: success, when 1:1 NAT object is in task
304 type: complex
305 contains:
306 protocol:
307 description: Protocol to apply NAT rule to.
308 returned: success, when 1:1 NAT object is in task
309 type: str
310 example: tcp
311 destinationPorts:
312 description: Ports to apply NAT rule to.
313 returned: success, when 1:1 NAT object is in task
314 type: str
315 example: 80
316 allowedIps:
317 description: List of IP addresses to be forwarded.
318 returned: success, when 1:1 NAT object is in task
319 type: list
320 example: 10.80.100.0/24
321 one_to_many:
322 description: Information about 1:many NAT object.
323 returned: success, when 1:many NAT object is in task
324 type: complex
325 contains:
326 rules:
327 description: List of 1:many NAT rules.
328 returned: success, when 1:many NAT object is in task
329 type: complex
330 contains:
331 publicIp:
332 description: Public IP address to be mapped.
333 returned: success, when 1:many NAT object is in task
334 type: str
335 example: 148.2.5.100
336 uplink:
337 description: Internet port where rule is applied.
338 returned: success, when 1:many NAT object is in task
339 type: str
340 example: internet1
341 portRules:
342 description: List of NAT port rules.
343 returned: success, when 1:many NAT object is in task
344 type: complex
345 contains:
346 name:
347 description: Name of NAT object.
348 returned: success, when 1:many NAT object is in task
349 type: str
350 example: Web server behind NAT
351 protocol:
352 description: Protocol to apply NAT rule to.
353 returned: success, when 1:1 NAT object is in task
354 type: str
355 example: tcp
356 publicPort:
357 description: Destination port of the traffic that is arriving on WAN.
358 returned: success, when 1:1 NAT object is in task
359 type: int
360 example: 9443
361 localIp:
362 description: Local IP address traffic will be forwarded.
363 returned: success, when 1:1 NAT object is in task
364 type: str
365 example: 192.0.2.10
366 localPort:
367 description: Destination port to be forwarded to.
368 returned: success, when 1:1 NAT object is in task
369 type: int
370 example: 443
371 allowedIps:
372 description: List of IP addresses to be forwarded.
373 returned: success, when 1:1 NAT object is in task
374 type: list
375 example: 10.80.100.0/24
376 port_forwarding:
377 description: Information about port forwarding rules.
378 returned: success, when port forwarding is in task
379 type: complex
380 contains:
381 rules:
382 description: List of port forwarding rules.
383 returned: success, when port forwarding is in task
384 type: complex
385 contains:
386 lanIp:
387 description: Local IP address to be mapped.
388 returned: success, when port forwarding is in task
389 type: str
390 example: 192.168.128.22
391 allowedIps:
392 description: List of IP addresses to be forwarded.
393 returned: success, when port forwarding is in task
394 type: list
395 example: 10.80.100.0/24
396 name:
397 description: Name of NAT object.
398 returned: success, when port forwarding is in task
399 type: str
400 example: Web server behind NAT
401 protocol:
402 description: Protocol to apply NAT rule to.
403 returned: success, when port forwarding is in task
404 type: str
405 example: tcp
406 publicPort:
407 description: Destination port of the traffic that is arriving on WAN.
408 returned: success, when port forwarding is in task
409 type: int
410 example: 9443
411 localPort:
412 description: Destination port to be forwarded to.
413 returned: success, when port forwarding is in task
414 type: int
415 example: 443
416 uplink:
417 description: Internet port where rule is applied.
418 returned: success, when port forwarding is in task
419 type: str
420 example: internet1
421 '''
422
423 from ansible.module_utils.basic import AnsibleModule, json
424 from ansible.module_utils.common.dict_transformations import recursive_diff
425 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec
426
427 key_map = {'name': 'name',
428 'public_ip': 'publicIp',
429 'lan_ip': 'lanIp',
430 'uplink': 'uplink',
431 'allowed_inbound': 'allowedInbound',
432 'protocol': 'protocol',
433 'destination_ports': 'destinationPorts',
434 'allowed_ips': 'allowedIps',
435 'port_rules': 'portRules',
436 'public_port': 'publicPort',
437 'local_ip': 'localIp',
438 'local_port': 'localPort',
439 }
440
441
442 def construct_payload(params):
443 if isinstance(params, list):
444 items = []
445 for item in params:
446 items.append(construct_payload(item))
447 return items
448 elif isinstance(params, dict):
449 info = {}
450 for param in params:
451 info[key_map[param]] = construct_payload(params[param])
452 return info
453 elif isinstance(params, str) or isinstance(params, int):
454 return params
455
456
457 def list_int_to_str(data):
458 return [str(item) for item in data]
459
460
461 def main():
462
463 # define the available arguments/parameters that a user can pass to
464 # the module
465
466 one_to_one_allowed_inbound_spec = dict(protocol=dict(type='str', choices=['tcp', 'udp', 'icmp-ping', 'any'], default='any'),
467 destination_ports=dict(type='list', elements='str'),
468 allowed_ips=dict(type='list', elements='str'),
469 )
470
471 one_to_many_port_inbound_spec = dict(protocol=dict(type='str', choices=['tcp', 'udp']),
472 name=dict(type='str'),
473 local_ip=dict(type='str'),
474 local_port=dict(type='str'),
475 allowed_ips=dict(type='list', elements='str'),
476 public_port=dict(type='str'),
477 )
478
479 one_to_one_spec = dict(name=dict(type='str'),
480 public_ip=dict(type='str'),
481 lan_ip=dict(type='str'),
482 uplink=dict(type='str', choices=['internet1', 'internet2', 'both']),
483 allowed_inbound=dict(type='list', elements='dict', options=one_to_one_allowed_inbound_spec),
484 )
485
486 one_to_many_spec = dict(public_ip=dict(type='str'),
487 uplink=dict(type='str', choices=['internet1', 'internet2', 'both']),
488 port_rules=dict(type='list', elements='dict', options=one_to_many_port_inbound_spec),
489 )
490
491 port_forwarding_spec = dict(name=dict(type='str'),
492 lan_ip=dict(type='str'),
493 uplink=dict(type='str', choices=['internet1', 'internet2', 'both']),
494 protocol=dict(type='str', choices=['tcp', 'udp']),
495 public_port=dict(type='int'),
496 local_port=dict(type='int'),
497 allowed_ips=dict(type='list', elements='str'),
498 )
499
500 argument_spec = meraki_argument_spec()
501 argument_spec.update(
502 net_id=dict(type='str'),
503 net_name=dict(type='str', aliases=['name', 'network']),
504 state=dict(type='str', choices=['present', 'query'], default='present'),
505 subset=dict(type='list', elements='str', choices=['1:1', '1:many', 'all', 'port_forwarding'], default='all'),
506 one_to_one=dict(type='list', elements='dict', options=one_to_one_spec),
507 one_to_many=dict(type='list', elements='dict', options=one_to_many_spec),
508 port_forwarding=dict(type='list', elements='dict', options=port_forwarding_spec),
509 )
510
511 # the AnsibleModule object will be our abstraction working with Ansible
512 # this includes instantiation, a couple of common attr would be the
513 # args/params passed to the execution, as well as if the module
514 # supports check mode
515 module = AnsibleModule(argument_spec=argument_spec,
516 supports_check_mode=True,
517 )
518
519 meraki = MerakiModule(module, function='nat')
520 module.params['follow_redirects'] = 'all'
521
522 one_to_one_payload = None
523 one_to_many_payload = None
524 port_forwarding_payload = None
525 if meraki.params['state'] == 'present':
526 if meraki.params['one_to_one'] is not None:
527 rules = []
528 for i in meraki.params['one_to_one']:
529 data = {'name': i['name'],
530 'publicIp': i['public_ip'],
531 'uplink': i['uplink'],
532 'lanIp': i['lan_ip'],
533 'allowedInbound': construct_payload(i['allowed_inbound'])
534 }
535 for inbound in data['allowedInbound']:
536 inbound['destinationPorts'] = list_int_to_str(inbound['destinationPorts'])
537 rules.append(data)
538 one_to_one_payload = {'rules': rules}
539 if meraki.params['one_to_many'] is not None:
540 rules = []
541 for i in meraki.params['one_to_many']:
542 data = {'publicIp': i['public_ip'],
543 'uplink': i['uplink'],
544 }
545 port_rules = []
546 for port_rule in i['port_rules']:
547 rule = {'name': port_rule['name'],
548 'protocol': port_rule['protocol'],
549 'publicPort': str(port_rule['public_port']),
550 'localIp': port_rule['local_ip'],
551 'localPort': str(port_rule['local_port']),
552 'allowedIps': port_rule['allowed_ips'],
553 }
554 port_rules.append(rule)
555 data['portRules'] = port_rules
556 rules.append(data)
557 one_to_many_payload = {'rules': rules}
558 if meraki.params['port_forwarding'] is not None:
559 port_forwarding_payload = {'rules': construct_payload(meraki.params['port_forwarding'])}
560 for rule in port_forwarding_payload['rules']:
561 rule['localPort'] = str(rule['localPort'])
562 rule['publicPort'] = str(rule['publicPort'])
563
564 onetomany_urls = {'nat': '/networks/{net_id}/appliance/firewall/oneToManyNatRules'}
565 onetoone_urls = {'nat': '/networks/{net_id}/appliance/firewall/oneToOneNatRules'}
566 port_forwarding_urls = {'nat': '/networks/{net_id}/appliance/firewall/portForwardingRules'}
567 meraki.url_catalog['1:many'] = onetomany_urls
568 meraki.url_catalog['1:1'] = onetoone_urls
569 meraki.url_catalog['port_forwarding'] = port_forwarding_urls
570
571 if meraki.params['net_name'] and meraki.params['net_id']:
572 meraki.fail_json(msg='net_name and net_id are mutually exclusive')
573
574 org_id = meraki.params['org_id']
575 if not org_id:
576 org_id = meraki.get_org_id(meraki.params['org_name'])
577 net_id = meraki.params['net_id']
578 if net_id is None:
579 nets = meraki.get_nets(org_id=org_id)
580 net_id = meraki.get_net_id(org_id, meraki.params['net_name'], data=nets)
581
582 if meraki.params['state'] == 'query':
583 if meraki.params['subset'][0] == 'all':
584 path = meraki.construct_path('1:many', net_id=net_id)
585 data = {'1:many': meraki.request(path, method='GET')}
586 path = meraki.construct_path('1:1', net_id=net_id)
587 data['1:1'] = meraki.request(path, method='GET')
588 path = meraki.construct_path('port_forwarding', net_id=net_id)
589 data['port_forwarding'] = meraki.request(path, method='GET')
590 meraki.result['data'] = data
591 else:
592 for subset in meraki.params['subset']:
593 path = meraki.construct_path(subset, net_id=net_id)
594 data = {subset: meraki.request(path, method='GET')}
595 try:
596 meraki.result['data'][subset] = data
597 except KeyError:
598 meraki.result['data'] = {subset: data}
599 elif meraki.params['state'] == 'present':
600 meraki.result['data'] = dict()
601 if one_to_one_payload is not None:
602 path = meraki.construct_path('1:1', net_id=net_id)
603 current = meraki.request(path, method='GET')
604 if meraki.is_update_required(current, one_to_one_payload):
605 if meraki.module.check_mode is True:
606 diff = recursive_diff(current, one_to_one_payload)
607 current.update(one_to_one_payload)
608 if 'diff' not in meraki.result:
609 meraki.result['diff'] = {'before': {}, 'after': {}}
610 meraki.result['diff']['before'].update({'one_to_one': diff[0]})
611 meraki.result['diff']['after'].update({'one_to_one': diff[1]})
612 meraki.result['data'] = {'one_to_one': current}
613 meraki.result['changed'] = True
614 else:
615 r = meraki.request(path, method='PUT', payload=json.dumps(one_to_one_payload))
616 if meraki.status == 200:
617 diff = recursive_diff(current, one_to_one_payload)
618 if 'diff' not in meraki.result:
619 meraki.result['diff'] = {'before': {}, 'after': {}}
620 meraki.result['diff']['before'].update({'one_to_one': diff[0]})
621 meraki.result['diff']['after'].update({'one_to_one': diff[1]})
622 meraki.result['data'] = {'one_to_one': r}
623 meraki.result['changed'] = True
624 else:
625 meraki.result['data']['one_to_one'] = current
626 if one_to_many_payload is not None:
627 path = meraki.construct_path('1:many', net_id=net_id)
628 current = meraki.request(path, method='GET')
629 if meraki.is_update_required(current, one_to_many_payload):
630 if meraki.module.check_mode is True:
631 diff = recursive_diff(current, one_to_many_payload)
632 current.update(one_to_many_payload)
633 if 'diff' not in meraki.result:
634 meraki.result['diff'] = {'before': {}, 'after': {}}
635 meraki.result['diff']['before'].update({'one_to_many': diff[0]})
636 meraki.result['diff']['after'].update({'one_to_many': diff[1]})
637 meraki.result['data']['one_to_many'] = current
638 meraki.result['changed'] = True
639 else:
640 r = meraki.request(path, method='PUT', payload=json.dumps(one_to_many_payload))
641 if meraki.status == 200:
642 diff = recursive_diff(current, one_to_many_payload)
643 if 'diff' not in meraki.result:
644 meraki.result['diff'] = {'before': {}, 'after': {}}
645 meraki.result['diff']['before'].update({'one_to_many': diff[0]})
646 meraki.result['diff']['after'].update({'one_to_many': diff[1]})
647 meraki.result['data'].update({'one_to_many': r})
648 meraki.result['changed'] = True
649 else:
650 meraki.result['data']['one_to_many'] = current
651 if port_forwarding_payload is not None:
652 path = meraki.construct_path('port_forwarding', net_id=net_id)
653 current = meraki.request(path, method='GET')
654 if meraki.is_update_required(current, port_forwarding_payload):
655 if meraki.module.check_mode is True:
656 diff = recursive_diff(current, port_forwarding_payload)
657 current.update(port_forwarding_payload)
658 if 'diff' not in meraki.result:
659 meraki.result['diff'] = {'before': {}, 'after': {}}
660 meraki.result['diff']['before'].update({'port_forwarding': diff[0]})
661 meraki.result['diff']['after'].update({'port_forwarding': diff[1]})
662 meraki.result['data']['port_forwarding'] = current
663 meraki.result['changed'] = True
664 else:
665 r = meraki.request(path, method='PUT', payload=json.dumps(port_forwarding_payload))
666 if meraki.status == 200:
667 if 'diff' not in meraki.result:
668 meraki.result['diff'] = {'before': {}, 'after': {}}
669 diff = recursive_diff(current, port_forwarding_payload)
670 meraki.result['diff']['before'].update({'port_forwarding': diff[0]})
671 meraki.result['diff']['after'].update({'port_forwarding': diff[1]})
672 meraki.result['data'].update({'port_forwarding': r})
673 meraki.result['changed'] = True
674 else:
675 meraki.result['data']['port_forwarding'] = current
676
677 # in the event of a successful module execution, you will want to
678 # simple AnsibleModule.exit_json(), passing the key/value results
679 meraki.exit_json(**meraki.result)
680
681
682 if __name__ == '__main__':
683 main()