Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_loadbalancer.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2016, Thomas Stringer <[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
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_loadbalancer
14
15 version_added: "0.1.2"
16
17 short_description: Manage Azure load balancers
18
19 description:
20 - Create, update and delete Azure load balancers.
21
22 options:
23 resource_group:
24 description:
25 - Name of a resource group where the load balancer exists or will be created.
26 required: true
27 type: str
28 name:
29 description:
30 - Name of the load balancer.
31 required: true
32 type: str
33 state:
34 description:
35 - Assert the state of the load balancer. Use C(present) to create/update a load balancer, or C(absent) to delete one.
36 default: present
37 type: str
38 choices:
39 - absent
40 - present
41 location:
42 description:
43 - Valid Azure location. Defaults to location of the resource group.
44 type: str
45 sku:
46 description:
47 - The load balancer SKU.
48 type: str
49 choices:
50 - Basic
51 - Standard
52 frontend_ip_configurations:
53 description:
54 - List of frontend IPs to be used.
55 type: list
56 elements: dict
57 suboptions:
58 name:
59 description:
60 - Name of the frontend ip configuration.
61 type: str
62 required: True
63 public_ip_address:
64 description:
65 - Name of an existing public IP address object in the current resource group to associate with the security group.
66 type: str
67 private_ip_address:
68 description:
69 - The reference of the Public IP resource.
70 type: str
71 private_ip_allocation_method:
72 description:
73 - The Private IP allocation method.
74 type: str
75 choices:
76 - Static
77 - Dynamic
78 subnet:
79 description:
80 - The reference of the subnet resource.
81 - Should be an existing subnet's resource id.
82 type: str
83 zones:
84 description:
85 - list of availability zones denoting the IP allocated for the resource needs to come from.
86 - This must be specified I(sku=Standard) and I(subnet) when setting zones.
87 type: list
88 elements: str
89 backend_address_pools:
90 description:
91 - List of backend address pools.
92 type: list
93 elements: dict
94 suboptions:
95 name:
96 description:
97 - Name of the backend address pool.
98 required: True
99 type: str
100 probes:
101 description:
102 - List of probe definitions used to check endpoint health.
103 type: list
104 elements: dict
105 suboptions:
106 name:
107 description:
108 - Name of the probe.
109 type: str
110 required: True
111 port:
112 description:
113 - Probe port for communicating the probe. Possible values range from 1 to 65535, inclusive.
114 type: int
115 required: True
116 protocol:
117 description:
118 - The protocol of the end point to be probed.
119 - If C(Tcp) is specified, a received ACK is required for the probe to be successful.
120 - If C(Http) or C(Https) is specified, a 200 OK response from the specified URL is required for the probe to be successful.
121 type: str
122 choices:
123 - Tcp
124 - Http
125 - Https
126 interval:
127 description:
128 - The interval, in seconds, for how frequently to probe the endpoint for health status.
129 - Slightly less than half the allocated timeout period, which allows two full probes before taking the instance out of rotation.
130 - The default value is C(15), the minimum value is C(5).
131 type: int
132 default: 15
133 fail_count:
134 description:
135 - The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint.
136 - This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure.
137 default: 3
138 type: int
139 aliases:
140 - number_of_probes
141 request_path:
142 description:
143 - The URI used for requesting health status from the VM.
144 - Path is required if I(protocol=Http) or I(protocol=Https). Otherwise, it is not allowed.
145 type: str
146 inbound_nat_pools:
147 description:
148 - Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer.
149 - Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range.
150 - Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules.
151 - Inbound NAT pools are referenced from virtual machine scale sets.
152 - NICs that are associated with individual virtual machines cannot reference an inbound NAT pool.
153 - They have to reference individual inbound NAT rules.
154 type: list
155 elements: dict
156 suboptions:
157 name:
158 description:
159 - Name of the inbound NAT pool.
160 type: str
161 required: True
162 frontend_ip_configuration_name:
163 description:
164 - A reference to frontend IP addresses.
165 required: True
166 type: str
167 protocol:
168 description:
169 - IP protocol for the NAT pool.
170 type: str
171 choices:
172 - Tcp
173 - Udp
174 - All
175 frontend_port_range_start:
176 description:
177 - The first port in the range of external ports that will be used to provide inbound NAT to NICs associated with the load balancer.
178 - Acceptable values range between 1 and 65534.
179 type: int
180 required: True
181 frontend_port_range_end:
182 description:
183 - The last port in the range of external ports that will be used to provide inbound NAT to NICs associated with the load balancer.
184 - Acceptable values range between 1 and 65535.
185 type: int
186 required: True
187 backend_port:
188 description:
189 - The port used for internal connections on the endpoint.
190 - Acceptable values are between 1 and 65535.
191 type: int
192 required: true
193 load_balancing_rules:
194 description:
195 - Object collection representing the load balancing rules Gets the provisioning.
196 type: list
197 elements: dict
198 suboptions:
199 name:
200 description:
201 - Name of the load balancing rule.
202 type: str
203 required: True
204 frontend_ip_configuration:
205 description:
206 - A reference to frontend IP addresses.
207 type: str
208 required: True
209 backend_address_pool:
210 description:
211 - A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs.
212 required: True
213 type: str
214 probe:
215 description:
216 - The name of the load balancer probe this rule should use for health checks.
217 required: True
218 type: str
219 protocol:
220 description:
221 - IP protocol for the load balancing rule.
222 type: str
223 choices:
224 - Tcp
225 - Udp
226 - All
227 load_distribution:
228 description:
229 - The session persistence policy for this rule; C(Default) is no persistence.
230 type: str
231 choices:
232 - Default
233 - SourceIP
234 - SourceIPProtocol
235 default: Default
236 frontend_port:
237 description:
238 - The port for the external endpoint.
239 - Frontend port numbers must be unique across all rules within the load balancer.
240 - Acceptable values are between 0 and 65534.
241 - Note that value 0 enables "Any Port".
242 type: int
243 required: true
244 backend_port:
245 description:
246 - The port used for internal connections on the endpoint.
247 - Acceptable values are between 0 and 65535.
248 - Note that value 0 enables "Any Port".
249 type: int
250 idle_timeout:
251 description:
252 - The timeout for the TCP idle connection.
253 - The value can be set between 4 and 30 minutes.
254 - The default value is C(4) minutes.
255 - This element is only used when the protocol is set to TCP.
256 type: int
257 default: 4
258 enable_floating_ip:
259 description:
260 - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group.
261 type: bool
262 enable_tcp_reset:
263 description:
264 - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
265 - This element is only used when the protocol is set to TCP.
266 type: bool
267 disable_outbound_snat:
268 description:
269 - Configure outbound source network address translation (SNAT).
270 - The default behavior when omitted is equivalent to I(disable_outbound_snat=True).
271 - True is equivalent to "(Recommended) Use outbound rules to provide backend pool members access to the internet" in portal.
272 - False is equivalent to "Use default outbound access" in portal.
273 type: bool
274 default: False
275 inbound_nat_rules:
276 description:
277 - Collection of inbound NAT Rules used by a load balancer.
278 - Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool.
279 - Inbound NAT pools are referenced from virtual machine scale sets.
280 - NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool.
281 - They have to reference individual inbound NAT rules.
282 type: list
283 elements: dict
284 suboptions:
285 name:
286 description:
287 - name of the inbound nat rule.
288 type: str
289 required: True
290 frontend_ip_configuration:
291 description:
292 - A reference to frontend IP addresses.
293 type: str
294 required: True
295 protocol:
296 description:
297 - IP protocol for the inbound nat rule.
298 type: str
299 choices:
300 - Tcp
301 - Udp
302 - All
303 frontend_port:
304 description:
305 - The port for the external endpoint.
306 - Frontend port numbers must be unique across all rules within the load balancer.
307 - Acceptable values are between 0 and 65534.
308 - Note that value 0 enables "Any Port".
309 type: int
310 required: True
311 backend_port:
312 description:
313 - The port used for internal connections on the endpoint.
314 - Acceptable values are between 0 and 65535.
315 - Note that value 0 enables "Any Port".
316 type: int
317 required: true
318 idle_timeout:
319 description:
320 - The timeout for the TCP idle connection.
321 - The value can be set between 4 and 30 minutes.
322 - The default value is C(4) minutes.
323 - This element is only used when I(protocol=Tcp).
324 type: int
325 enable_floating_ip:
326 description:
327 - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group.
328 - This setting is required when using the SQL AlwaysOn Availability Groups in SQL server.
329 - This setting can't be changed after you create the endpoint.
330 type: bool
331 enable_tcp_reset:
332 description:
333 - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
334 - This element is only used when I(protocol=Tcp).
335 type: bool
336 outbound_rules:
337 description:
338 - The outbound rules.
339 type: list
340 elements: dict
341 version_added: '3.5.0'
342 suboptions:
343 name:
344 description:
345 - The name of the resource that is unique within the set of outbound rules used by the load balancer.
346 - This name can be used to access the resource.
347 type: str
348 required: True
349 allocated_outbound_ports:
350 description:
351 - The number of outbound ports to be used for NAT.
352 type: int
353 frontend_ip_configurations:
354 description:
355 - The Frontend IP addresses of the load balancer.
356 type: list
357 elements: str
358 backend_address_pool:
359 description:
360 - A reference to a pool of DIPs.
361 - Outbound traffic is randomly load balanced across IPs in the backend IPs.
362 type: str
363 protocol:
364 description:
365 - The protocol for the outbound rule in load balancer.
366 type: str
367 choices:
368 - Tcp
369 - Udp
370 - All
371 enable_tcp_reset:
372 description:
373 - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
374 - This element is only used when the protocol is set to C(Tcp).
375 type: bool
376 idle_timeout_in_minutes:
377 description:
378 - The timeout for the TCP idle connection.
379 type: int
380 extends_documentation_fragment:
381 - azure.azcollection.azure
382 - azure.azcollection.azure_tags
383
384 author:
385 - Thomas Stringer (@trstringer)
386 - Yuwei Zhou (@yuwzho)
387 '''
388
389 EXAMPLES = '''
390 - name: create load balancer
391 azure_rm_loadbalancer:
392 resource_group: myResourceGroup
393 name: testloadbalancer1
394 frontend_ip_configurations:
395 - name: frontendipconf0
396 public_ip_address: testpip
397 - name: frontendipconf1
398 public_ip_address: testpip1
399 backend_address_pools:
400 - name: backendaddrpool0
401 - name: backendaddrpool1
402 probes:
403 - name: prob0
404 port: 80
405 inbound_nat_pools:
406 - name: inboundnatpool0
407 frontend_ip_configuration_name: frontendipconf0
408 protocol: Tcp
409 frontend_port_range_start: 80
410 frontend_port_range_end: 81
411 backend_port: 8080
412 load_balancing_rules:
413 - name: lbrbalancingrule0
414 frontend_ip_configuration: frontendipconf0
415 backend_address_pool: backendaddrpool0
416 frontend_port: 80
417 backend_port: 80
418 probe: prob0
419 inbound_nat_rules:
420 - name: inboundnatrule0
421 backend_port: 8080
422 protocol: Tcp
423 frontend_port: 8080
424 frontend_ip_configuration: frontendipconf0
425 outbound_rules:
426 - name: outrule1
427 allocated_outbound_ports: 800
428 frontend_ip_configurations:
429 - frontendipconf1
430 backend_address_pool: backendaddrpool1
431 protocol: Tcp
432 enable_tcp_reset: true
433 idle_timeout_in_minutes: 4
434 '''
435
436 RETURN = '''
437 state:
438 description:
439 - Current state of the load balancer.
440 returned: always
441 type: dict
442 changed:
443 description:
444 - Whether or not the resource has changed.
445 returned: always
446 type: bool
447 '''
448
449 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import format_resource_id
450 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
451 from ansible.module_utils._text import to_native
452 try:
453 from azure.core.exceptions import ResourceNotFoundError
454 from azure.mgmt.core.tools import parse_resource_id
455 except ImportError:
456 # This is handled in azure_rm_common
457 pass
458
459
460 frontend_ip_configuration_spec = dict(
461 name=dict(
462 type='str',
463 required=True
464 ),
465 public_ip_address=dict(
466 type='str'
467 ),
468 private_ip_address=dict(
469 type='str'
470 ),
471 private_ip_allocation_method=dict(
472 type='str',
473 choices=['Static', 'Dynamic']
474 ),
475 subnet=dict(
476 type='str'
477 ),
478 zones=dict(
479 type='list',
480 elements='str'
481 )
482 )
483
484
485 backend_address_pool_spec = dict(
486 name=dict(
487 type='str',
488 required=True
489 )
490 )
491
492
493 probes_spec = dict(
494 name=dict(
495 type='str',
496 required=True
497 ),
498 port=dict(
499 type='int',
500 required=True
501 ),
502 protocol=dict(
503 type='str',
504 choices=['Tcp', 'Http', 'Https']
505 ),
506 interval=dict(
507 type='int',
508 default=15
509 ),
510 fail_count=dict(
511 type='int',
512 default=3,
513 aliases=['number_of_probes']
514 ),
515 request_path=dict(
516 type='str'
517 )
518 )
519
520
521 inbound_nat_pool_spec = dict(
522 name=dict(
523 type='str',
524 required=True
525 ),
526 frontend_ip_configuration_name=dict(
527 type='str',
528 required=True
529 ),
530 protocol=dict(
531 type='str',
532 choices=['Tcp', 'Udp', 'All']
533 ),
534 frontend_port_range_start=dict(
535 type='int',
536 required=True
537 ),
538 frontend_port_range_end=dict(
539 type='int',
540 required=True
541 ),
542 backend_port=dict(
543 type='int',
544 required=True
545 )
546 )
547
548
549 inbound_nat_rule_spec = dict(
550 name=dict(
551 type='str',
552 required=True
553 ),
554 frontend_ip_configuration=dict(
555 type='str',
556 required=True
557 ),
558 protocol=dict(
559 type='str',
560 choices=['Tcp', 'Udp', 'All']
561 ),
562 frontend_port=dict(
563 type='int',
564 required=True
565 ),
566 idle_timeout=dict(
567 type='int'
568 ),
569 backend_port=dict(
570 type='int',
571 required=True
572 ),
573 enable_floating_ip=dict(
574 type='bool'
575 ),
576 enable_tcp_reset=dict(
577 type='bool'
578 )
579 )
580
581
582 load_balancing_rule_spec = dict(
583 name=dict(
584 type='str',
585 required=True
586 ),
587 frontend_ip_configuration=dict(
588 type='str',
589 required=True
590 ),
591 backend_address_pool=dict(
592 type='str',
593 required=True
594 ),
595 probe=dict(
596 type='str',
597 required=True
598 ),
599 protocol=dict(
600 type='str',
601 choices=['Tcp', 'Udp', 'All']
602 ),
603 load_distribution=dict(
604 type='str',
605 choices=['Default', 'SourceIP', 'SourceIPProtocol'],
606 default='Default'
607 ),
608 frontend_port=dict(
609 type='int',
610 required=True
611 ),
612 backend_port=dict(
613 type='int'
614 ),
615 idle_timeout=dict(
616 type='int',
617 default=4
618 ),
619 enable_floating_ip=dict(
620 type='bool'
621 ),
622 disable_outbound_snat=dict(
623 type='bool',
624 default=False
625 ),
626 enable_tcp_reset=dict(
627 type='bool'
628 )
629 )
630
631
632 outbound_rule_spec = dict(
633 name=dict(type='str', required=True),
634 allocated_outbound_ports=dict(type='int'),
635 frontend_ip_configurations=dict(type='list', elements='str'),
636 backend_address_pool=dict(type='str'),
637 protocol=dict(type='str', choices=['Tcp', 'Udp', 'All']),
638 enable_tcp_reset=dict(type='bool'),
639 idle_timeout_in_minutes=dict(type='int')
640
641 )
642
643
644 class AzureRMLoadBalancer(AzureRMModuleBaseExt):
645 """Configuration class for an Azure RM load balancer resource"""
646
647 def __init__(self):
648 self.module_args = dict(
649 resource_group=dict(
650 type='str',
651 required=True
652 ),
653 name=dict(
654 type='str',
655 required=True
656 ),
657 state=dict(
658 type='str',
659 default='present',
660 choices=['present', 'absent']
661 ),
662 location=dict(
663 type='str'
664 ),
665 sku=dict(
666 type='str',
667 choices=['Basic', 'Standard']
668 ),
669 frontend_ip_configurations=dict(
670 type='list',
671 elements='dict',
672 options=frontend_ip_configuration_spec
673 ),
674 backend_address_pools=dict(
675 type='list',
676 elements='dict',
677 options=backend_address_pool_spec
678 ),
679 probes=dict(
680 type='list',
681 elements='dict',
682 options=probes_spec
683 ),
684 inbound_nat_rules=dict(
685 type='list',
686 elements='dict',
687 options=inbound_nat_rule_spec
688 ),
689 inbound_nat_pools=dict(
690 type='list',
691 elements='dict',
692 options=inbound_nat_pool_spec
693 ),
694 load_balancing_rules=dict(
695 type='list',
696 elements='dict',
697 options=load_balancing_rule_spec
698 ),
699 outbound_rules=dict(
700 type='list',
701 elements='dict',
702 options=outbound_rule_spec
703 )
704 )
705
706 self.resource_group = None
707 self.name = None
708 self.location = None
709 self.sku = None
710 self.frontend_ip_configurations = None
711 self.backend_address_pools = None
712 self.probes = None
713 self.inbound_nat_rules = None
714 self.inbound_nat_pools = None
715 self.outbound_rules = None
716 self.load_balancing_rules = None
717 self.state = None
718 self.tags = None
719
720 self.results = dict(changed=False, state=dict())
721
722 super(AzureRMLoadBalancer, self).__init__(
723 derived_arg_spec=self.module_args,
724 supports_check_mode=True
725 )
726
727 def exec_module(self, **kwargs):
728 """Main module execution method"""
729 for key in list(self.module_args.keys()) + ['tags']:
730 setattr(self, key, kwargs[key])
731
732 changed = False
733
734 resource_group = self.get_resource_group(self.resource_group)
735 if not self.location:
736 self.location = resource_group.location
737
738 load_balancer = self.get_load_balancer()
739
740 if self.state == 'present':
741 # create new load balancer structure early, so it can be easily compared
742 if not load_balancer:
743 changed = True
744 else:
745 response = self.format_item(load_balancer)
746 update1, self.frontend_ip_configurations = self.update_item(self.frontend_ip_configurations, response.get('frontend_ip_configurations'))
747 update2, self.backend_address_pools = self.update_item(self.backend_address_pools, response.get('backend_address_pools'))
748 update3, self.probes = self.update_item(self.probes, response.get('probes'))
749 update4, self.inbound_nat_rules = self.update_item(self.inbound_nat_rules, response.get('inbound_nat_rules'))
750 update5, self.inbound_nat_pools = self.update_item(self.inbound_nat_pools, response.get('inbound_nat_pools'))
751 update6, self.outbound_rules = self.update_item(self.outbound_rules, response.get('outbound_rules'))
752 update7, self.load_balancing_rules = self.update_item(self.load_balancing_rules, response.get('load_balancing_rules'))
753
754 changed = update1 or update2 or update3 or update4 or update5 or update6 or update7
755
756 frontend_ip_configurations_param = [self.network_models.FrontendIPConfiguration(
757 name=item.get('name'),
758 public_ip_address=self.get_public_ip_address_instance(item.get('public_ip_address')) if item.get('public_ip_address') else None,
759 private_ip_address=item.get('private_ip_address'),
760 private_ip_allocation_method=item.get('private_ip_allocation_method'),
761 zones=item.get('zones'),
762 subnet=self.network_models.Subnet(
763 id=item.get('subnet'),
764 private_endpoint_network_policies=None,
765 private_link_service_network_policies=None
766 ) if item.get('subnet') else None
767 ) for item in self.frontend_ip_configurations] if self.frontend_ip_configurations else None
768
769 backend_address_pools_param = [self.network_models.BackendAddressPool(
770 name=item.get('name')
771 ) for item in self.backend_address_pools] if self.backend_address_pools else None
772
773 probes_param = [self.network_models.Probe(
774 name=item.get('name'),
775 port=item.get('port'),
776 protocol=item.get('protocol'),
777 interval_in_seconds=item.get('interval'),
778 request_path=item.get('request_path'),
779 number_of_probes=item.get('fail_count')
780 ) for item in self.probes] if self.probes else None
781
782 inbound_nat_pools_param = [self.network_models.InboundNatPool(
783 name=item.get('name'),
784 frontend_ip_configuration=self.network_models.SubResource(
785 id=frontend_ip_configuration_id(
786 self.subscription_id,
787 self.resource_group,
788 self.name,
789 item.get('frontend_ip_configuration_name'))),
790 protocol=item.get('protocol'),
791 frontend_port_range_start=item.get('frontend_port_range_start'),
792 frontend_port_range_end=item.get('frontend_port_range_end'),
793 backend_port=item.get('backend_port')
794 ) for item in self.inbound_nat_pools] if self.inbound_nat_pools else None
795
796 load_balancing_rules_param = [self.network_models.LoadBalancingRule(
797 name=item.get('name'),
798 frontend_ip_configuration=self.network_models.SubResource(
799 id=frontend_ip_configuration_id(
800 self.subscription_id,
801 self.resource_group,
802 self.name,
803 item.get('frontend_ip_configuration')
804 )
805 ),
806 backend_address_pool=self.network_models.SubResource(
807 id=backend_address_pool_id(
808 self.subscription_id,
809 self.resource_group,
810 self.name,
811 item.get('backend_address_pool')
812 )
813 ),
814 probe=self.network_models.SubResource(
815 id=probe_id(
816 self.subscription_id,
817 self.resource_group,
818 self.name,
819 item.get('probe')
820 )
821 ),
822 protocol=item.get('protocol'),
823 load_distribution=item.get('load_distribution'),
824 frontend_port=item.get('frontend_port'),
825 backend_port=item.get('backend_port'),
826 idle_timeout_in_minutes=item.get('idle_timeout'),
827 enable_floating_ip=item.get('enable_floating_ip'),
828 enable_tcp_reset=item.get('enable_tcp_reset'),
829 disable_outbound_snat=item.get('disable_outbound_snat'),
830 ) for item in self.load_balancing_rules] if self.load_balancing_rules else None
831
832 inbound_nat_rules_param = [self.network_models.InboundNatRule(
833 name=item.get('name'),
834 frontend_ip_configuration=self.network_models.SubResource(
835 id=frontend_ip_configuration_id(
836 self.subscription_id,
837 self.resource_group,
838 self.name,
839 item.get('frontend_ip_configuration')
840 )
841 ) if item.get('frontend_ip_configuration') else None,
842 protocol=item.get('protocol'),
843 frontend_port=item.get('frontend_port'),
844 backend_port=item.get('backend_port'),
845 idle_timeout_in_minutes=item.get('idle_timeout'),
846 enable_tcp_reset=item.get('enable_tcp_reset'),
847 enable_floating_ip=item.get('enable_floating_ip')
848 ) for item in self.inbound_nat_rules] if self.inbound_nat_rules else None
849
850 outbound_rules_param = [self.network_models.OutboundRule(
851 name=item.get('name'),
852 frontend_ip_configurations=[self.network_models.SubResource(
853 id=frontend_ip_configuration_id(
854 self.subscription_id,
855 self.resource_group,
856 self.name,
857 value
858 )
859 )for value in item['frontend_ip_configurations']] if item.get('frontend_ip_configurations') else None,
860 backend_address_pool=self.network_models.SubResource(
861 id=backend_address_pool_id(
862 self.subscription_id,
863 self.resource_group,
864 self.name,
865 item.get('backend_address_pool')
866 )
867 ),
868 allocated_outbound_ports=item.get('allocated_outbound_ports'),
869 protocol=item.get('protocol'),
870 enable_tcp_reset=item.get('enable_tcp_reset'),
871 idle_timeout_in_minutes=item.get('idle_timeout_in_minutes')
872 ) for item in self.outbound_rules] if self.outbound_rules else None
873
874 # construct the new instance, if the parameter is none, keep remote one
875 self.new_load_balancer = self.network_models.LoadBalancer(
876 sku=self.network_models.LoadBalancerSku(name=self.sku) if self.sku else None,
877 location=self.location,
878 tags=self.tags,
879 frontend_ip_configurations=frontend_ip_configurations_param,
880 backend_address_pools=backend_address_pools_param,
881 probes=probes_param,
882 inbound_nat_pools=inbound_nat_pools_param,
883 load_balancing_rules=load_balancing_rules_param,
884 inbound_nat_rules=inbound_nat_rules_param,
885 outbound_rules=outbound_rules_param,
886 )
887
888 self.new_load_balancer = self.assign_protocol(self.new_load_balancer, load_balancer)
889
890 if load_balancer:
891 self.new_load_balancer = self.object_assign(self.new_load_balancer, load_balancer)
892 elif self.state == 'absent' and load_balancer:
893 changed = True
894
895 self.results['state'] = load_balancer.as_dict() if load_balancer else {}
896 if 'tags' in self.results['state']:
897 update_tags, self.results['state']['tags'] = self.update_tags(self.results['state']['tags'])
898 if update_tags:
899 changed = True
900 else:
901 if self.tags:
902 changed = True
903 self.results['changed'] = changed
904
905 if self.check_mode:
906 return self.results
907
908 if self.state == 'present' and changed:
909 self.results['state'] = self.create_or_update_load_balancer(self.new_load_balancer).as_dict()
910 elif self.state == 'absent' and changed:
911 self.delete_load_balancer()
912 self.results['state'] = None
913
914 return self.results
915
916 def update_item(self, new, old):
917 changed = False
918 if new is not None:
919 if old is not None:
920 if not self.default_compare({}, new, old, '', dict(compare=[])):
921 changed = True
922
923 keys = [item['name'] for item in new]
924 for item in old:
925 if item['name'] not in keys:
926 new.append(item)
927 else:
928 changed = True
929 else:
930 new = old
931 return changed, new
932
933 def format_item(self, item):
934 results = dict()
935 if item.frontend_ip_configurations is not None:
936 results['frontend_ip_configurations'] = []
937 for value in item.frontend_ip_configurations:
938 new_item = dict(name=value.name,
939 public_ip_address=None,
940 private_ip_address=value.private_ip_address,
941 private_ip_allocation_method=value.private_ip_allocation_method,
942 subnet=None,
943 zones=value.zones)
944 if value.public_ip_address is not None:
945 new_item['public_ip_address'] = parse_resource_id(value.public_ip_address.id)['name']
946 if value.subnet is not None:
947 new_item['subnet'] = value.subnet.id
948 results['frontend_ip_configurations'].append(new_item)
949 else:
950 results['frontend_ip_configurations'] = None
951 if item.backend_address_pools is not None:
952 results['backend_address_pools'] = []
953 for value in item.backend_address_pools:
954 results['backend_address_pools'].append(dict(name=value.name))
955 else:
956 results['backend_address_pools'] = None
957 if item.probes is not None:
958 results['probes'] = []
959 for value in item.probes:
960 results['probes'].append(dict(name=value.name,
961 port=value.port,
962 protocol=value.protocol,
963 interval=value.interval_in_seconds,
964 fail_count=value.number_of_probes,
965 request_path=value.request_path))
966 else:
967 results['probes'] = None
968 if item.inbound_nat_pools is not None:
969 results['inbound_nat_pools'] = []
970 for value in item.inbound_nat_pools:
971 new_item = dict(name=value.name,
972 frontend_ip_configuration_name=None,
973 protocol=value.protocol,
974 frontend_port_range_start=value.frontend_port_range_start,
975 frontend_port_range_end=value.frontend_port_range_end,
976 backend_port=value.backend_port)
977 if value.frontend_ip_configuration is not None:
978 new_item['frontend_ip_configuration_name'] = parse_resource_id(value.frontend_ip_configuration.id)['resource_name']
979 results['inbound_nat_pools'].append(new_item)
980 else:
981 results['inbound_nat_pools'] = None
982 if item.inbound_nat_rules is not None:
983 results['inbound_nat_rules'] = []
984 for value in item.inbound_nat_rules:
985 new_item = dict(name=value.name,
986 frontend_ip_configuration=None,
987 protocol=value.protocol,
988 frontend_port=value.frontend_port,
989 idle_timeout=value.idle_timeout_in_minutes,
990 backend_port=value.backend_port,
991 enable_floating_ip=value.enable_floating_ip,
992 enable_tcp_reset=value.enable_tcp_reset)
993 if value.frontend_ip_configuration is not None:
994 new_item['frontend_ip_configuration'] = parse_resource_id(value.frontend_ip_configuration.id)['resource_name']
995 results['inbound_nat_rules'].append(new_item)
996 else:
997 results['inbound_nat_rules'] = None
998 if item.load_balancing_rules is not None:
999 results['load_balancing_rules'] = []
1000 for value in item.load_balancing_rules:
1001 new_item = dict(name=value.name,
1002 frontend_ip_configuration=None,
1003 backend_address_pool=None,
1004 probe=None,
1005 protocol=value.protocol,
1006 load_distribution=value.load_distribution,
1007 frontend_port=value.frontend_port,
1008 backend_port=value.backend_port,
1009 idle_timeout=value.idle_timeout_in_minutes,
1010 enable_floating_ip=value.enable_floating_ip,
1011 disable_outbound_snat=value.disable_outbound_snat,
1012 enable_tcp_reset=value.enable_tcp_reset)
1013 if value.frontend_ip_configuration is not None:
1014 new_item['frontend_ip_configuration'] = parse_resource_id(value.frontend_ip_configuration.id)['resource_name']
1015 if value.backend_address_pool is not None:
1016 new_item['backend_address_pool'] = parse_resource_id(value.backend_address_pool.id)['resource_name']
1017 if value.probe is not None:
1018 new_item['probe'] = parse_resource_id(value.probe.id)['resource_name']
1019 results['load_balancing_rules'].append(new_item)
1020 else:
1021 results['load_balancing_rules'] = None
1022 if item.outbound_rules is not None:
1023 results['outbound_rules'] = []
1024 for value in item.outbound_rules:
1025 new_item = dict(name=value.name,
1026 allocated_outbound_ports=value.allocated_outbound_ports,
1027 frontend_ip_configurations=[],
1028 backend_address_pool=None,
1029 protocol=value.protocol,
1030 enable_tcp_reset=value.enable_tcp_reset,
1031 idle_timeout_in_minutes=value.idle_timeout_in_minutes)
1032 if value.frontend_ip_configurations is not None:
1033 for key in value.frontend_ip_configurations:
1034 new_item['frontend_ip_configurations'].append(parse_resource_id(key.id)['resource_name'])
1035 else:
1036 new_item['frontend_ip_configurations'] = None
1037 if value.backend_address_pool is not None:
1038 new_item['backend_address_pool'] = parse_resource_id(value.backend_address_pool.id)['resource_name']
1039 results['outbound_rules'].append(new_item)
1040 else:
1041 results['outbound_rules'] = None
1042
1043 return results
1044
1045 def get_public_ip_address_instance(self, id):
1046 """Get a reference to the public ip address resource"""
1047 self.log('Fetching public ip address {0}'.format(id))
1048 resource_id = format_resource_id(id, self.subscription_id, 'Microsoft.Network', 'publicIPAddresses', self.resource_group)
1049 return self.network_models.PublicIPAddress(id=resource_id)
1050
1051 def get_load_balancer(self):
1052 """Get a load balancer"""
1053 self.log('Fetching loadbalancer {0}'.format(self.name))
1054 try:
1055 return self.network_client.load_balancers.get(self.resource_group, self.name)
1056 except ResourceNotFoundError:
1057 return None
1058
1059 def delete_load_balancer(self):
1060 """Delete a load balancer"""
1061 self.log('Deleting loadbalancer {0}'.format(self.name))
1062 try:
1063 poller = self.network_client.load_balancers.begin_delete(self.resource_group, self.name)
1064 return self.get_poller_result(poller)
1065 except Exception as exc:
1066 self.fail("Error deleting loadbalancer {0} - {1}".format(self.name, str(exc)))
1067
1068 def create_or_update_load_balancer(self, param):
1069 try:
1070 poller = self.network_client.load_balancers.begin_create_or_update(self.resource_group, self.name, param)
1071 new_lb = self.get_poller_result(poller)
1072 return new_lb
1073 except Exception as exc:
1074 self.fail("Error creating or updating load balancer {0} - {1}".format(self.name, str(exc)))
1075
1076 def object_assign(self, patch, origin):
1077 attribute_map = set(self.network_models.LoadBalancer._attribute_map.keys()) - set(self.network_models.LoadBalancer._validation.keys())
1078 for key in attribute_map:
1079 if not getattr(patch, key):
1080 setattr(patch, key, getattr(origin, key))
1081 return patch
1082
1083 def assign_protocol(self, patch, origin):
1084 attribute_map = ['probes', 'inbound_nat_rules', 'inbound_nat_pools', 'load_balancing_rules']
1085 for attribute in attribute_map:
1086 properties = getattr(patch, attribute)
1087 if not properties:
1088 continue
1089 references = getattr(origin, attribute) if origin else []
1090 for item in properties:
1091 if item.protocol:
1092 continue
1093 refs = [x for x in references if to_native(x.name) == item.name]
1094 ref = refs[0] if len(refs) > 0 else None
1095 item.protocol = ref.protocol if ref else 'Tcp'
1096 return patch
1097
1098
1099 def frontend_ip_configuration_id(subscription_id, resource_group_name, load_balancer_name, name):
1100 """Generate the id for a frontend ip configuration"""
1101 return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/loadBalancers/{2}/frontendIPConfigurations/{3}'.format(
1102 subscription_id,
1103 resource_group_name,
1104 load_balancer_name,
1105 name
1106 )
1107
1108
1109 def backend_address_pool_id(subscription_id, resource_group_name, load_balancer_name, name):
1110 """Generate the id for a backend address pool"""
1111 return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/loadBalancers/{2}/backendAddressPools/{3}'.format(
1112 subscription_id,
1113 resource_group_name,
1114 load_balancer_name,
1115 name
1116 )
1117
1118
1119 def probe_id(subscription_id, resource_group_name, load_balancer_name, name):
1120 """Generate the id for a probe"""
1121 return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/loadBalancers/{2}/probes/{3}'.format(
1122 subscription_id,
1123 resource_group_name,
1124 load_balancer_name,
1125 name
1126 )
1127
1128
1129 def main():
1130 """Main execution"""
1131 AzureRMLoadBalancer()
1132
1133
1134 if __name__ == '__main__':
1135 main()