Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_virtual_server.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
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 DOCUMENTATION = r'''
11 ---
12 module: bigip_virtual_server
13 short_description: Manage LTM virtual servers on a BIG-IP
14 description:
15 - Manage LTM virtual servers on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 state:
19 description:
20 - The virtual server state. If C(absent), deletes the virtual server
21 if it exists. If C(present), creates the virtual server and enables it.
22 If C(enabled), enables the virtual server if it exists. If C(disabled),
23 creates the virtual server if needed, and sets the state to C(disabled).
24 - Attempting to change C(state) on a virtual server that belongs to an iAPP with strict updates enabled will result
25 in an error message returned by device, unless C(insert_metadata) parameter is set to C(no).
26 type: str
27 choices:
28 - present
29 - absent
30 - enabled
31 - disabled
32 default: present
33 type:
34 description:
35 - Specifies the network service provided by this virtual server.
36 - When creating a new virtual server, if this parameter is not provided, the
37 default is C(standard).
38 - This value cannot be changed after it is set.
39 - When C(standard), specifies a virtual server that directs client traffic to
40 a load balancing pool, and is the most basic type of virtual server. When you
41 first create the virtual server, you assign an existing default pool to it.
42 From then on, the virtual server automatically directs traffic to that default pool.
43 - When C(forwarding-l2), specifies a virtual server that shares the same IP address as a
44 node in an associated VLAN.
45 - When C(forwarding-ip), specifies a virtual server like other virtual servers, except
46 the virtual server has no pool members to load balance. The virtual server simply
47 forwards the packet directly to the destination IP address specified in the client request.
48 - When C(performance-http), specifies a virtual server with which you associate a Fast HTTP
49 profile. Together, the virtual server and profile increase the speed at which the virtual
50 server processes HTTP requests.
51 - When C(performance-l4), specifies a virtual server with which you associate a Fast L4 profile.
52 Together, the virtual server and profile increase the speed at which the virtual server
53 processes layer 4 requests.
54 - When C(stateless), specifies a virtual server that accepts traffic matching the virtual
55 server address and load balances the packet to the pool members without attempting to
56 match the packet to a pre-existing connection in the connection table. New connections
57 are immediately removed from the connection table. This addresses the requirement for
58 one-way UDP traffic that needs to be processed at very high throughput levels, for example,
59 load balancing syslog traffic to a pool of syslog servers. Stateless virtual servers are
60 not suitable for processing traffic requiring stateful tracking, such as TCP traffic.
61 Stateless virtual servers do not support iRules, persistence, connection mirroring,
62 rateshaping, or SNAT automap.
63 - When C(reject), specifies the BIG-IP system rejects any traffic destined for the
64 virtual server IP address.
65 - When C(dhcp), specifies a virtual server that relays Dynamic Host Control Protocol (DHCP)
66 client requests for an IP address to one or more DHCP servers, and provides DHCP server
67 responses with an available IP address for the client.
68 - When C(internal), specifies a virtual server that supports modification of HTTP requests
69 and responses. Internal virtual servers enable the use of ICAP (Internet Content Adaptation
70 Protocol) servers to modify HTTP requests and responses by creating and applying an ICAP
71 profile and adding Request Adapt or Response Adapt profiles to the virtual server.
72 - When C(message-routing), specifies a virtual server that uses a SIP application protocol
73 and functions in accordance with a SIP session profile and SIP router profile.
74 type: str
75 choices:
76 - standard
77 - forwarding-l2
78 - forwarding-ip
79 - performance-http
80 - performance-l4
81 - stateless
82 - reject
83 - dhcp
84 - internal
85 - message-routing
86 default: standard
87 name:
88 description:
89 - Virtual server name.
90 type: str
91 required: True
92 aliases:
93 - vs
94 destination:
95 description:
96 - Destination IP of the virtual server.
97 - Required when C(state) is C(present) and the virtual server does not exist.
98 - When C(type) is C(internal), this parameter is ignored. For all other types,
99 it is required.
100 - Destination can also be specified as a name for an existing Virtual Address.
101 type: str
102 aliases:
103 - address
104 - ip
105 source:
106 description:
107 - Specifies an IP address or network from which the virtual server accepts traffic.
108 - The virtual server accepts clients only from one of these IP addresses.
109 - For this setting to function effectively, specify a value other than 0.0.0.0/0 or ::/0
110 (that is, any/0, any6/0).
111 - In order to maximize the utility of this setting, specify the most specific address
112 prefixes covering all customer addresses and no others.
113 - Specify the IP address in Classless Inter-Domain Routing (CIDR) format; address/prefix,
114 where the prefix length is in bits. For example, for IPv4, 10.0.0.1/32 or 10.0.0.0/24,
115 and for IPv6, ffe1::0020/64 or 2001:ed8:77b5:2:10:10:100:42/64.
116 type: str
117 port:
118 description:
119 - Port of the virtual server. Required when C(state) is C(present)
120 and the virtual server does not exist.
121 - If you do not want to specify a particular port, use the value C(0).
122 This means the virtual server listens on any port.
123 - When C(type) is C(dhcp), this module forces the C(port) parameter to C(67).
124 - When C(type) is C(internal), this module forces the C(port) parameter to C(0).
125 - In addition to specifying a port number, a select number of service names may also
126 be provided.
127 - The string C(ftp) may be substituted for for port C(21).
128 - The string C(http) may be substituted for for port C(80).
129 - The string C(https) may be substituted for for port C(443).
130 - The string C(telnet) may be substituted for for port C(23).
131 - The string C(smtp) may be substituted for for port C(25).
132 - The string C(snmp) may be substituted for for port C(161).
133 - The string C(snmp-trap) may be substituted for for port C(162).
134 - The string C(ssh) may be substituted for for port C(22).
135 - The string C(tftp) may be substituted for for port C(69).
136 - The string C(isakmp) may be substituted for for port C(500).
137 - The string C(mqtt) may be substituted for for port C(1883).
138 - The string C(mqtt-tls) may be substituted for for port C(8883).
139 type: str
140 profiles:
141 description:
142 - List of profiles (HTTP, ClientSSL, ServerSSL, etc) to apply to both sides
143 of the connection (client-side and server-side).
144 - If you only want to apply a particular profile to the client-side of
145 the connection, specify C(client-side) for the profile's C(context).
146 - If you only want to apply a particular profile to the server-side of
147 the connection, specify C(server-side) for the profile's C(context).
148 - If C(context) is not provided, it will default to C(all).
149 - If you want to remove a profile from the list of profiles currently active
150 on the virtual, simply remove it from the C(profiles) list. See
151 examples for an illustration of this.
152 - If you want to add a profile to the list of profiles currently active
153 on the virtual, simply add it to the C(profiles) list. See
154 examples for an illustration of this.
155 - B(Profiles are important). This module will fail to configure a BIG-IP if you mix up
156 your profiles, or if you attempt to set an IP protocol which your current,
157 or new, profiles do not support. Both this module, and BIG-IP, will report an error
158 if this is incorrect, resembling C(lists profiles incompatible with its protocol).
159 - If you are unsure what the correct profile combinations are, we suggest having a BIG-IP
160 available in which you can make changes and copy what the correct combinations are.
161 - To use C(http2) in full proxy to enable C(HTTP MRF Router) option seen in the GUI you need to assign
162 C(/Common/httprouter) profile with C(context) set to C(all). See the bottom of examples section below.
163 type: raw
164 aliases:
165 - all_profiles
166 suboptions:
167 name:
168 description:
169 - Name of the profile.
170 - This must be specified if a context is specified.
171 - If this is not specified, it is assumed the profile item is
172 only a name of a profile.
173 type: str
174 context:
175 description:
176 - The side of the connection on which the profile should be applied.
177 type: str
178 choices:
179 - all
180 - server-side
181 - client-side
182 default: all
183 irules:
184 description:
185 - Specifies a list of rules to be applied in priority order.
186 - If you want to remove existing iRules, specify a single empty value; C("").
187 See the documentation for an example.
188 - The order in which iRules are specified does matter, so a list that contains
189 the same list elements but in a different order in the playbook will make changes
190 on the device.
191 - When C(type) is C(dhcp), C(stateless), C(reject), or C(internal), this parameter is ignored.
192 type: list
193 elements: str
194 aliases:
195 - all_rules
196 enabled_vlans:
197 description:
198 - List of VLANs to enable. When a VLAN named C(all) is used, all
199 VLANs will be allowed. VLANs can be specified with or without the
200 leading partition. If the partition is not specified in the VLAN,
201 the C(partition) option of this module is used.
202 - This parameter is mutually exclusive with the C(disabled_vlans) parameter.
203 type: list
204 elements: str
205 disabled_vlans:
206 description:
207 - List of VLANs to be disabled. If the partition is not specified in the VLAN,
208 the C(partition) option of this module is used.
209 - This parameter is mutually exclusive with the C(enabled_vlans) parameters.
210 type: list
211 elements: str
212 pool:
213 description:
214 - Default pool for the virtual server.
215 - If you want to remove the existing pool, specify an empty value; C("").
216 See the documentation for an example.
217 - When creating a new virtual server, and C(type) is C(stateless), this parameter
218 is required.
219 - If C(type) is C(stateless), the C(pool) must not have any members
220 which define a C(rate_limit).
221 type: str
222 policies:
223 description:
224 - Specifies the policies for the virtual server.
225 - When C(type) is C(dhcp), C(reject), or C(internal), this parameter is ignored.
226 type: list
227 elements: str
228 aliases:
229 - all_policies
230 per_flow_request_access_policy:
231 description:
232 - Specifies the Per-Request access policy for the virtual server.
233 type: str
234 snat:
235 description:
236 - Source network address policy.
237 - When C(type) is C(dhcp), C(reject), or C(internal), this parameter is ignored.
238 - The name of a SNAT pool (like "/Common/snat_pool_name") can be specified to enable SNAT
239 with the specific pool.
240 - To remove SNAT, specify the word C(none).
241 - To specify automap, use the word C(automap).
242 type: str
243 serverssl_use_sni:
244 description:
245 - When C(enabled), specifies whether SNI is enabled on the server-side SSL connection
246 - When C(disabled), specifies whether SNI is disabled on the server-side SSL connection
247 - When creating a new virtual server, the default is C(disabled).
248 type: bool
249 default_persistence_profile:
250 description:
251 - Default profile which manages the session persistence.
252 - If you want to remove the existing default persistence profile, specify an
253 empty value; C(""). See the documentation for an example.
254 - When C(type) is C(dhcp), this parameter is ignored.
255 type: str
256 description:
257 description:
258 - Virtual server description.
259 type: str
260 fallback_persistence_profile:
261 description:
262 - Specifies the persistence profile you want the system to use if it
263 cannot use the specified default persistence profile.
264 - If you want to remove the existing fallback persistence profile, specify an
265 empty value; C(""). See the documentation for an example.
266 - When C(type) is C(dhcp), this parameter is ignored.
267 type: str
268 partition:
269 description:
270 - Device partition to manage resources on.
271 type: str
272 default: Common
273 metadata:
274 description:
275 - Arbitrary key/value pairs you can attach to a virtual server. This is useful in
276 situations where you want to annotate a virtual to be managed by Ansible.
277 - Key names are stored as strings; this includes names that are numbers.
278 - Values for all of the keys are stored as strings; this includes values
279 that are numbers.
280 - Data is persisted, not ephemeral.
281 type: raw
282 insert_metadata:
283 description:
284 - When set to C(false), the module does not set metadata on the device.
285 - Currently there is a limitation that non-admin users cannot set metadata on the object, despite being
286 able to create and modify virtual server objects. Setting this option to C(false) allows
287 such users to use this module to manage virtual server objects on the device.
288 - Attempting to change C(state) on Virtual Server that belongs to an iAPP with strict updates enabled will result
289 in error message returned by device, unless C(insert_metadata) parameter is set to C(false).
290 type: bool
291 default: true
292 address_translation:
293 description:
294 - When C(enabled), specifies the system translates the address of the
295 virtual server.
296 - When C(disabled), specifies the system uses the address without translation.
297 - This option is useful when the system is load balancing devices that have the
298 same IP address.
299 - When creating a new virtual server, the default is C(enabled).
300 type: bool
301 port_translation:
302 description:
303 - When C(enabled), specifies the system translates the port of the virtual
304 server.
305 - When C(disabled), specifies the system uses the port without translation.
306 Turning off port translation for a virtual server is useful if you want to use
307 the virtual server to load balance connections to any service.
308 - When creating a new virtual server, the default is C(enabled).
309 type: bool
310 source_port:
311 description:
312 - Specifies whether the system preserves the source port of the connection.
313 - When creating a new virtual server, if this parameter is not specified, the default is C(preserve).
314 type: str
315 choices:
316 - preserve
317 - preserve-strict
318 - change
319 mirror:
320 description:
321 - Specifies the system mirrors connections on each member of a redundant pair.
322 - When creating a new virtual server, if this parameter is not specified, the default is C(disabled).
323 type: bool
324 auto_last_hop:
325 description:
326 - Allows the BIG-IP system to track the source MAC address of incoming connections and return traffic from
327 pools to the source MAC address, regardless of the routing table.
328 type: str
329 choices:
330 - default
331 - enabled
332 - disabled
333 version_added: "1.13.0"
334 mask:
335 description:
336 - Specifies the destination address network mask. This parameter works with IPv4 and IPv6 addresses.
337 - This is an optional parameter which can be specified when creating or updating virtual server.
338 - If C(destination) is set in CIDR notation format and C(mask) is provided, the C(mask) parameter takes precedence.
339 - If you specify a catchall destination (for example, C(0.0.0.0) for IPv4, C(::) for IPv6)
340 the mask parameter is set to C(any) or C(any6) respectively.
341 - When the C(destination) is not in CIDR notation and a C(mask) is not specified, C(255.255.255.255) or
342 C(ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) is set for IPv4 and IPv6 addresses respectively.
343 - When C(destination) is provided in CIDR notation format and a C(mask) is not specified, the mask parameter is
344 inferred from C(destination).
345 - When C(destination) is provided as a virtual address name, and a C(mask) is not specified,
346 the mask will be C(None), allowing device set it with its internal defaults.
347 type: str
348 ip_protocol:
349 description:
350 - Specifies a network protocol name you want the system to use to direct traffic
351 on this virtual server.
352 - When creating a new virtual server, if this parameter is not specified, the default is C(tcp).
353 - The Protocol setting is not available when you select Performance (HTTP) as the C(Type).
354 - The value of this argument can be specified in either its numeric value, or in a select number
355 of named values. Refer to C(choices) for examples.
356 - For a list of valid IP protocol numbers, refer to https://en.wikipedia.org/wiki/List_of_IP_protocol_numbers.
357 - When C(type) is C(dhcp), this module forces the C(ip_protocol) parameter to C(17) (UDP).
358 type: str
359 choices:
360 - ah
361 - any
362 - bna
363 - esp
364 - etherip
365 - gre
366 - icmp
367 - ipencap
368 - ipv6
369 - ipv6-auth
370 - ipv6-crypt
371 - ipv6-icmp
372 - isp-ip
373 - mux
374 - ospf
375 - sctp
376 - tcp
377 - udp
378 - udplite
379 firewall_enforced_policy:
380 description:
381 - Applies the specified AFM policy to the virtual in an enforcing way.
382 - When creating a new virtual, if this parameter is not specified, the enforced
383 policy is disabled.
384 type: str
385 firewall_staged_policy:
386 description:
387 - Applies the specified AFM policy to the virtual in an enforcing way.
388 - A staged policy shows the results of the policy rules in the log, while not
389 actually applying the rules to traffic.
390 - When creating a new virtual, if this parameter is not specified, the staged
391 policy is disabled.
392 type: str
393 security_log_profiles:
394 description:
395 - Specifies the log profile applied to the virtual server.
396 - To make use of this feature, the AFM module must be licensed and provisioned.
397 - The C(Log all requests) and C(Log illegal requests) are mutually exclusive and
398 therefore, this module raises an error if the two are specified together.
399 type: list
400 elements: str
401 security_nat_policy:
402 description:
403 - Specify the Firewall NAT policies for the virtual server.
404 - You can specify one or more NAT policies to use.
405 - The most specific policy is used. For example, if you specify the
406 virtual server should use the device policy and the route domain policy, the route
407 domain policy overrides the device policy.
408 suboptions:
409 policy:
410 description:
411 - Specifies the policy to apply a NAT policy directly to the virtual server.
412 - The virtual server NAT policy is the most specific, and overrides a
413 route domain and device policy, if specified.
414 - To remove the policy, specify an empty string value.
415 type: str
416 use_device_policy:
417 description:
418 - Specifies the virtual server uses the device NAT policy, as specified
419 in the Firewall Options.
420 - The device policy is used if no route domain or virtual server NAT
421 setting is specified.
422 type: bool
423 use_route_domain_policy:
424 description:
425 - Specifies the virtual server uses the route domain policy, as
426 specified in the Route Domain Security settings.
427 - When specified, the route domain policy overrides the device policy, and
428 is overridden by a virtual server policy.
429 type: bool
430 type: dict
431 ip_intelligence_policy:
432 description:
433 - Specifies the IP intelligence policy applied to the virtual server.
434 - This parameter requires a valid BIG-IP security module is provisioned,
435 such as ASM or AFM.
436 type: str
437 rate_limit:
438 description:
439 - Virtual server rate limit (connections-per-second). Setting this to C(0)
440 disables the limit.
441 - The valid value range is C(0) - C(4294967295).
442 type: int
443 rate_limit_dst_mask:
444 description:
445 - Specifies a mask, in bits, to be applied to the destination address as part of the rate limiting.
446 - The default value is C(0), which is equivalent to using the entire address - C(32) in IPv4, or C(128) in IPv6.
447 - The valid value range is C(0) - C(4294967295).
448 type: int
449 rate_limit_src_mask:
450 description:
451 - Specifies a mask, in bits, to be applied to the source address as part of the rate limiting.
452 - The default value is C(0), which is equivalent to using the entire address - C(32) in IPv4, or C(128) in IPv6.
453 - The valid value range is C(0) - C(4294967295).
454 type: int
455 rate_limit_mode:
456 description:
457 - Indicates whether the rate limit is applied per virtual object, per source address, per destination address,
458 or some combination thereof.
459 - The default value is C(object), which does not use the source or destination address as part of the key.
460 type: str
461 choices:
462 - object
463 - object-source
464 - object-destination
465 - object-source-destination
466 - destination
467 - source
468 - source-destination
469 default: object
470 clone_pools:
471 description:
472 - Specifies a pool or list of pools that the virtual server uses to replicate either client-side
473 or server-side traffic.
474 - Typically this option is used for intrusion detection.
475 type: list
476 elements: dict
477 suboptions:
478 pool_name:
479 description:
480 - The pool name to which the server replicates the traffic.
481 - Only pools created on the Common partition or on the same partition as the virtual server can be used.
482 - Referencing a pool on the Common partition needs to be done in the full path format,
483 for example, C(/Common/pool_name).
484 type: str
485 required: True
486 context:
487 description:
488 - The context option for a clone pool to replicate either client-side or server-side traffic.
489 type: str
490 required: True
491 choices:
492 - clientside
493 - serverside
494 service_down_immediate_action:
495 description:
496 - Specifies the immediate action to take upon the receipt of the initial SYN packet if the
497 availability status of the virtual server is Offline or Unavailable.
498 - Supported for virtual servers with a Type of C(standard) and Protocol of C(TCP).
499 type: str
500 choices:
501 - none
502 - reset
503 - drop
504 version_added: "1.16.0"
505 check_profiles:
506 description:
507 - Specifies whether the client and server SSL profiles specified by the user should be verified to be
508 correct against the existing profiles. This is useful in cases where a large number of profiles
509 are being added at once.
510 - Not recommended for common use. In case of duplicate profiles, or erroneous profiles,
511 the BIG-IP throws an error.
512 type: bool
513 default: true
514 version_added: "1.2.0"
515 bypass_module_checks:
516 description:
517 - Disables all built-in module verification checks that require BIG-IP device calls. Using this option cuts
518 down on the number of REST calls made by this module. The trade off is that most parameters are sent as is,
519 which requires extra care when defining them.
520 - The device is the final source of truth for such configurations, usable in cases where speed is
521 preferred over accuracy.
522 - If set to C(true), the module ignores the value op C(check_profiles) parameter.
523 - This parameter can be used when creating new or updating existing resources.
524 type: bool
525 default: false
526 version_added: "1.3.0"
527 extends_documentation_fragment: f5networks.f5_modules.f5
528 author:
529 - Tim Rupp (@caphrim007)
530 - Wojciech Wypior (@wojtek0806)
531 - Nitin Khanna (@nitinthewiz)
532 '''
533
534 EXAMPLES = r'''
535 - name: Modify Port of the Virtual Server
536 bigip_virtual_server:
537 state: present
538 partition: Common
539 name: my-virtual-server
540 port: 8080
541 provider:
542 server: lb.mydomain.net
543 user: admin
544 password: secret
545 delegate_to: localhost
546
547 - name: Delete virtual server
548 bigip_virtual_server:
549 state: absent
550 partition: Common
551 name: my-virtual-server
552 provider:
553 server: lb.mydomain.net
554 user: admin
555 password: secret
556 delegate_to: localhost
557
558 - name: Add virtual server
559 bigip_virtual_server:
560 state: present
561 partition: Common
562 name: my-virtual-server
563 destination: 10.10.10.10
564 port: 443
565 pool: my-pool
566 snat: Automap
567 description: Test Virtual Server
568 profiles:
569 - http
570 - fix
571 - name: clientssl
572 context: server-side
573 - name: ilx
574 context: client-side
575 policies:
576 - my-ltm-policy-for-asm
577 - ltm-uri-policy
578 - ltm-policy-2
579 - ltm-policy-3
580 enabled_vlans:
581 - /Common/vlan2
582 provider:
583 server: lb.mydomain.net
584 user: admin
585 password: secret
586 delegate_to: localhost
587
588 - name: Add FastL4 virtual server
589 bigip_virtual_server:
590 destination: 1.1.1.1
591 name: fastl4_vs
592 port: 80
593 profiles:
594 - fastL4
595 state: present
596 provider:
597 server: lb.mydomain.net
598 user: admin
599 password: secret
600 delegate_to: localhost
601
602 - name: Add iRules to the Virtual Server
603 bigip_virtual_server:
604 name: my-virtual-server
605 irules:
606 - irule1
607 - irule2
608 provider:
609 server: lb.mydomain.net
610 user: admin
611 password: secret
612 delegate_to: localhost
613
614 - name: Remove one iRule from the Virtual Server
615 bigip_virtual_server:
616 name: my-virtual-server
617 irules:
618 - irule2
619 provider:
620 server: lb.mydomain.net
621 user: admin
622 password: secret
623 delegate_to: localhost
624
625 - name: Remove all iRules from the Virtual Server
626 bigip_virtual_server:
627 name: my-virtual-server
628 irules: ""
629 provider:
630 server: lb.mydomain.net
631 user: admin
632 password: secret
633 delegate_to: localhost
634
635 - name: Remove pool from the Virtual Server
636 bigip_virtual_server:
637 name: my-virtual-server
638 pool: ""
639 provider:
640 server: lb.mydomain.net
641 user: admin
642 password: secret
643 delegate_to: localhost
644
645 - name: Add metadata to virtual
646 bigip_virtual_server:
647 name: my-virtual-server
648 partition: Common
649 metadata:
650 ansible: 2.4
651 updated_at: 2017-12-20T17:50:46Z
652 provider:
653 server: lb.mydomain.com
654 user: admin
655 password: secret
656 delegate_to: localhost
657
658 - name: Add virtual with two profiles
659 bigip_virtual_server:
660 name: my-virtual-server
661 partition: Common
662 profiles:
663 - http
664 - tcp
665 provider:
666 server: lb.mydomain.com
667 user: admin
668 password: secret
669 delegate_to: localhost
670
671 - name: Remove HTTP profile from previous virtual
672 bigip_virtual_server:
673 name: my-virtual-server
674 partition: Common
675 profiles:
676 - tcp
677 provider:
678 server: lb.mydomain.com
679 user: admin
680 password: secret
681 delegate_to: localhost
682
683 - name: Add the HTTP profile back to the previous virtual
684 bigip_virtual_server:
685 name: my-virtual-server
686 partition: Common
687 profiles:
688 - http
689 - tcp
690 provider:
691 server: lb.mydomain.com
692 user: admin
693 password: secret
694 delegate_to: localhost
695
696 - name: Add virtual server with rate limit
697 bigip_virtual_server:
698 state: present
699 partition: Common
700 name: my-virtual-server
701 destination: 10.10.10.10
702 port: 443
703 pool: my-pool
704 snat: Automap
705 description: Test Virtual Server
706 profiles:
707 - http
708 - fix
709 - name: clientssl
710 context: server-side
711 - name: ilx
712 context: client-side
713 policies:
714 - my-ltm-policy-for-asm
715 - ltm-uri-policy
716 - ltm-policy-2
717 - ltm-policy-3
718 enabled_vlans:
719 - /Common/vlan2
720 rate_limit: 400
721 rate_limit_mode: destination
722 rate_limit_dst_mask: 32
723 provider:
724 server: lb.mydomain.net
725 user: admin
726 password: secret
727 delegate_to: localhost
728
729 - name: Add FastL4 virtual server with clone_pools
730 bigip_virtual_server:
731 destination: 1.1.1.1
732 name: fastl4_vs
733 port: 80
734 profiles:
735 - fastL4
736 state: present
737 clone_pools:
738 - pool_name: FooPool
739 context: clientside
740 provider:
741 server: lb.mydomain.net
742 user: admin
743 password: secret
744 delegate_to: localhost
745
746 - name: Add virtual with MRF router option set
747 bigip_virtual_server:
748 name: my-virtual-server
749 destination: 10.10.10.10
750 port: 443
751 partition: Common
752 profiles:
753 - http
754 - tcp
755 - name: noneg-ssl
756 context: client-side
757 - name: http2
758 context: client-side
759 - name: httprouter
760 context: all
761 provider:
762 server: lb.mydomain.net
763 user: admin
764 password: secret
765 delegate_to: localhost
766 '''
767
768 RETURN = r'''
769 description:
770 description: New description of the virtual server.
771 returned: changed
772 type: str
773 sample: This is my description
774 default_persistence_profile:
775 description: Default persistence profile set on the virtual server.
776 returned: changed
777 type: str
778 sample: /Common/dest_addr
779 destination:
780 description: Destination of the virtual server.
781 returned: changed
782 type: str
783 sample: 1.1.1.1
784 disabled:
785 description: Whether the virtual server is disabled or not.
786 returned: changed
787 type: bool
788 sample: true
789 disabled_vlans:
790 description: List of VLANs that the virtual is disabled for.
791 returned: changed
792 type: list
793 sample: ['/Common/vlan1', '/Common/vlan2']
794 enabled:
795 description: Whether the virtual server is enabled or not.
796 returned: changed
797 type: bool
798 sample: false
799 enabled_vlans:
800 description: List of VLANs that the virtual is enabled for.
801 returned: changed
802 type: list
803 sample: ['/Common/vlan5', '/Common/vlan6']
804 fallback_persistence_profile:
805 description: Fallback persistence profile set on the virtual server.
806 returned: changed
807 type: str
808 sample: /Common/source_addr
809 irules:
810 description: iRules set on the virtual server.
811 returned: changed
812 type: list
813 sample: ['/Common/irule1', '/Common/irule2']
814 pool:
815 description: Pool the virtual server is attached to.
816 returned: changed
817 type: str
818 sample: /Common/my-pool
819 policies:
820 description: List of policies attached to the virtual.
821 returned: changed
822 type: list
823 sample: ['/Common/policy1', '/Common/policy2']
824 per_flow_request_access_policy:
825 description: Per-request policy attached to the virtual.
826 returned: changed
827 type: str
828 sample: '/Common/sample_per-request_policy'
829 port:
830 description: Port the virtual server is configured to listen on.
831 returned: changed
832 type: int
833 sample: 80
834 profiles:
835 description: List of profiles set on the virtual server.
836 returned: changed
837 type: list
838 sample: [{'name': 'tcp', 'context': 'server-side'}, {'name': 'tcp-legacy', 'context': 'client-side'}]
839 snat:
840 description: SNAT setting of the virtual server.
841 returned: changed
842 type: str
843 sample: Automap
844 serverssl_use_sni:
845 description: Specifies whether SNI is enabled or disabled on the server-side SSL connection.
846 returned: changed
847 type: bool
848 sample: true
849 source:
850 description: Source address set on the virtual server, in CIDR format.
851 returned: changed
852 type: str
853 sample: 1.2.3.4/32
854 metadata:
855 description: The new value of the virtual.
856 returned: changed
857 type: dict
858 sample: {'key1': 'foo', 'key2': 'bar'}
859 address_translation:
860 description: The new value specifying whether address translation is on or off.
861 returned: changed
862 type: bool
863 sample: true
864 port_translation:
865 description: The new value specifying whether port translation is on or off.
866 returned: changed
867 type: bool
868 sample: true
869 source_port:
870 description: Specifies whether the system preserves the source port of the connection.
871 returned: changed
872 type: str
873 sample: change
874 mirror:
875 description: Specifies the system mirrors connections on each member of a redundant pair.
876 returned: changed
877 type: bool
878 sample: true
879 auto_last_hop:
880 description: Specifies the autoLasthop value of the virtual server
881 returned: changed
882 type: str
883 sample: enabled
884 ip_protocol:
885 description: The new value of the IP protocol.
886 returned: changed
887 type: int
888 sample: 6
889 firewall_enforced_policy:
890 description: The new enforcing firewall policy.
891 returned: changed
892 type: str
893 sample: /Common/my-enforced-fw
894 firewall_staged_policy:
895 description: The new staging firewall policy.
896 returned: changed
897 type: str
898 sample: /Common/my-staged-fw
899 security_log_profiles:
900 description: The new list of security log profiles.
901 returned: changed
902 type: list
903 sample: ['/Common/profile1', '/Common/profile2']
904 ip_intelligence_policy:
905 description: The new IP Intelligence Policy assigned to the virtual.
906 returned: changed
907 type: str
908 sample: /Common/ip-intelligence
909 rate_limit:
910 description: The maximum number of connections per second allowed for a virtual server.
911 returned: changed
912 type: int
913 sample: 5000
914 rate_limit_src_mask:
915 description: Specifies a mask, in bits, to be applied to the source address as part of the rate limiting.
916 returned: changed
917 type: int
918 sample: 32
919 rate_limit_dst_mask:
920 description: Specifies a mask, in bits, to be applied to the destination address as part of the rate limiting.
921 returned: changed
922 type: int
923 sample: 32
924 rate_limit_mode:
925 description: Sets the type of rate limiting to be used on the virtual server.
926 returned: changed
927 type: str
928 sample: object-source
929 clone_pools:
930 description: Pools to which virtual server copies traffic.
931 returned: changed
932 type: list
933 sample: [{'pool_name':'/Common/Pool1', 'context': 'clientside'}]
934 service_down_immediate_action:
935 description: Action to take upon the receipt of the initial SYN packet if server is Offline or Unavailable.
936 returned: changed
937 type: str
938 sample: drop
939 '''
940 import os
941 import re
942 import traceback
943 from collections import namedtuple
944 from datetime import datetime
945
946 try:
947 from packaging.version import Version
948 except ImportError:
949 HAS_PACKAGING = False
950 Version = None
951 PACKAGING_IMPORT_ERROR = traceback.format_exc()
952 else:
953 HAS_PACKAGING = True
954 PACKAGING_IMPORT_ERROR = None
955
956 from ansible.module_utils.basic import (
957 AnsibleModule, missing_required_lib, env_fallback
958 )
959 from ansible.module_utils.six import iteritems
960
961 from ..module_utils.bigip import F5RestClient
962 from ..module_utils.common import (
963 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name,
964 only_has_managed_metadata, mark_managed_by, is_empty_list
965 )
966 from ..module_utils.constants import (
967 MANAGED_BY_ANNOTATION_MODIFIED, MANAGED_BY_ANNOTATION_VERSION
968 )
969 from ..module_utils.compare import cmp_simple_list
970 from ..module_utils.icontrol import (
971 modules_provisioned, tmos_version
972 )
973 from ..module_utils.ipaddress import (
974 is_valid_ip, is_valid_ip_interface, ip_interface, validate_ip_v6_address, get_netmask, compress_address
975 )
976 from ..module_utils.teem import send_teem
977
978
979 class Parameters(AnsibleF5Parameters):
980 api_map = {
981 'sourceAddressTranslation': 'snat',
982 'fallbackPersistence': 'fallback_persistence_profile',
983 'persist': 'default_persistence_profile',
984 'vlansEnabled': 'vlans_enabled',
985 'vlansDisabled': 'vlans_disabled',
986 'profilesReference': 'profiles',
987 'policiesReference': 'policies',
988 'rules': 'irules',
989 'translateAddress': 'address_translation',
990 'translatePort': 'port_translation',
991 'ipProtocol': 'ip_protocol',
992 'fwEnforcedPolicy': 'firewall_enforced_policy',
993 'fwStagedPolicy': 'firewall_staged_policy',
994 'securityLogProfiles': 'security_log_profiles',
995 'securityNatPolicy': 'security_nat_policy',
996 'serversslUseSni': 'serverssl_use_sni',
997 'sourcePort': 'source_port',
998 'ipIntelligencePolicy': 'ip_intelligence_policy',
999 'rateLimit': 'rate_limit',
1000 'rateLimitMode': 'rate_limit_mode',
1001 'rateLimitDstMask': 'rate_limit_dst_mask',
1002 'rateLimitSrcMask': 'rate_limit_src_mask',
1003 'clonePools': 'clone_pools',
1004 'autoLasthop': 'auto_last_hop',
1005 'serviceDownImmediateAction': 'service_down_immediate_action',
1006 'perFlowRequestAccessPolicy': 'per_flow_request_access_policy',
1007 }
1008
1009 api_attributes = [
1010 'description',
1011 'destination',
1012 'disabled',
1013 'enabled',
1014 'fallbackPersistence',
1015 'ipProtocol',
1016 'metadata',
1017 'persist',
1018 'policies',
1019 'pool',
1020 'profiles',
1021 'rules',
1022 'source',
1023 'sourceAddressTranslation',
1024 'serversslUseSni',
1025 'serviceDownImmediateAction',
1026 'vlans',
1027 'vlansEnabled',
1028 'vlansDisabled',
1029 'translateAddress',
1030 'translatePort',
1031 'l2Forward',
1032 'ipForward',
1033 'stateless',
1034 'reject',
1035 'dhcpRelay',
1036 'internal',
1037 'fwEnforcedPolicy',
1038 'fwStagedPolicy',
1039 'securityLogProfiles',
1040 'securityNatPolicy',
1041 'sourcePort',
1042 'mirror',
1043 'mask',
1044 'ipIntelligencePolicy',
1045 'rateLimit',
1046 'rateLimitMode',
1047 'rateLimitDstMask',
1048 'rateLimitSrcMask',
1049 'clonePools',
1050 'autoLasthop',
1051 'perFlowRequestAccessPolicy',
1052 ]
1053
1054 updatables = [
1055 'address_translation',
1056 'description',
1057 'default_persistence_profile',
1058 'destination',
1059 'disabled_vlans',
1060 'enabled',
1061 'enabled_vlans',
1062 'fallback_persistence_profile',
1063 'ip_protocol',
1064 'irules',
1065 'metadata',
1066 'pool',
1067 'policies',
1068 'port',
1069 'port_translation',
1070 'profiles',
1071 'service_down_immediate_action',
1072 'snat',
1073 'serverssl_use_sni',
1074 'source',
1075 'type',
1076 'firewall_enforced_policy',
1077 'firewall_staged_policy',
1078 'security_log_profiles',
1079 'security_nat_policy',
1080 'source_port',
1081 'mirror',
1082 'mask',
1083 'ip_intelligence_policy',
1084 'rate_limit',
1085 'rate_limit_mode',
1086 'rate_limit_src_mask',
1087 'rate_limit_dst_mask',
1088 'clone_pools',
1089 'auto_last_hop',
1090 'per_flow_request_access_policy',
1091 ]
1092
1093 returnables = [
1094 'address_translation',
1095 'description',
1096 'default_persistence_profile',
1097 'destination',
1098 'disabled',
1099 'disabled_vlans',
1100 'enabled',
1101 'enabled_vlans',
1102 'fallback_persistence_profile',
1103 'ip_protocol',
1104 'irules',
1105 'metadata',
1106 'pool',
1107 'policies',
1108 'port',
1109 'port_translation',
1110 'profiles',
1111 'service_down_immediate_action',
1112 'snat',
1113 'serverssl_use_sni',
1114 'source',
1115 'vlans',
1116 'vlans_enabled',
1117 'vlans_disabled',
1118 'type',
1119 'firewall_enforced_policy',
1120 'firewall_staged_policy',
1121 'security_log_profiles',
1122 'security_nat_policy',
1123 'source_port',
1124 'mirror',
1125 'mask',
1126 'ip_intelligence_policy',
1127 'rate_limit',
1128 'rate_limit_mode',
1129 'rate_limit_src_mask',
1130 'rate_limit_dst_mask',
1131 'clone_pools',
1132 'auto_last_hop',
1133 'per_flow_request_access_policy',
1134 ]
1135
1136 profiles_mutex = [
1137 'sip',
1138 'sipsession',
1139 'iiop',
1140 'rtsp',
1141 'http',
1142 'diameter',
1143 'diametersession',
1144 'radius',
1145 'ftp',
1146 'tftp',
1147 'dns',
1148 'pptp',
1149 'fix',
1150 ]
1151
1152 ip_protocols_map = [
1153 ('ah', 51),
1154 ('bna', 49),
1155 ('esp', 50),
1156 ('etherip', 97),
1157 ('gre', 47),
1158 ('icmp', 1),
1159 ('ipencap', 4),
1160 ('ipv6', 41),
1161 ('ipv6-auth', 51), # not in the official list
1162 ('ipv6-crypt', 50), # not in the official list
1163 ('ipv6-icmp', 58),
1164 ('iso-ip', 80),
1165 ('mux', 18),
1166 ('ospf', 89),
1167 ('sctp', 132),
1168 ('tcp', 6),
1169 ('udp', 17),
1170 ('udplite', 136),
1171 ]
1172
1173 def _format_port_for_destination(self, ip, port):
1174 if validate_ip_v6_address(ip):
1175 result = '.{0}'.format(port)
1176 else:
1177 result = ':{0}'.format(port)
1178 return result
1179
1180 def _format_destination(self, address, port, route_domain):
1181 if port is None:
1182 if route_domain is None:
1183 result = '{0}'.format(
1184 fq_name(self.partition, address)
1185 )
1186 else:
1187 result = '{0}%{1}'.format(
1188 fq_name(self.partition, address),
1189 route_domain
1190 )
1191 else:
1192 port = self._format_port_for_destination(address, port)
1193 if route_domain is None:
1194 result = '{0}{1}'.format(
1195 fq_name(self.partition, address),
1196 port
1197 )
1198 else:
1199 result = '{0}%{1}{2}'.format(
1200 fq_name(self.partition, address),
1201 route_domain,
1202 port
1203 )
1204 return result
1205
1206 @property
1207 def ip_protocol(self):
1208 if self._values['ip_protocol'] is None:
1209 return None
1210 if self._values['ip_protocol'] == 'any':
1211 return 'any'
1212 for x in self.ip_protocols_map:
1213 if x[0] == self._values['ip_protocol']:
1214 return int(x[1])
1215 try:
1216 return int(self._values['ip_protocol'])
1217 except ValueError:
1218 raise F5ModuleError(
1219 "Specified ip_protocol was neither a number nor in the list of common protocols."
1220 )
1221
1222 @property
1223 def has_message_routing_profiles(self):
1224 if self.profiles is None:
1225 return None
1226 current = self._read_current_message_routing_profiles_from_device()
1227 result = [x['name'] for x in self.profiles if x['name'] in current]
1228 if len(result) > 0:
1229 return True
1230 return False
1231
1232 @property
1233 def has_fastl4_profiles(self):
1234 if self.profiles is None:
1235 return None
1236 current = self._read_current_fastl4_profiles_from_device()
1237 result = [x['name'] for x in self.profiles if x['name'] in current]
1238 if len(result) > 0:
1239 return True
1240 return False
1241
1242 @property
1243 def has_fasthttp_profiles(self):
1244 """Check if ``fasthttp`` profile is in API profiles
1245
1246 This method is used to determine the server type when doing comparisons
1247 in the Difference class.
1248
1249 Returns:
1250 bool: True if server has ``fasthttp`` profiles. False otherwise.
1251 """
1252 if self.profiles is None:
1253 return None
1254 current = self._read_current_fasthttp_profiles_from_device()
1255 result = [x['name'] for x in self.profiles if x['name'] in current]
1256 if len(result) > 0:
1257 return True
1258 return False
1259
1260 def _read_current_message_routing_profiles_from_device(self):
1261 result = []
1262 result += self._read_diameter_profiles_from_device()
1263 result += self._read_sip_profiles_from_device()
1264 result += self._read_legacy_sip_profiles_from_device()
1265 return result
1266
1267 def _read_diameter_profiles_from_device(self):
1268 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/diameter/".format(
1269 self.client.provider['server'],
1270 self.client.provider['server_port'],
1271 )
1272 resp = self.client.api.get(uri)
1273 try:
1274 response = resp.json()
1275 except ValueError as ex:
1276 raise F5ModuleError(str(ex))
1277
1278 if 'code' in response and response['code'] == 400:
1279 if 'message' in response:
1280 raise F5ModuleError(response['message'])
1281 else:
1282 raise F5ModuleError(resp.content)
1283 result = [x['name'] for x in response['items']]
1284 return result
1285
1286 def _read_legacy_sip_profiles_from_device(self):
1287 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/".format(
1288 self.client.provider['server'],
1289 self.client.provider['server_port'],
1290 )
1291 resp = self.client.api.get(uri)
1292 try:
1293 response = resp.json()
1294 except ValueError as ex:
1295 raise F5ModuleError(str(ex))
1296
1297 if 'code' in response and response['code'] == 400:
1298 if 'message' in response:
1299 raise F5ModuleError(response['message'])
1300 else:
1301 raise F5ModuleError(resp.content)
1302 result = [x['name'] for x in response['items']]
1303 return result
1304
1305 def _read_sip_profiles_from_device(self):
1306 version = tmos_version(self.client)
1307 if Version(version) < Version('14.0.0'):
1308 return []
1309 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/sip/profile/session/".format(
1310 self.client.provider['server'],
1311 self.client.provider['server_port'],
1312 )
1313 resp = self.client.api.get(uri)
1314 try:
1315 response = resp.json()
1316 except ValueError as ex:
1317 raise F5ModuleError(str(ex))
1318
1319 if 'code' in response and response['code'] == 400:
1320 if 'message' in response:
1321 raise F5ModuleError(response['message'])
1322 else:
1323 raise F5ModuleError(resp.content)
1324 result = [x['name'] for x in response['items']]
1325 return result
1326
1327 def _read_current_fastl4_profiles_from_device(self):
1328 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/fastl4/".format(
1329 self.client.provider['server'],
1330 self.client.provider['server_port'],
1331 )
1332 resp = self.client.api.get(uri)
1333 try:
1334 response = resp.json()
1335 except ValueError as ex:
1336 raise F5ModuleError(str(ex))
1337
1338 if 'code' in response and response['code'] == 400:
1339 if 'message' in response:
1340 raise F5ModuleError(response['message'])
1341 else:
1342 raise F5ModuleError(resp.content)
1343 result = [x['name'] for x in response['items']]
1344 return result
1345
1346 def _read_current_fasthttp_profiles_from_device(self):
1347 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/fasthttp/".format(
1348 self.client.provider['server'],
1349 self.client.provider['server_port'],
1350 )
1351 resp = self.client.api.get(uri)
1352 try:
1353 response = resp.json()
1354 except ValueError as ex:
1355 raise F5ModuleError(str(ex))
1356
1357 if 'code' in response and response['code'] == 400:
1358 if 'message' in response:
1359 raise F5ModuleError(response['message'])
1360 else:
1361 raise F5ModuleError(resp.content)
1362 result = [x['name'] for x in response['items']]
1363 return result
1364
1365 def _read_current_clientssl_profiles_from_device(self):
1366 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/".format(
1367 self.client.provider['server'],
1368 self.client.provider['server_port'],
1369 )
1370 resp = self.client.api.get(uri)
1371 try:
1372 response = resp.json()
1373 except ValueError as ex:
1374 raise F5ModuleError(str(ex))
1375
1376 if 'code' in response and response['code'] == 400:
1377 if 'message' in response:
1378 raise F5ModuleError(response['message'])
1379 else:
1380 raise F5ModuleError(resp.content)
1381 result = [x['name'] for x in response['items']]
1382 return result
1383
1384 def _read_current_serverssl_profiles_from_device(self):
1385 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/".format(
1386 self.client.provider['server'],
1387 self.client.provider['server_port'],
1388 )
1389 resp = self.client.api.get(uri)
1390 try:
1391 response = resp.json()
1392 except ValueError as ex:
1393 raise F5ModuleError(str(ex))
1394
1395 if 'code' in response and response['code'] == 400:
1396 if 'message' in response:
1397 raise F5ModuleError(response['message'])
1398 else:
1399 raise F5ModuleError(resp.content)
1400 result = [x['name'] for x in response['items']]
1401 return result
1402
1403 def _is_client_ssl_profile(self, profile):
1404 if profile['name'] in self._read_current_clientssl_profiles_from_device():
1405 return True
1406 return False
1407
1408 def _is_server_ssl_profile(self, profile):
1409 if profile['name'] in self._read_current_serverssl_profiles_from_device():
1410 return True
1411 return False
1412
1413 def _check_pool(self, item):
1414 pool = transform_name(name=fq_name(self.partition, item))
1415 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1416 self.client.provider['server'],
1417 self.client.provider['server_port'],
1418 pool
1419 )
1420 resp = self.client.api.get(uri)
1421 try:
1422 response = resp.json()
1423 except ValueError:
1424 return False
1425 if resp.status == 404 or 'code' in response and response['code'] == 404:
1426 raise F5ModuleError(
1427 'The specified pool {0} does not exist.'.format(pool)
1428 )
1429 return item
1430
1431
1432 class ApiParameters(Parameters):
1433 @property
1434 def type(self):
1435 """Attempt to determine the current server type
1436
1437 This check is very unscientific. It turns out that this information is not
1438 exactly available anywhere on a BIG-IP. Instead, we rely on a semi-reliable
1439 means for determining what the type of the virtual server is. Hopefully it
1440 always works.
1441
1442 There are a handful of attributes that can be used to determine a specific
1443 type. There are some types though that can only be determined by looking at
1444 the profiles that are assigned to them. We follow that method for those
1445 complicated types; message-routing, fasthttp, and fastl4.
1446
1447 Because type determination is an expensive operation, we cache the result
1448 from the operation.
1449
1450 Returns:
1451 string: The server type.
1452 """
1453 if self._values['type']:
1454 return self._values['type']
1455 if self.l2Forward is True:
1456 result = 'forwarding-l2'
1457 elif self.ipForward is True:
1458 result = 'forwarding-ip'
1459 elif self.stateless is True:
1460 result = 'stateless'
1461 elif self.reject is True:
1462 result = 'reject'
1463 elif self.dhcpRelay is True:
1464 result = 'dhcp'
1465 elif self.internal is True:
1466 result = 'internal'
1467 elif self.has_fasthttp_profiles:
1468 result = 'performance-http'
1469 elif self.has_fastl4_profiles:
1470 result = 'performance-l4'
1471 elif self.has_message_routing_profiles:
1472 result = 'message-routing'
1473 else:
1474 result = 'standard'
1475 self._values['type'] = result
1476 return result
1477
1478 @property
1479 def destination(self):
1480 if self._values['destination'] is None:
1481 return None
1482 destination = self.destination_tuple
1483 result = self._format_destination(destination.ip, destination.port, destination.route_domain)
1484 return result
1485
1486 @property
1487 def destination_tuple(self):
1488 Destination = namedtuple('Destination', ['ip', 'port', 'route_domain', 'mask'])
1489
1490 # Remove the partition
1491 if self._values['destination'] is None:
1492 result = Destination(ip=None, port=None, route_domain=None, mask=None)
1493 return result
1494 destination = re.sub(r'^/[a-zA-Z0-9_.-]+/', '', self._values['destination'])
1495 # Covers the following examples
1496 #
1497 # /Common/2700:bc00:1f10:101::6%2.80
1498 # 2700:bc00:1f10:101::6%2.80
1499 # 1.1.1.1%2:80
1500 # /Common/1.1.1.1%2:80
1501 # /Common/2700:bc00:1f10:101::6%2.any
1502 #
1503 pattern = r'(?P<ip>[^%]+)%(?P<route_domain>[0-9]+)[:.](?P<port>[0-9]+|any)'
1504 matches = re.search(pattern, destination)
1505 if matches:
1506 try:
1507 port = int(matches.group('port'))
1508 except ValueError:
1509 # Can be a port of "any". This only happens with IPv6
1510 port = matches.group('port')
1511 if port == 'any':
1512 port = 0
1513 result = Destination(
1514 ip=matches.group('ip'),
1515 port=port,
1516 route_domain=int(matches.group('route_domain')),
1517 mask=self.mask
1518 )
1519 return result
1520
1521 pattern = r'(?P<ip>[^%]+)%(?P<route_domain>[0-9]+)'
1522 matches = re.search(pattern, destination)
1523 if matches:
1524 result = Destination(
1525 ip=matches.group('ip'),
1526 port=None,
1527 route_domain=int(matches.group('route_domain')),
1528 mask=self.mask
1529 )
1530 return result
1531
1532 # this will match any IPV4 Address and port, no RD
1533 pattern = r'^(?P<ip>(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4]' \
1534 r'[0-9]|25[0-5])):(?P<port>[0-9]+)'
1535
1536 matches = re.search(pattern, destination)
1537 if matches:
1538 result = Destination(
1539 ip=matches.group('ip'),
1540 port=int(matches.group('port')),
1541 route_domain=None,
1542 mask=self.mask
1543 )
1544 return result
1545
1546 # match standalone IPV6 address, no port
1547 pattern = r'^([0-9a-f]{0,4}:){2,7}(:|[0-9a-f]{1,4})$'
1548 matches = re.search(pattern, destination)
1549 if matches:
1550 result = Destination(
1551 ip=destination,
1552 port=None,
1553 route_domain=None,
1554 mask=self.mask
1555 )
1556 return result
1557
1558 # match IPV6 address with port
1559 pattern = r'(?P<ip>([0-9a-f]{0,4}:){2,7}(:|[0-9a-f]{1,4}).(?P<port>[0-9]+|any))'
1560 matches = re.search(pattern, destination)
1561 if matches:
1562 ip = matches.group('ip').split('.')[0]
1563 try:
1564 port = int(matches.group('port'))
1565 except ValueError:
1566 # Can be a port of "any". This only happens with IPv6
1567 port = matches.group('port')
1568 if port == 'any':
1569 port = 0
1570 result = Destination(
1571 ip=ip,
1572 port=port,
1573 route_domain=None,
1574 mask=self.mask
1575 )
1576 return result
1577
1578 # this will match any alphanumeric Virtual Address and port
1579 pattern = r'(?P<name>^[a-zA-Z0-9_.-]+):(?P<port>[0-9]+)'
1580 matches = re.search(pattern, destination)
1581 if matches:
1582 result = Destination(
1583 ip=matches.group('name'),
1584 port=int(matches.group('port')),
1585 route_domain=None,
1586 mask=self.mask
1587 )
1588 return result
1589
1590 # this will match any alphanumeric Virtual Address
1591 pattern = r'(?P<name>^[a-zA-Z0-9_.-]+)'
1592 matches = re.search(pattern, destination)
1593 if matches:
1594 result = Destination(
1595 ip=matches.group('name'),
1596 port=None,
1597 route_domain=None,
1598 mask=self.mask
1599 )
1600 return result
1601
1602 # match IPv6 wildcard with port without RD
1603 pattern = r'(?P<ip>[^.]+).(?P<port>[0-9]+|any)'
1604 matches = re.search(pattern, destination)
1605 if matches:
1606 result = Destination(
1607 ip=matches.group('ip'),
1608 port=matches.group('port'),
1609 route_domain=None,
1610 mask=self.mask
1611 )
1612 return result
1613
1614 result = Destination(ip=None, port=None, route_domain=None, mask=None)
1615 return result
1616
1617 @property
1618 def port(self):
1619 destination = self.destination_tuple
1620 self._values['port'] = destination.port
1621 return destination.port
1622
1623 @property
1624 def route_domain(self):
1625 """Return a route domain number from the destination
1626
1627 Returns:
1628 int: The route domain number
1629 """
1630 destination = self.destination_tuple
1631 self._values['route_domain'] = destination.route_domain
1632 return int(destination.route_domain)
1633
1634 @property
1635 def profiles(self):
1636 """Returns a list of profiles from the API
1637
1638 The profiles are formatted so that they are usable in this module and
1639 are able to be compared by the Difference engine.
1640
1641 Returns:
1642 list (:obj:`list` of :obj:`dict`): List of profiles.
1643
1644 Each dictionary in the list contains the following three (3) keys.
1645
1646 * name
1647 * context
1648 * fullPath
1649
1650 Raises:
1651 F5ModuleError: If the specified context is a value other that
1652 ``all``, ``serverside``, or ``clientside``.
1653 """
1654 if 'items' not in self._values['profiles']:
1655 return None
1656 result = []
1657 prof_path = 'https://localhost/mgmt/tm/ltm/profile/'
1658 accprof_path = 'https://localhost/mgmt/tm/apm/profile/access'
1659 for item in self._values['profiles']['items']:
1660 context = item['context']
1661 name = item['name']
1662 if 'nameReference' not in item:
1663 path = item['selfLink']
1664 else:
1665 path = item['nameReference']['link']
1666 if context in ['all', 'serverside', 'clientside']:
1667 result.append(dict(name=name, context=context, fullPath=item['fullPath']))
1668 # if path.startswith(prof_path):
1669 # result.append(dict(name=name, context=context, fullPath=item['fullPath']))
1670 # if path.startswith(accprof_path):
1671 # result.append(dict(name=name, context=context, fullPath=item['fullPath']))
1672 else:
1673 raise F5ModuleError(
1674 "Unknown profile context found: '{0}'".format(context)
1675 )
1676 return result
1677
1678 @property
1679 def profile_types(self):
1680 return [x['name'] for x in iteritems(self.profiles)]
1681
1682 @property
1683 def policies(self):
1684 if 'items' not in self._values['policies']:
1685 return None
1686 result = []
1687 for item in self._values['policies']['items']:
1688 name = item['name']
1689 partition = item['partition']
1690 result.append(dict(name=name, partition=partition))
1691 return result
1692
1693 @property
1694 def default_persistence_profile(self):
1695 """Get the name of the current default persistence profile
1696
1697 These persistence profiles are always lists when we get them
1698 from the REST API even though there can only be one. We'll
1699 make it a list again when we get to the Difference engine.
1700
1701 Returns:
1702 string: The name of the default persistence profile
1703 """
1704 if self._values['default_persistence_profile'] is None:
1705 return None
1706 return self._values['default_persistence_profile'][0]
1707
1708 @property
1709 def enabled(self):
1710 if 'enabled' in self._values:
1711 return True
1712 return False
1713
1714 @property
1715 def disabled(self):
1716 if 'disabled' in self._values:
1717 return True
1718 return False
1719
1720 @property
1721 def metadata(self):
1722 if self._values['metadata'] is None:
1723 return None
1724 if only_has_managed_metadata(self._values['metadata']):
1725 return None
1726 result = []
1727 for md in self._values['metadata']:
1728 if md['name'] in [MANAGED_BY_ANNOTATION_VERSION, MANAGED_BY_ANNOTATION_MODIFIED]:
1729 continue
1730
1731 tmp = dict(name=str(md['name']))
1732 if 'value' in md:
1733 tmp['value'] = str(md['value'])
1734 else:
1735 tmp['value'] = ''
1736 result.append(tmp)
1737 return result
1738
1739 @property
1740 def security_log_profiles(self):
1741 if self._values['security_log_profiles'] is None:
1742 return None
1743 # At the moment, BIG-IP wraps the names of log profiles in double-quotes if
1744 # the profile name contains spaces. This is likely due to the REST code being
1745 # too close to actual tmsh code and, at the tmsh level, a space in the profile
1746 # name would cause tmsh to see the 2nd word (and beyond) as "the next parameter".
1747 #
1748 # This seems like a bug to me.
1749 result = list(set([x.strip('"') for x in self._values['security_log_profiles']]))
1750 result.sort()
1751 return result
1752
1753 @property
1754 def sec_nat_use_device_policy(self):
1755 if self._values['security_nat_policy'] is None:
1756 return None
1757 if 'useDevicePolicy' not in self._values['security_nat_policy']:
1758 return None
1759 if self._values['security_nat_policy']['useDevicePolicy'] == "no":
1760 return False
1761 return True
1762
1763 @property
1764 def sec_nat_use_rd_policy(self):
1765 if self._values['security_nat_policy'] is None:
1766 return None
1767 if 'useRouteDomainPolicy' not in self._values['security_nat_policy']:
1768 return None
1769 if self._values['security_nat_policy']['useRouteDomainPolicy'] == "no":
1770 return False
1771 return True
1772
1773 @property
1774 def sec_nat_policy(self):
1775 if self._values['security_nat_policy'] is None:
1776 return None
1777 if 'policy' not in self._values['security_nat_policy']:
1778 return None
1779 return self._values['security_nat_policy']['policy']
1780
1781 @property
1782 def irules(self):
1783 if self._values['irules'] is None:
1784 return []
1785 return self._values['irules']
1786
1787 @property
1788 def rate_limit(self):
1789 if self._values['rate_limit'] is None:
1790 return None
1791 if self._values['rate_limit'] == 'disabled':
1792 return 0
1793 return int(self._values['rate_limit'])
1794
1795 @property
1796 def clone_pools(self):
1797 if self._values['clone_pools'] is None:
1798 return None
1799 result = []
1800 for item in self._values['clone_pools']:
1801 pool_name = fq_name(item['partition'], item['name'])
1802 context = item['context']
1803 tmp = {
1804 'name': pool_name,
1805 'context': context
1806 }
1807 result.append(tmp)
1808 return result
1809
1810
1811 class ModuleParameters(Parameters):
1812 services_map = {
1813 'ftp': 21,
1814 'http': 80,
1815 'https': 443,
1816 'telnet': 23,
1817 'pptp': 1723,
1818 'smtp': 25,
1819 'snmp': 161,
1820 'snmp-trap': 162,
1821 'ssh': 22,
1822 'tftp': 69,
1823 'isakmp': 500,
1824 'mqtt': 1883,
1825 'mqtt-tls': 8883,
1826 'rtsp': 554
1827 }
1828
1829 def _handle_profile_context(self, tmp):
1830 if 'context' not in tmp:
1831 tmp['context'] = 'all'
1832 else:
1833 if 'name' not in tmp:
1834 raise F5ModuleError(
1835 "A profile name must be specified when a context is specified."
1836 )
1837 tmp['context'] = tmp['context'].replace('server-side', 'serverside')
1838 tmp['context'] = tmp['context'].replace('client-side', 'clientside')
1839
1840 def _handle_ssl_profile_nuances(self, profile):
1841 if self.check_profiles:
1842 if profile['name'] == 'serverssl' or self._is_server_ssl_profile(profile):
1843 if profile['context'] != 'serverside':
1844 profile['context'] = 'serverside'
1845 if profile['name'] == 'clientssl' or self._is_client_ssl_profile(profile):
1846 if profile['context'] != 'clientside':
1847 profile['context'] = 'clientside'
1848 else:
1849 if profile['name'] == 'serverssl':
1850 if profile['context'] != 'serverside':
1851 profile['context'] = 'serverside'
1852 if profile['name'] == 'clientssl':
1853 if profile['context'] != 'clientside':
1854 profile['context'] = 'clientside'
1855
1856 def _check_port(self):
1857 try:
1858 port = int(self._values['port'])
1859 except ValueError:
1860 raise F5ModuleError(
1861 "The specified port was not a valid integer"
1862 )
1863 if 0 <= port <= 65535:
1864 return port
1865 raise F5ModuleError(
1866 "Valid ports must be in range 0 - 65535"
1867 )
1868
1869 def _check_clone_pool_contexts(self):
1870 client = 0
1871 server = 0
1872 for item in self._values['clone_pools']:
1873 if item['context'] == 'clientside':
1874 client += 1
1875 if item['context'] == 'serverside':
1876 server += 1
1877 if client > 1 or server > 1:
1878 raise F5ModuleError(
1879 'You must specify only one clone pool for each context.'
1880 )
1881
1882 @property
1883 def check_profiles(self):
1884 result = flatten_boolean(self._values['check_profiles'])
1885 if result == 'yes':
1886 return True
1887 return False
1888
1889 @property
1890 def bypass_module_checks(self):
1891 result = flatten_boolean(self._values['bypass_module_checks'])
1892 if result == 'yes':
1893 return True
1894 return False
1895
1896 @property
1897 def source(self):
1898 if self._values['source'] is None:
1899 return None
1900 source = self.source_tuple
1901 if is_valid_ip_interface(u'{0}/{1}'.format(source.ip, source.cidr)):
1902 if source.route_domain:
1903 result = '{0}%{1}/{2}'.format(source.ip, source.route_domain, source.cidr)
1904 else:
1905 result = '{0}/{1}'.format(source.ip, source.cidr)
1906 return result
1907 raise F5ModuleError(
1908 "The source IP address must be a valid CIDR format: address/prefix."
1909 )
1910
1911 @property
1912 def source_tuple(self):
1913 Source = namedtuple('Source', ['ip', 'route_domain', 'cidr'])
1914 if self._values['source'] is None:
1915 result = Source(ip=None, route_domain=None, cidr=None)
1916 return result
1917 # match source with RD
1918 pattern = r'(?P<ip>[^%]+)%(?P<route_domain>[0-9]+)/(?P<cidr>[0-9]+)'
1919 matches = re.search(pattern, self._values['source'])
1920 if matches:
1921 result = Source(
1922 ip=matches.group('ip'),
1923 route_domain=matches.group('route_domain'),
1924 cidr=matches.group('cidr')
1925 )
1926 return result
1927 # match source without RD
1928 pattern = r'(?P<ip>[^%]+)/(?P<cidr>[0-9]+)'
1929 matches = re.search(pattern, self._values['source'])
1930 if matches:
1931 result = Source(
1932 ip=matches.group('ip'),
1933 route_domain=None,
1934 cidr=matches.group('cidr')
1935 )
1936 return result
1937
1938 result = Source(ip=None, route_domain=None, cidr=None)
1939 return result
1940
1941 @property
1942 def destination(self):
1943 pattern = r'^[a-zA-Z0-9_.-]+'
1944 if len(self._values['destination'].split('/')) > 1:
1945 addr, dud = self._values['destination'].split('/')
1946 if '%' in addr:
1947 addr = addr.split('%')[0]
1948 else:
1949 addr = self._values['destination'].split('%')[0]
1950 if not is_valid_ip(addr):
1951 matches = re.search(pattern, addr)
1952 if not matches:
1953 raise F5ModuleError(
1954 "The provided destination is not a valid IP address or a Virtual Address name."
1955 )
1956 result = self._format_destination(addr, self.port, self.route_domain)
1957 return result
1958
1959 @property
1960 def route_domain(self):
1961 if self._values['destination'] is None:
1962 return None
1963 result = None
1964 if len(self._values['destination'].split('/')) > 1:
1965 addr, dud = self._values['destination'].split('/')
1966 if '%' in addr:
1967 result = addr.split('%')
1968 else:
1969 result = self._values['destination'].split('%')
1970 if result and len(result) > 1:
1971 pattern = r'^[a-zA-Z0-9_.-]+'
1972 matches = re.search(pattern, result[0])
1973 if matches and not is_valid_ip(result[0]):
1974 # we need to strip RD because when using Virtual Address names the RD is not needed.
1975 return None
1976 return int(result[1])
1977 return None
1978
1979 @property
1980 def destination_tuple(self):
1981 pattern = r'^[a-zA-Z0-9_.-]+'
1982 Destination = namedtuple('Destination', ['ip', 'port', 'route_domain', 'mask', 'not_ip'])
1983 if self._values['destination'] is None:
1984 result = Destination(ip=None, port=None, route_domain=None, mask=None, not_ip=None)
1985 return result
1986 addr = self._values['destination'].split("%")[0].split('/')[0]
1987 if is_valid_ip(addr):
1988 addr = compress_address(u'{0}'.format(addr))
1989 result = Destination(ip=addr, port=self.port, route_domain=self.route_domain, mask=self.mask, not_ip=False)
1990 return result
1991 else:
1992 matches = re.search(pattern, addr)
1993 if matches:
1994 result = Destination(ip=addr, port=self.port, route_domain=self.route_domain,
1995 mask=self.mask, not_ip=True)
1996 return result
1997 result = Destination(ip=addr, port=self.port, route_domain=self.route_domain, mask=self.mask, not_ip=False)
1998 return result
1999
2000 @property
2001 def mask(self):
2002 if self._values['destination'] is None:
2003 return None
2004 if len(self._values['destination'].split('/')) > 1:
2005 addr, cidr = self._values['destination'].split('/')
2006 if '%' in addr:
2007 addr = addr.split('%')[0] + '/' + cidr
2008 else:
2009 addr = self._values['destination']
2010 else:
2011 addr = self._values['destination'].split('%')[0]
2012 if addr in ['0.0.0.0', '0.0.0.0/any', '0.0.0.0/0']:
2013 return 'any'
2014 if addr in ['::', '::/0', '::/any6']:
2015 return 'any6'
2016 if self._values['mask'] is None:
2017 if is_valid_ip_interface(addr):
2018 return get_netmask(addr)
2019 else:
2020 return None
2021 return compress_address(self._values['mask'])
2022
2023 @property
2024 def port(self):
2025 if self._values['port'] is None:
2026 return None
2027 if self._values['port'] in ['*', 'any', '0']:
2028 return 0
2029 if self._values['port'] in self.services_map:
2030 port = self._values['port']
2031 self._values['port'] = self.services_map[port]
2032 self._check_port()
2033 return int(self._values['port'])
2034
2035 @property
2036 def irules(self):
2037 results = []
2038 if self._values['irules'] is None:
2039 return None
2040 if is_empty_list(self._values['irules']):
2041 return ''
2042 for irule in self._values['irules']:
2043 result = fq_name(self.partition, irule)
2044 results.append(result)
2045 return results
2046
2047 @property
2048 def profiles(self):
2049 if self._values['profiles'] is None:
2050 return None
2051 if is_empty_list(self._values['profiles']):
2052 return ''
2053 result = []
2054 for profile in self._values['profiles']:
2055 tmp = dict()
2056 if isinstance(profile, dict):
2057 tmp.update(profile)
2058 self._handle_profile_context(tmp)
2059 tmp['name'] = profile
2060 if 'name' in profile:
2061 tmp['name'] = profile['name']
2062 if 'partition' not in profile:
2063 if isinstance(tmp['name'], str) and len(tmp["name"].split("/")) > 1:
2064 tmp["partition"] = tmp["name"].split("/")[1]
2065 tmp['name'] = os.path.basename(tmp['name'])
2066 else:
2067 tmp['partition'] = "Common"
2068 tmp['fullPath'] = fq_name(tmp['partition'], tmp['name'])
2069 if not self.bypass_module_checks:
2070 self._handle_ssl_profile_nuances(tmp)
2071 else:
2072 if len(profile.split("/")) > 1:
2073 full_path = profile
2074 tmp["partition"] = profile.split("/")[1]
2075 else:
2076 full_path = fq_name("Common", profile)
2077 tmp["partition"] = "Common"
2078 tmp['name'] = os.path.basename(profile)
2079 tmp['context'] = 'all'
2080 tmp['fullPath'] = full_path
2081 if not self.bypass_module_checks:
2082 self._handle_ssl_profile_nuances(tmp)
2083 result.append(tmp)
2084 mutually_exclusive = [x['name'] for x in result if x in self.profiles_mutex]
2085 if len(mutually_exclusive) > 1:
2086 raise F5ModuleError(
2087 "Profiles {0} are mutually exclusive".format(
2088 ', '.join(self.profiles_mutex).strip()
2089 )
2090 )
2091 return result
2092
2093 @property
2094 def policies(self):
2095 if self._values['policies'] is None:
2096 return None
2097 if is_empty_list(self._values['policies']):
2098 return ''
2099 result = []
2100 policies = [fq_name(self.partition, p) for p in self._values['policies']]
2101 policies = set(policies)
2102 for policy in policies:
2103 parts = policy.split('/')
2104 if len(parts) != 3:
2105 raise F5ModuleError(
2106 "The specified policy '{0}' is malformed".format(policy)
2107 )
2108 tmp = dict(
2109 name=parts[2],
2110 partition=parts[1]
2111 )
2112 result.append(tmp)
2113 return result
2114
2115 @property
2116 def pool(self):
2117 if self._values['pool'] is None:
2118 return None
2119 if self._values['pool'] == '':
2120 return ''
2121 return fq_name(self.partition, self._values['pool'])
2122
2123 @property
2124 def vlans_enabled(self):
2125 if self._values['enabled_vlans'] is None:
2126 return None
2127 elif self._values['vlans_enabled'] is False:
2128 # This is a special case for "all" enabled VLANs
2129 return False
2130 if self._values['disabled_vlans'] is None:
2131 return True
2132 return False
2133
2134 @property
2135 def vlans_disabled(self):
2136 if self._values['disabled_vlans'] is None:
2137 return None
2138 elif self._values['vlans_disabled'] is True:
2139 # This is a special case for "all" enabled VLANs
2140 return True
2141 elif self._values['enabled_vlans'] is None:
2142 return True
2143 return False
2144
2145 @property
2146 def enabled_vlans(self):
2147 if self._values['enabled_vlans'] is None:
2148 return None
2149 elif any(x.lower() for x in self._values['enabled_vlans'] if x.lower() in ['all', '*']):
2150 result = [fq_name(self.partition, 'all')]
2151 return result
2152 results = list(set([fq_name(self.partition, x) for x in self._values['enabled_vlans']]))
2153 results.sort()
2154 return results
2155
2156 @property
2157 def disabled_vlans(self):
2158 if self._values['disabled_vlans'] is None:
2159 return None
2160 elif any(x.lower() for x in self._values['disabled_vlans'] if x.lower() in ['all', '*']):
2161 raise F5ModuleError(
2162 "You cannot disable all VLANs. You must name them individually."
2163 )
2164 results = list(set([fq_name(self.partition, x) for x in self._values['disabled_vlans']]))
2165 results.sort()
2166 return results
2167
2168 @property
2169 def vlans(self):
2170 disabled = self.disabled_vlans
2171 if disabled:
2172 return self.disabled_vlans
2173 return self.enabled_vlans
2174
2175 @property
2176 def state(self):
2177 if self._values['state'] == 'present':
2178 return 'enabled'
2179 return self._values['state']
2180
2181 @property
2182 def snat(self):
2183 if self._values['snat'] is None:
2184 return None
2185 lowercase = self._values['snat'].lower()
2186 if lowercase in ['automap', 'none']:
2187 return dict(type=lowercase)
2188 snat_pool = fq_name(self.partition, self._values['snat'])
2189 return dict(pool=snat_pool, type='snat')
2190
2191 @property
2192 def serverssl_use_sni(self):
2193 if self._values['serverssl_use_sni'] is None:
2194 return None
2195 if self._values['serverssl_use_sni']:
2196 return 'enabled'
2197 return 'disabled'
2198
2199 @property
2200 def default_persistence_profile(self):
2201 if self._values['default_persistence_profile'] is None:
2202 return None
2203 if self._values['default_persistence_profile'] == '':
2204 return ''
2205 profile = fq_name(self.partition, self._values['default_persistence_profile'])
2206 parts = profile.split('/')
2207 if len(parts) != 3:
2208 raise F5ModuleError(
2209 "The specified 'default_persistence_profile' is malformed"
2210 )
2211 result = dict(
2212 name=parts[2],
2213 partition=parts[1]
2214 )
2215 return result
2216
2217 @property
2218 def fallback_persistence_profile(self):
2219 if self._values['fallback_persistence_profile'] is None:
2220 return None
2221 if self._values['fallback_persistence_profile'] == '':
2222 return ''
2223 result = fq_name(self.partition, self._values['fallback_persistence_profile'])
2224 return result
2225
2226 @property
2227 def enabled(self):
2228 if self._values['state'] == 'enabled':
2229 return True
2230 elif self._values['state'] == 'disabled':
2231 return False
2232 else:
2233 return None
2234
2235 @property
2236 def disabled(self):
2237 if self._values['state'] == 'enabled':
2238 return False
2239 elif self._values['state'] == 'disabled':
2240 return True
2241 else:
2242 return None
2243
2244 @property
2245 def metadata(self):
2246 if self._values['metadata'] is None:
2247 return None
2248 if self._values['metadata'] == '':
2249 return []
2250 result = []
2251 try:
2252 for k, v in iteritems(self._values['metadata']):
2253 tmp = dict(name=str(k))
2254 if v:
2255 tmp['value'] = str(v)
2256 else:
2257 tmp['value'] = ''
2258 result.append(tmp)
2259 except AttributeError:
2260 raise F5ModuleError(
2261 "The 'metadata' parameter must be a dictionary of key/value pairs."
2262 )
2263 return result
2264
2265 @property
2266 def address_translation(self):
2267 if self._values['address_translation'] is None:
2268 return None
2269 if self._values['address_translation']:
2270 return 'enabled'
2271 return 'disabled'
2272
2273 @property
2274 def port_translation(self):
2275 if self._values['port_translation'] is None:
2276 return None
2277 if self._values['port_translation']:
2278 return 'enabled'
2279 return 'disabled'
2280
2281 @property
2282 def firewall_enforced_policy(self):
2283 if self._values['firewall_enforced_policy'] is None:
2284 return None
2285 return fq_name(self.partition, self._values['firewall_enforced_policy'])
2286
2287 @property
2288 def firewall_staged_policy(self):
2289 if self._values['firewall_staged_policy'] is None:
2290 return None
2291 return fq_name(self.partition, self._values['firewall_staged_policy'])
2292
2293 @property
2294 def ip_intelligence_policy(self):
2295 if self._values['ip_intelligence_policy'] is None:
2296 return None
2297 if self._values['ip_intelligence_policy'] in ['', 'none']:
2298 return ''
2299 return fq_name(self.partition, self._values['ip_intelligence_policy'])
2300
2301 @property
2302 def security_log_profiles(self):
2303 if self._values['security_log_profiles'] is None:
2304 return None
2305 if len(self._values['security_log_profiles']) == 1 and self._values['security_log_profiles'][0] == '':
2306 return ''
2307 result = list(set([fq_name(self.partition, x) for x in self._values['security_log_profiles']]))
2308 result.sort()
2309 return result
2310
2311 @property
2312 def sec_nat_use_device_policy(self):
2313 if self._values['security_nat_policy'] is None:
2314 return None
2315 if 'use_device_policy' not in self._values['security_nat_policy']:
2316 return None
2317 return self._values['security_nat_policy']['use_device_policy']
2318
2319 @property
2320 def sec_nat_use_rd_policy(self):
2321 if self._values['security_nat_policy'] is None:
2322 return None
2323 if 'use_route_domain_policy' not in self._values['security_nat_policy']:
2324 return None
2325 return self._values['security_nat_policy']['use_route_domain_policy']
2326
2327 @property
2328 def sec_nat_policy(self):
2329 if self._values['security_nat_policy'] is None:
2330 return None
2331 if 'policy' not in self._values['security_nat_policy']:
2332 return None
2333 if self._values['security_nat_policy']['policy'] == '':
2334 return ''
2335 return fq_name(self.partition, self._values['security_nat_policy']['policy'])
2336
2337 @property
2338 def security_nat_policy(self):
2339 result = dict()
2340 if self.sec_nat_policy:
2341 result['policy'] = self.sec_nat_policy
2342 if self.sec_nat_use_device_policy is not None:
2343 result['use_device_policy'] = self.sec_nat_use_device_policy
2344 if self.sec_nat_use_rd_policy is not None:
2345 result['use_route_domain_policy'] = self.sec_nat_use_rd_policy
2346 if result:
2347 return result
2348 return None
2349
2350 @property
2351 def mirror(self):
2352 result = flatten_boolean(self._values['mirror'])
2353 if result is None:
2354 return None
2355 if result == 'yes':
2356 return 'enabled'
2357 return 'disabled'
2358
2359 @property
2360 def rate_limit(self):
2361 if self._values['rate_limit'] is None:
2362 return None
2363 if 0 <= int(self._values['rate_limit']) <= 4294967295:
2364 return int(self._values['rate_limit'])
2365 raise F5ModuleError(
2366 "Valid 'rate_limit' must be in range 0 - 4294967295."
2367 )
2368
2369 @property
2370 def rate_limit_src_mask(self):
2371 if self._values['rate_limit_src_mask'] is None:
2372 return None
2373 if 0 <= int(self._values['rate_limit_src_mask']) <= 4294967295:
2374 return int(self._values['rate_limit_src_mask'])
2375 raise F5ModuleError(
2376 "Valid 'rate_limit_src_mask' must be in range 0 - 4294967295."
2377 )
2378
2379 @property
2380 def rate_limit_dst_mask(self):
2381 if self._values['rate_limit_dst_mask'] is None:
2382 return None
2383 if 0 <= int(self._values['rate_limit_dst_mask']) <= 4294967295:
2384 return int(self._values['rate_limit_dst_mask'])
2385 raise F5ModuleError(
2386 "Valid 'rate_limit_dst_mask' must be in range 0 - 4294967295."
2387 )
2388
2389 @property
2390 def clone_pools(self):
2391 if self._values['clone_pools'] is None:
2392 return None
2393 if not self._values['clone_pools']:
2394 return []
2395 self._check_clone_pool_contexts()
2396 result = []
2397 for item in self._values['clone_pools']:
2398 pool_name = fq_name(self.partition, self._check_pool(item['pool_name']))
2399 context = item['context']
2400 tmp = {
2401 'name': pool_name,
2402 'context': context
2403 }
2404 result.append(tmp)
2405 return result
2406
2407
2408 class Changes(Parameters):
2409 def to_return(self):
2410 result = {}
2411 for returnable in self.returnables:
2412 try:
2413 result[returnable] = getattr(self, returnable)
2414 except Exception:
2415 raise
2416 result = self._filter_params(result)
2417 return result
2418
2419
2420 class UsableChanges(Changes):
2421 @property
2422 def destination(self):
2423 if self._values['type'] == 'internal':
2424 return None
2425 return self._values['destination']
2426
2427 @property
2428 def vlans(self):
2429 if self._values['vlans'] is None:
2430 return None
2431 elif len(self._values['vlans']) == 0:
2432 return []
2433 elif any(x for x in self._values['vlans'] if x.lower() in ['/common/all', 'all']):
2434 return []
2435 return self._values['vlans']
2436
2437 @property
2438 def irules(self):
2439 if self._values['irules'] is None:
2440 return None
2441 if self._values['type'] in ['dhcp', 'stateless', 'reject', 'internal']:
2442 return None
2443 if self._values['irules'] == '':
2444 return []
2445 return self._values['irules']
2446
2447 @property
2448 def policies(self):
2449 if self._values['policies'] is None:
2450 return None
2451 if self._values['type'] in ['dhcp', 'reject', 'internal']:
2452 return None
2453 if self._values['policies'] == '':
2454 return []
2455 return self._values['policies']
2456
2457 @property
2458 def default_persistence_profile(self):
2459 if self._values['default_persistence_profile'] is None:
2460 return None
2461 if self._values['type'] == 'dhcp':
2462 return None
2463 if not self._values['default_persistence_profile']:
2464 return []
2465 return [self._values['default_persistence_profile']]
2466
2467 @property
2468 def fallback_persistence_profile(self):
2469 if self._values['fallback_persistence_profile'] is None:
2470 return None
2471 if self._values['type'] == 'dhcp':
2472 return None
2473 return self._values['fallback_persistence_profile']
2474
2475 @property
2476 def snat(self):
2477 if self._values['snat'] is None:
2478 return None
2479 if self._values['type'] in ['dhcp', 'reject', 'internal']:
2480 return None
2481 return self._values['snat']
2482
2483 @property
2484 def dhcpRelay(self):
2485 if self._values['type'] == 'dhcp':
2486 return True
2487
2488 @property
2489 def reject(self):
2490 if self._values['type'] == 'reject':
2491 return True
2492
2493 @property
2494 def stateless(self):
2495 if self._values['type'] == 'stateless':
2496 return True
2497
2498 @property
2499 def internal(self):
2500 if self._values['type'] == 'internal':
2501 return True
2502
2503 @property
2504 def ipForward(self):
2505 if self._values['type'] == 'forwarding-ip':
2506 return True
2507
2508 @property
2509 def l2Forward(self):
2510 if self._values['type'] == 'forwarding-l2':
2511 return True
2512
2513 @property
2514 def security_log_profiles(self):
2515 if self._values['security_log_profiles'] is None:
2516 return None
2517 mutex = ('Log all requests', 'Log illegal requests')
2518 if len([x for x in self._values['security_log_profiles'] if x.endswith(mutex)]) >= 2:
2519 raise F5ModuleError(
2520 "The 'Log all requests' and 'Log illegal requests' are mutually exclusive."
2521 )
2522 return self._values['security_log_profiles']
2523
2524 @property
2525 def security_nat_policy(self):
2526 if self._values['security_nat_policy'] is None:
2527 return None
2528 result = dict()
2529 sec = self._values['security_nat_policy']
2530 if 'policy' in sec:
2531 result['policy'] = sec['policy']
2532 if 'use_device_policy' in sec:
2533 result['useDevicePolicy'] = 'yes' if sec['use_device_policy'] else 'no'
2534 if 'use_route_domain_policy' in sec:
2535 result['useRouteDomainPolicy'] = 'yes' if sec['use_route_domain_policy'] else 'no'
2536 if result:
2537 return result
2538 return None
2539
2540
2541 class ReportableChanges(Changes):
2542 @property
2543 def mirror(self):
2544 if self._values['mirror'] is None:
2545 return None
2546 elif self._values['mirror'] == 'enabled':
2547 return 'yes'
2548 return 'no'
2549
2550 @property
2551 def snat(self):
2552 if self._values['snat'] is None:
2553 return None
2554 result = self._values['snat'].get('type', None)
2555 if result == 'automap':
2556 return 'Automap'
2557 elif result == 'none':
2558 return 'none'
2559 result = self._values['snat'].get('pool', None)
2560 return result
2561
2562 @property
2563 def serverssl_use_sni(self):
2564 if self._values['serverssl_use_sni'] is None:
2565 return None
2566 if self._values['serverssl_use_sni'] == 'enabled':
2567 return True
2568 return False
2569
2570 @property
2571 def destination(self):
2572 params = ApiParameters(params=dict(destination=self._values['destination']))
2573 result = params.destination_tuple.ip
2574 return result
2575
2576 @property
2577 def port(self):
2578 params = ApiParameters(params=dict(destination=self._values['destination']))
2579 result = params.destination_tuple.port
2580 return result
2581
2582 @property
2583 def default_persistence_profile(self):
2584 if self._values['default_persistence_profile'] is None:
2585 return None
2586 if len(self._values['default_persistence_profile']) == 0:
2587 return []
2588 profile = self._values['default_persistence_profile'][0]
2589 result = '/{0}/{1}'.format(profile['partition'], profile['name'])
2590 return result
2591
2592 @property
2593 def policies(self):
2594 if self._values['policies'] is None:
2595 return None
2596 if len(self._values['policies']) == 0:
2597 return []
2598 if len(self._values['policies']) == 1 and self._values['policies'][0] == '':
2599 return ''
2600 result = ['/{0}/{1}'.format(x['partition'], x['name']) for x in self._values['policies']]
2601 return result
2602
2603 @property
2604 def irules(self):
2605 if self._values['irules'] is None:
2606 return None
2607 if len(self._values['irules']) == 0:
2608 return []
2609 if len(self._values['irules']) == 1 and self._values['irules'][0] == '':
2610 return ''
2611 return self._values['irules']
2612
2613 @property
2614 def enabled_vlans(self):
2615 if self._values['vlans'] is None:
2616 return None
2617 if len(self._values['vlans']) == 0 and self._values['vlans_disabled'] is True:
2618 return 'all'
2619 elif len(self._values['vlans']) > 0 and self._values['vlans_enabled'] is True:
2620 return self._values['vlans']
2621
2622 @property
2623 def disabled_vlans(self):
2624 if self._values['vlans'] is None:
2625 return None
2626 if len(self._values['vlans']) > 0 and self._values['vlans_disabled'] is True:
2627 return self._values['vlans']
2628
2629 @property
2630 def address_translation(self):
2631 if self._values['address_translation'] is None:
2632 return None
2633 if self._values['address_translation'] == 'enabled':
2634 return True
2635 return False
2636
2637 @property
2638 def port_translation(self):
2639 if self._values['port_translation'] is None:
2640 return None
2641 if self._values['port_translation'] == 'enabled':
2642 return True
2643 return False
2644
2645 @property
2646 def ip_protocol(self):
2647 if self._values['ip_protocol'] is None:
2648 return None
2649 try:
2650 int(self._values['ip_protocol'])
2651 except ValueError:
2652 return self._values['ip_protocol']
2653
2654 protocol = next((x[0] for x in self.ip_protocols_map if x[1] == self._values['ip_protocol']), None)
2655 if protocol:
2656 return protocol
2657 return self._values['ip_protocol']
2658
2659
2660 class VirtualServerValidator(object):
2661 def __init__(self, module=None, client=None, want=None, have=None):
2662 self.have = have if have else ApiParameters()
2663 self.want = want if want else ModuleParameters()
2664 self.client = client
2665 self.module = module
2666
2667 def check_update(self):
2668 # Regular checks
2669 self._override_port_by_type()
2670 self._override_protocol_by_type()
2671 self._verify_type_has_correct_profiles()
2672 self._verify_default_persistence_profile_for_type()
2673 self._verify_fallback_persistence_profile_for_type()
2674 self._update_persistence_profile()
2675 self._ensure_server_type_supports_vlans()
2676 self._verify_type_has_correct_ip_protocol()
2677
2678 # For different server types
2679 self._verify_dhcp_profile()
2680 self._verify_fastl4_profile()
2681 self._verify_stateless_profile()
2682
2683 def check_create(self):
2684 # Regular checks
2685 self._verify_virtual_has_required_parameters()
2686 self._set_default_ip_protocol()
2687 self._set_default_profiles()
2688 self._override_port_by_type()
2689 self._override_protocol_by_type()
2690 self._verify_type_has_correct_profiles()
2691 self._verify_default_persistence_profile_for_type()
2692 self._verify_fallback_persistence_profile_for_type()
2693 self._update_persistence_profile()
2694 self._ensure_server_type_supports_vlans()
2695 self._override_vlans_if_all_specified()
2696 self._check_source_and_destination_match()
2697 self._verify_type_has_correct_ip_protocol()
2698 self._verify_minimum_profile()
2699
2700 # For different server types
2701 self._verify_dhcp_profile()
2702 self._verify_fastl4_profile()
2703 self._verify_stateless_profile_on_create()
2704
2705 def _ensure_server_type_supports_vlans(self):
2706 """Verifies the specified server type supports VLANs
2707
2708 A select number of server types do not support VLANs. This method
2709 checks to see if the specified types were provided along with VLANs.
2710 If they were, the module will raise an error informing the user that
2711 they need to either remove the VLANs, or, change the ``type``.
2712
2713 Returns:
2714 None: Returned if no VLANs are specified.
2715 Raises:
2716 F5ModuleError: Raised if the server type conflicts with VLANs.
2717 """
2718 if self.want.enabled_vlans is None:
2719 return
2720 if self.want.type == 'internal':
2721 raise F5ModuleError(
2722 "The 'internal' server type does not support VLANs."
2723 )
2724
2725 def _override_vlans_if_all_specified(self):
2726 """Overrides any specified VLANs if "all" VLANs are specified
2727
2728 The special setting "all VLANs" in a BIG-IP requires that no other VLANs
2729 be specified. If you specify any number of VLANs, AND include the "all"
2730 VLAN, this method will erase all of the other VLANs and only return the
2731 "all" VLAN.
2732 """
2733 all_vlans = ['/common/all', 'all']
2734 if self.want.enabled_vlans is not None:
2735 if any(x for x in self.want.enabled_vlans if x.lower() in all_vlans):
2736 self.want.update(
2737 dict(
2738 enabled_vlans=[],
2739 vlans_disabled=True,
2740 vlans_enabled=False
2741 )
2742 )
2743
2744 def _override_port_by_type(self):
2745 if self.want.type == 'dhcp':
2746 self.want.update({'port': 67})
2747 elif self.want.type == 'internal':
2748 self.want.update({'port': 0})
2749
2750 def _override_protocol_by_type(self):
2751 if self.want.type in ['stateless']:
2752 self.want.update({'ip_protocol': 17})
2753
2754 def _check_source_and_destination_match(self):
2755 """Verify that destination and source are of the same IP version
2756
2757 BIG-IP does not allow for mixing of the IP versions for destination and
2758 source addresses. For example, a destination IPv6 address cannot be
2759 associated with a source IPv4 address.
2760
2761 This method checks that you specified the same IP version for these
2762 parameters.
2763
2764 This method will not do this check if the virtual address name is used.
2765
2766 Raises:
2767 F5ModuleError: Raised when the IP versions of source and destination differ.
2768 """
2769 if self.want.source and self.want.destination and not self.want.destination_tuple.not_ip:
2770 want = ip_interface(u'{0}/{1}'.format(self.want.source_tuple.ip, self.want.source_tuple.cidr))
2771 have = ip_interface(u'{0}'.format(self.want.destination_tuple.ip))
2772 if want.version != have.version:
2773 raise F5ModuleError(
2774 "The source and destination addresses for the virtual server "
2775 "must be be the same type (IPv4 or IPv6)."
2776 )
2777
2778 def _verify_type_has_correct_ip_protocol(self):
2779 if self.want.ip_protocol is None:
2780 return
2781 if self.want.type == 'standard':
2782 # Standard supports
2783 # - tcp
2784 # - udp
2785 # - sctp
2786 # - ipsec-ah
2787 # - ipsec esp
2788 # - all protocols
2789 if self.want.ip_protocol not in [6, 17, 132, 51, 50, 'any']:
2790 raise F5ModuleError(
2791 "The 'standard' server type does not support the specified 'ip_protocol'."
2792 )
2793 elif self.want.type == 'performance-http':
2794 # Perf HTTP supports
2795 #
2796 # - tcp
2797 if self.want.ip_protocol not in [6]:
2798 raise F5ModuleError(
2799 "The 'performance-http' server type does not support the specified 'ip_protocol'."
2800 )
2801 elif self.want.type == 'stateless':
2802 # Stateless supports
2803 #
2804 # - udp
2805 if self.want.ip_protocol not in [17]:
2806 raise F5ModuleError(
2807 "The 'stateless' server type does not support the specified 'ip_protocol'."
2808 )
2809 elif self.want.type == 'dhcp':
2810 # DHCP supports no IP protocols
2811 if self.want.ip_protocol is not None:
2812 raise F5ModuleError(
2813 "The 'dhcp' server type does not support an 'ip_protocol'."
2814 )
2815 elif self.want.type == 'internal':
2816 # Internal supports
2817 #
2818 # - tcp
2819 # - udp
2820 if self.want.ip_protocol not in [6, 17]:
2821 raise F5ModuleError(
2822 "The 'internal' server type does not support the specified 'ip_protocol'."
2823 )
2824 elif self.want.type == 'message-routing':
2825 # Message Routing supports
2826 #
2827 # - tcp
2828 # - udp
2829 # - sctp
2830 # - all protocols
2831 if self.want.ip_protocol not in [6, 17, 132, 'all', 'any']:
2832 raise F5ModuleError(
2833 "The 'message-routing' server type does not support the specified 'ip_protocol'."
2834 )
2835
2836 def _verify_virtual_has_required_parameters(self):
2837 """Verify that the virtual has required parameters
2838
2839 Virtual servers require several parameters that are not necessarily required
2840 when updating the virtual. This method will check for the required params
2841 upon creation.
2842
2843 Ansible supports ``default`` variables in an Argument Spec, but those defaults
2844 apply to all operations; including create, update, and delete. Since users are not
2845 required to always specify these parameters, we cannot use Ansible's facility.
2846 If we did, and then users would be required to provide them when, for example,
2847 they attempted to delete a virtual (even though they are not required to delete
2848 a virtual.
2849
2850 Raises:
2851 F5ModuleError: Raised when the user did not specify required parameters.
2852 """
2853 required_resources = ['destination', 'port']
2854 if self.want.type == 'internal':
2855 return
2856 if all(getattr(self.want, v) is None for v in required_resources):
2857 raise F5ModuleError(
2858 "You must specify both of " + ', '.join(required_resources)
2859 )
2860
2861 def _verify_default_persistence_profile_for_type(self):
2862 """Verify that the server type supports default persistence profiles
2863
2864 Verifies that the specified server type supports default persistence profiles.
2865 Some virtual servers do not support these types of profiles. This method will
2866 check that the type actually supports what you are sending it.
2867
2868 Types that do not, at this time, support default persistence profiles include,
2869
2870 * dhcp
2871 * message-routing
2872 * reject
2873 * stateless
2874 * forwarding-ip
2875 * forwarding-l2
2876
2877 Raises:
2878 F5ModuleError: Raised if server type does not support default persistence profiles.
2879 """
2880 default_profile_not_allowed = [
2881 'dhcp', 'message-routing', 'reject', 'stateless', 'forwarding-ip', 'forwarding-l2'
2882 ]
2883 if self.want.ip_protocol in default_profile_not_allowed:
2884 raise F5ModuleError(
2885 "The '{0}' server type does not support a 'default_persistence_profile'".format(self.want.type)
2886 )
2887
2888 def _verify_fallback_persistence_profile_for_type(self):
2889 """Verify that the server type supports fallback persistence profiles
2890
2891 Verifies that the specified server type supports fallback persistence profiles.
2892 Some virtual servers do not support these types of profiles. This method will
2893 check that the type actually supports what you are sending it.
2894
2895 Types that do not, at this time, support fallback persistence profiles include,
2896
2897 * dhcp
2898 * message-routing
2899 * reject
2900 * stateless
2901 * forwarding-ip
2902 * forwarding-l2
2903 * performance-http
2904
2905 Raises:
2906 F5ModuleError: Raised if server type does not support fallback persistence profiles.
2907 """
2908 default_profile_not_allowed = [
2909 'dhcp', 'message-routing', 'reject', 'stateless', 'forwarding-ip', 'forwarding-l2',
2910 'performance-http'
2911 ]
2912 if self.want.ip_protocol in default_profile_not_allowed:
2913 raise F5ModuleError(
2914 "The '{0}' server type does not support a 'fallback_persistence_profile'".format(self.want.type)
2915 )
2916
2917 def _update_persistence_profile(self):
2918 # This must be changed back to a list to make a valid REST API
2919 # value. The module manipulates this as a normal dictionary
2920 if self.want.default_persistence_profile is not None:
2921 self.want.update({'default_persistence_profile': self.want.default_persistence_profile})
2922
2923 def _verify_type_has_correct_profiles(self):
2924 """Verify that specified server type does not include forbidden profiles
2925
2926 The type of the server determines the ``type``s of profiles that it accepts. This
2927 method checks that the server ``type`` that you specified is indeed one that can
2928 accept the profiles that you specified.
2929
2930 The common situations are
2931
2932 * ``standard`` types that include ``fasthttp``, ``fastl4``, or ``message routing`` profiles
2933 * ``fasthttp`` types that are missing a ``fasthttp`` profile
2934 * ``fastl4`` types that are missing a ``fastl4`` profile
2935 * ``message-routing`` types that are missing ``diameter`` or ``sip`` profiles
2936
2937 Raises:
2938 F5ModuleError: Raised when a validation check fails.
2939 """
2940 if self.want.type == 'standard':
2941 if self.want.has_fasthttp_profiles:
2942 raise F5ModuleError("A 'standard' type may not have 'fasthttp' profiles.")
2943 if self.want.has_fastl4_profiles:
2944 raise F5ModuleError("A 'standard' type may not have 'fastl4' profiles.")
2945 # if self.want.has_message_routing_profiles:
2946 # raise F5ModuleError("A 'standard' type may not have 'message-routing' profiles.")
2947 elif self.want.type == 'performance-http':
2948 if not self.want.has_fasthttp_profiles:
2949 raise F5ModuleError("A 'fasthttp' type must have at least one 'fasthttp' profile.")
2950 elif self.want.type == 'performance-l4':
2951 if not self.want.has_fastl4_profiles:
2952 raise F5ModuleError("A 'fastl4' type must have at least one 'fastl4' profile.")
2953 elif self.want.type == 'message-routing':
2954 if not self.want.has_message_routing_profiles:
2955 raise F5ModuleError("A 'message-routing' type must have either a 'sip' or 'diameter' profile.")
2956
2957 def _set_default_ip_protocol(self):
2958 if self.want.type == 'dhcp':
2959 return
2960 if self.want.ip_protocol is None:
2961 self.want.update({'ip_protocol': 6})
2962
2963 def _set_default_profiles(self):
2964 if self.want.type == 'standard':
2965 if not self.want.profiles:
2966 # Sets a default profiles when creating a new standard virtual.
2967 #
2968 # It appears that if no profiles are deliberately specified, then under
2969 # certain circumstances, the server type will default to ``performance-l4``.
2970 #
2971 # It's unclear what these circumstances are, but they are met in issue 00093.
2972 # If this block of profile setting code is removed, the virtual server's
2973 # type will change to performance-l4 for some reason.
2974 #
2975 if self.want.ip_protocol == 6:
2976 self.want.update({'profiles': ['tcp']})
2977 if self.want.ip_protocol == 17:
2978 self.want.update({'profiles': ['udp']})
2979 if self.want.ip_protocol == 132:
2980 self.want.update({'profiles': ['sctp']})
2981
2982 def _verify_minimum_profile(self):
2983 if self.want.profiles:
2984 return None
2985 if self.want.type == 'internal' and self.want.profiles == '':
2986 raise F5ModuleError(
2987 "An 'internal' server must have at least one profile relevant to its 'ip_protocol'. "
2988 "For example, 'tcp', 'udp', or variations of those."
2989 )
2990
2991 def _verify_dhcp_profile(self):
2992 if self.want.type != 'dhcp':
2993 return
2994 if self.want.profiles is None:
2995 return
2996 have = set(self.read_dhcp_profiles_from_device())
2997 want = set([x['fullPath'] for x in self.want.profiles])
2998 if have.intersection(want):
2999 return True
3000 raise F5ModuleError(
3001 "A dhcp profile, such as 'dhcpv4', or 'dhcpv6' must be specified when 'type' is 'dhcp'."
3002 )
3003
3004 def _verify_fastl4_profile(self):
3005 if self.want.type != 'performance-l4':
3006 return
3007 if self.want.profiles is None:
3008 return
3009 have = set(self.read_fastl4_profiles_from_device())
3010 want = set([x['fullPath'] for x in self.want.profiles])
3011 if have.intersection(want):
3012 return True
3013 raise F5ModuleError(
3014 "A performance-l4 profile, such as 'fastL4', must be specified when 'type' is 'performance-l4'."
3015 )
3016
3017 def _verify_fasthttp_profile(self):
3018 if self.want.type != 'performance-http':
3019 return
3020 if self.want.profiles is None:
3021 return
3022 have = set(self.read_fasthttp_profiles_from_device())
3023 want = set([x['fullPath'] for x in self.want.profiles])
3024 if have.intersection(want):
3025 return True
3026 raise F5ModuleError(
3027 "A performance-http profile, such as 'fasthttp', must be specified when 'type' is 'performance-http'."
3028 )
3029
3030 def _verify_stateless_profile_on_create(self):
3031 if self.want.type != 'stateless':
3032 return
3033 result = self._verify_stateless_profile()
3034 if result is None:
3035 raise F5ModuleError(
3036 "A udp profile, must be specified when 'type' is 'stateless'."
3037 )
3038
3039 def _verify_stateless_profile(self):
3040 if self.want.type != 'stateless':
3041 return
3042 if self.want.profiles is None:
3043 return
3044 have = set(self.read_udp_profiles_from_device())
3045 want = set([x['fullPath'] for x in self.want.profiles])
3046 if have.intersection(want):
3047 return True
3048 raise F5ModuleError(
3049 "A udp profile, must be specified when 'type' is 'stateless'."
3050 )
3051
3052 def read_dhcp_profiles_from_device(self):
3053 result = []
3054 result += self.read_dhcpv4_profiles_from_device()
3055 result += self.read_dhcpv6_profiles_from_device()
3056 return result
3057
3058 def read_dhcpv4_profiles_from_device(self):
3059 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dhcpv4/".format(
3060 self.client.provider['server'],
3061 self.client.provider['server_port'],
3062 )
3063 resp = self.client.api.get(uri)
3064 try:
3065 response = resp.json()
3066 except ValueError as ex:
3067 raise F5ModuleError(str(ex))
3068
3069 if 'code' in response and response['code'] == 400:
3070 if 'message' in response:
3071 raise F5ModuleError(response['message'])
3072 else:
3073 raise F5ModuleError(resp.content)
3074 result = [fq_name(self.want.partition, x['name']) for x in response['items']]
3075 return result
3076
3077 def read_dhcpv6_profiles_from_device(self):
3078 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dhcpv6/".format(
3079 self.client.provider['server'],
3080 self.client.provider['server_port'],
3081 )
3082 resp = self.client.api.get(uri)
3083 try:
3084 response = resp.json()
3085 except ValueError as ex:
3086 raise F5ModuleError(str(ex))
3087
3088 if 'code' in response and response['code'] == 400:
3089 if 'message' in response:
3090 raise F5ModuleError(response['message'])
3091 else:
3092 raise F5ModuleError(resp.content)
3093 result = [fq_name(self.want.partition, x['name']) for x in response['items']]
3094 return result
3095
3096 def read_fastl4_profiles_from_device(self):
3097 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/fastl4/".format(
3098 self.client.provider['server'],
3099 self.client.provider['server_port'],
3100 )
3101 resp = self.client.api.get(uri)
3102 try:
3103 response = resp.json()
3104 except ValueError as ex:
3105 raise F5ModuleError(str(ex))
3106
3107 if 'code' in response and response['code'] == 400:
3108 if 'message' in response:
3109 raise F5ModuleError(response['message'])
3110 else:
3111 raise F5ModuleError(resp.content)
3112 # result = [fq_name(self.want.partition, x['name']) for x in response['items']]
3113 result = [x['fullPath'] for x in response['items']]
3114 return result
3115
3116 def read_fasthttp_profiles_from_device(self):
3117 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/fasthttp/".format(
3118 self.client.provider['server'],
3119 self.client.provider['server_port'],
3120 )
3121 resp = self.client.api.get(uri)
3122 try:
3123 response = resp.json()
3124 except ValueError as ex:
3125 raise F5ModuleError(str(ex))
3126
3127 if 'code' in response and response['code'] == 400:
3128 if 'message' in response:
3129 raise F5ModuleError(response['message'])
3130 else:
3131 raise F5ModuleError(resp.content)
3132 result = [fq_name(self.want.partition, x['name']) for x in response['items']]
3133 return result
3134
3135 def read_udp_profiles_from_device(self):
3136 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/".format(
3137 self.client.provider['server'],
3138 self.client.provider['server_port'],
3139 )
3140 resp = self.client.api.get(uri)
3141 try:
3142 response = resp.json()
3143 except ValueError as ex:
3144 raise F5ModuleError(str(ex))
3145
3146 if 'code' in response and response['code'] == 400:
3147 if 'message' in response:
3148 raise F5ModuleError(response['message'])
3149 else:
3150 raise F5ModuleError(resp.content)
3151 result = [fq_name(self.want.partition, x['name']) for x in response['items']]
3152 return result
3153
3154
3155 class Difference(object):
3156 def __init__(self, want, have=None):
3157 self.have = have
3158 self.want = want
3159
3160 def compare(self, param):
3161 try:
3162 result = getattr(self, param)
3163 return result
3164 except AttributeError:
3165 result = self.__default(param)
3166 return result
3167
3168 def __default(self, param):
3169 attr1 = getattr(self.want, param)
3170 try:
3171 attr2 = getattr(self.have, param)
3172 if attr1 != attr2:
3173 return attr1
3174 except AttributeError:
3175 return attr1
3176
3177 def to_tuple(self, items):
3178 result = []
3179 for x in items:
3180 tmp = [(str(k), str(v)) for k, v in iteritems(x)]
3181 result += tmp
3182 return result
3183
3184 def _diff_complex_items(self, want, have):
3185 if want == [] and have is None:
3186 return None
3187 if want is None:
3188 return None
3189 w = self.to_tuple(want)
3190 h = self.to_tuple(have)
3191 if set(w).issubset(set(h)):
3192 return None
3193 else:
3194 return want
3195
3196 def _update_vlan_status(self, result):
3197 if self.want.vlans_disabled is not None:
3198 if self.want.vlans_disabled != self.have.vlans_disabled:
3199 result['vlans_disabled'] = self.want.vlans_disabled
3200 result['vlans_enabled'] = not self.want.vlans_disabled
3201 elif self.want.vlans_enabled is not None:
3202 if any(x.lower().endswith('/all') for x in self.want.vlans):
3203 if self.have.vlans_enabled is True:
3204 result['vlans_disabled'] = True
3205 result['vlans_enabled'] = False
3206 elif self.want.vlans_enabled != self.have.vlans_enabled:
3207 result['vlans_disabled'] = not self.want.vlans_enabled
3208 result['vlans_enabled'] = self.want.vlans_enabled
3209
3210 @property
3211 def destination(self):
3212 # The internal type does not support the 'destination' parameter, so it is ignored.
3213 if self.want.type == 'internal':
3214 return
3215
3216 addr_tuple = [self.want.destination, self.want.port, self.want.route_domain]
3217 if all(x is None for x in addr_tuple):
3218 return None
3219
3220 have = self.have.destination_tuple
3221 if self.want.port is None:
3222 self.want.update({'port': have.port})
3223 if self.want.route_domain is None:
3224 self.want.update({'route_domain': have.route_domain})
3225 if self.want.destination_tuple.ip is None:
3226 address = have.ip
3227 else:
3228 address = self.want.destination_tuple.ip
3229 want = self.want._format_destination(address, self.want.port, self.want.route_domain)
3230 if want != self.have.destination:
3231 return fq_name(self.want.partition, want)
3232
3233 @property
3234 def source(self):
3235 if self.want.source is None:
3236 return None
3237 if self.want.source != self.have.source:
3238 return self.want.source
3239
3240 @property
3241 def vlans(self):
3242 if self.want.vlans is None:
3243 return None
3244 elif self.want.vlans == [] and self.have.vlans is None:
3245 return None
3246 elif self.want.vlans == self.have.vlans:
3247 return None
3248
3249 # Specifically looking for /all because the vlans return value will be
3250 # an FQDN list. This means that "all" will be returned as "/partition/all",
3251 # ex, /Common/all.
3252 #
3253 # We do not want to accidentally match values that would end with the word
3254 # "all", like "vlansall". Therefore we look for the forward slash because this
3255 # is a path delimiter.
3256 elif any(x.lower().endswith('/all') for x in self.want.vlans):
3257 if self.have.vlans is None:
3258 return None
3259 else:
3260 return []
3261 else:
3262 return self.want.vlans
3263
3264 @property
3265 def enabled_vlans(self):
3266 return self.vlan_status
3267
3268 @property
3269 def disabled_vlans(self):
3270 return self.vlan_status
3271
3272 @property
3273 def vlan_status(self):
3274 result = dict()
3275 vlans = self.vlans
3276 if vlans is not None:
3277 result['vlans'] = vlans
3278 self._update_vlan_status(result)
3279 return result
3280
3281 @property
3282 def port(self):
3283 result = self.destination
3284 if result is not None:
3285 return dict(
3286 destination=result
3287 )
3288
3289 @property
3290 def profiles(self):
3291 if self.want.profiles is None:
3292 return None
3293 # raise F5ModuleError(f"want:{self.want.profiles} Have: {self.have.profiles}")
3294 if self.want.profiles == '' and len(self.have.profiles) > 0:
3295 have = set([(p['name'], p['context'], p['fullPath']) for p in self.have.profiles])
3296 if len(self.have.profiles) == 1:
3297 if not any(x[0] in ['tcp', 'udp', 'sctp'] for x in have):
3298 return []
3299 else:
3300 return None
3301 else:
3302 return []
3303 if self.want.profiles == '' and len(self.have.profiles) == 0:
3304 return None
3305 want = set([(p['name'], p['context'], p['fullPath']) for p in self.want.profiles])
3306 have = set([(p['name'], p['context'], p['fullPath']) for p in self.have.profiles])
3307 if len(have) == 0:
3308 return self.want.profiles
3309 elif len(have) == 1:
3310 if want != have:
3311 return self.want.profiles
3312 else:
3313 if not any(x[0] == 'tcp' for x in want):
3314 if self.want.type != 'stateless':
3315 have = set([x for x in have if x[0] != 'tcp'])
3316 if not any(x[0] == 'udp' for x in want):
3317 have = set([x for x in have if x[0] != 'udp'])
3318 if not any(x[0] == 'sctp' for x in want):
3319 if self.want.type != 'stateless':
3320 have = set([x for x in have if x[0] != 'sctp'])
3321 want = set([(p[2], p[1]) for p in want])
3322 have = set([(p[2], p[1]) for p in have])
3323 if want != have:
3324 return self.want.profiles
3325
3326 @property
3327 def ip_protocol(self):
3328 if self.want.ip_protocol != self.have.ip_protocol:
3329 return self.want.ip_protocol
3330
3331 @property
3332 def fallback_persistence_profile(self):
3333 if self.want.fallback_persistence_profile is None:
3334 return None
3335 if self.want.fallback_persistence_profile == '' and self.have.fallback_persistence_profile is not None:
3336 return ""
3337 if self.want.fallback_persistence_profile == '' and self.have.fallback_persistence_profile is None:
3338 return None
3339 if self.want.fallback_persistence_profile != self.have.fallback_persistence_profile:
3340 return self.want.fallback_persistence_profile
3341
3342 @property
3343 def default_persistence_profile(self):
3344 if self.want.default_persistence_profile is None:
3345 return None
3346 if self.want.default_persistence_profile == '' and self.have.default_persistence_profile is not None:
3347 return []
3348 if self.want.default_persistence_profile == '' and self.have.default_persistence_profile is None:
3349 return None
3350 if self.have.default_persistence_profile is None:
3351 return dict(
3352 default_persistence_profile=self.want.default_persistence_profile
3353 )
3354 w_name = self.want.default_persistence_profile.get('name', None)
3355 w_partition = self.want.default_persistence_profile.get('partition', None)
3356 h_name = self.have.default_persistence_profile.get('name', None)
3357 h_partition = self.have.default_persistence_profile.get('partition', None)
3358 if w_name != h_name or w_partition != h_partition:
3359 return dict(
3360 default_persistence_profile=self.want.default_persistence_profile
3361 )
3362
3363 @property
3364 def ip_intelligence_policy(self):
3365 if self.want.ip_intelligence_policy is None:
3366 return None
3367 if self.want.ip_intelligence_policy == '' and self.have.ip_intelligence_policy is not None:
3368 return ""
3369 if self.want.ip_intelligence_policy == '' and self.have.ip_intelligence_policy is None:
3370 return None
3371 if self.want.ip_intelligence_policy != self.have.ip_intelligence_policy:
3372 return self.want.ip_intelligence_policy
3373
3374 @property
3375 def policies(self):
3376 if self.want.policies is None:
3377 return None
3378 if self.want.policies in [[], ''] and self.have.policies is None:
3379 return None
3380 if self.want.policies == '' and len(self.have.policies) > 0:
3381 return []
3382 if not self.have.policies:
3383 return self.want.policies
3384 want = set([(p['name'], p['partition']) for p in self.want.policies])
3385 have = set([(p['name'], p['partition']) for p in self.have.policies])
3386 if not want == have:
3387 return self.want.policies
3388
3389 @property
3390 def snat(self):
3391 if self.want.snat is None:
3392 return None
3393 if self.want.snat['type'] != self.have.snat['type']:
3394 result = dict(snat=self.want.snat)
3395 return result
3396
3397 if self.want.snat.get('pool', None) is None:
3398 return None
3399
3400 if self.want.snat['pool'] != self.have.snat['pool']:
3401 result = dict(snat=self.want.snat)
3402 return result
3403
3404 @property
3405 def enabled(self):
3406 if self.want.state == 'enabled' and self.have.disabled:
3407 result = dict(
3408 enabled=True,
3409 disabled=False
3410 )
3411 return result
3412 elif self.want.state == 'disabled' and self.have.enabled:
3413 result = dict(
3414 enabled=False,
3415 disabled=True
3416 )
3417 return result
3418
3419 @property
3420 def irules(self):
3421 if self.want.irules is None:
3422 return None
3423 if self.want.irules == '' and len(self.have.irules) > 0:
3424 return []
3425 if self.want.irules in [[], ''] and len(self.have.irules) == 0:
3426 return None
3427 if self.want.irules != self.have.irules:
3428 return self.want.irules
3429
3430 @property
3431 def pool(self):
3432 if self.want.pool is None:
3433 return None
3434 if self.want.pool == '' and self.have.pool is not None:
3435 return ""
3436 if self.want.pool == '' and self.have.pool is None:
3437 return None
3438 if self.want.pool != self.have.pool:
3439 return self.want.pool
3440
3441 @property
3442 def metadata(self):
3443 if self.want.metadata is None:
3444 return None
3445 elif len(self.want.metadata) == 0 and self.have.metadata is None:
3446 return None
3447 elif len(self.want.metadata) == 0 and not self.want.insert_metadata:
3448 return None
3449 elif len(self.want.metadata) == 0 and self.want.insert_metadata:
3450 return []
3451 elif self.have.metadata is None:
3452 return self.want.metadata
3453 result = self._diff_complex_items(self.want.metadata, self.have.metadata)
3454 return result
3455
3456 @property
3457 def type(self):
3458 if self.want.state in ["disabled", "enabled"] and self.want.type in [None, "standard"]:
3459 # when type is missing
3460 self.want.type = self.have.type
3461
3462 if self.want.type != self.have.type:
3463 raise F5ModuleError(
3464 "Changing the 'type' parameter is not supported."
3465 )
3466
3467 @property
3468 def security_log_profiles(self):
3469 result = cmp_simple_list(self.want.security_log_profiles, self.have.security_log_profiles)
3470 return result
3471
3472 @property
3473 def security_nat_policy(self):
3474 result = dict()
3475 if self.want.sec_nat_use_device_policy is not None:
3476 if self.want.sec_nat_use_device_policy != self.have.sec_nat_use_device_policy:
3477 result['use_device_policy'] = self.want.sec_nat_use_device_policy
3478 if self.want.sec_nat_use_rd_policy is not None:
3479 if self.want.sec_nat_use_rd_policy != self.have.sec_nat_use_rd_policy:
3480 result['use_route_domain_policy'] = self.want.sec_nat_use_rd_policy
3481 if self.want.sec_nat_policy is not None:
3482 if self.want.sec_nat_policy == '' and self.have.sec_nat_policy is None:
3483 pass
3484 elif self.want.sec_nat_policy != self.have.sec_nat_policy:
3485 result['policy'] = self.want.sec_nat_policy
3486 if result:
3487 return dict(security_nat_policy=result)
3488
3489 @property
3490 def clone_pools(self):
3491 if self.want.clone_pools == [] and self.have.clone_pools:
3492 return self.want.clone_pools
3493 result = self._diff_complex_items(self.want.clone_pools, self.have.clone_pools)
3494 return result
3495
3496
3497 class ModuleManager(object):
3498 def __init__(self, *args, **kwargs):
3499 self.module = kwargs.get('module', None)
3500 self.client = F5RestClient(**self.module.params)
3501 self.have = ApiParameters(client=self.client)
3502 self.want = ModuleParameters(client=self.client, params=self.module.params)
3503 self.changes = UsableChanges()
3504 self.provisioned_modules = []
3505
3506 def exec_module(self):
3507 start = datetime.now().isoformat()
3508 version = tmos_version(self.client)
3509 changed = False
3510 result = dict()
3511 state = self.want.state
3512
3513 self.provisioned_modules = modules_provisioned(self.client)
3514
3515 if state in ['present', 'enabled', 'disabled']:
3516 changed = self.present()
3517 elif state == "absent":
3518 changed = self.absent()
3519
3520 reportable = ReportableChanges(params=self.changes.to_return())
3521 changes = reportable.to_return()
3522 result.update(**changes)
3523 result.update(dict(changed=changed))
3524 send_teem(start, self.client, self.module, version)
3525 return result
3526
3527 def present(self):
3528 if self.exists():
3529 return self.update()
3530 else:
3531 return self.create()
3532
3533 def absent(self):
3534 if self.exists():
3535 return self.remove()
3536 return False
3537
3538 def update(self):
3539 self.have = self.read_current_from_device()
3540 if not self.want.bypass_module_checks:
3541 validator = VirtualServerValidator(
3542 module=self.module, client=self.client, have=self.have, want=self.want
3543 )
3544 validator.check_update()
3545
3546 if self.want.ip_intelligence_policy is not None:
3547 if not any(x for x in self.provisioned_modules if x in ['afm', 'asm']):
3548 raise F5ModuleError(
3549 "AFM must be provisioned to configure an IP Intelligence policy."
3550 )
3551
3552 if not self.should_update():
3553 return False
3554 if self.module.check_mode:
3555 return True
3556 self.update_on_device()
3557 return True
3558
3559 def should_update(self):
3560 result = self._update_changed_options()
3561 if result:
3562 return True
3563 return False
3564
3565 def remove(self):
3566 if self.module.check_mode:
3567 return True
3568 self.remove_from_device()
3569 if self.exists():
3570 raise F5ModuleError("Failed to delete the resource")
3571 return True
3572
3573 def get_reportable_changes(self):
3574 result = ReportableChanges(params=self.changes.to_return())
3575 return result
3576
3577 def _set_changed_options(self):
3578 changed = {}
3579 for key in Parameters.returnables:
3580 if getattr(self.want, key) is not None:
3581 changed[key] = getattr(self.want, key)
3582 if changed:
3583 self.changes = UsableChanges(params=changed)
3584
3585 def _update_changed_options(self):
3586 diff = Difference(self.want, self.have)
3587 updatables = Parameters.updatables
3588 changed = dict()
3589 for k in updatables:
3590 change = diff.compare(k)
3591 if change is None:
3592 continue
3593 else:
3594 if isinstance(change, dict):
3595 changed.update(change)
3596 else:
3597 changed[k] = change
3598 if changed:
3599 self.changes = UsableChanges(params=changed)
3600 return True
3601 return False
3602
3603 def exists(self):
3604 uri = "https://{0}:{1}/mgmt/tm/ltm/virtual/{2}".format(
3605 self.client.provider['server'],
3606 self.client.provider['server_port'],
3607 transform_name(self.want.partition, self.want.name)
3608 )
3609 resp = self.client.api.get(uri)
3610 try:
3611 response = resp.json()
3612 except ValueError as ex:
3613 raise F5ModuleError(str(ex))
3614
3615 if resp.status == 404 or 'code' in response and response['code'] == 404:
3616 return False
3617 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
3618 return True
3619
3620 errors = [401, 403, 409, 500, 501, 502, 503, 504]
3621
3622 if resp.status in errors or 'code' in response and response['code'] in errors:
3623 if 'message' in response:
3624 raise F5ModuleError(response['message'])
3625 else:
3626 raise F5ModuleError(resp.content)
3627
3628 def create(self):
3629 if not self.want.bypass_module_checks:
3630 validator = VirtualServerValidator(
3631 module=self.module, client=self.client, have=self.have, want=self.want
3632 )
3633 validator.check_create()
3634
3635 if self.want.ip_intelligence_policy is not None:
3636 if not any(x for x in self.provisioned_modules if x in ['afm', 'asm']):
3637 raise F5ModuleError(
3638 "AFM must be provisioned to configure an IP Intelligence policy."
3639 )
3640 self._set_changed_options()
3641 if self.module.check_mode:
3642 return True
3643 self.create_on_device()
3644 return True
3645
3646 def update_on_device(self):
3647 params = self.changes.api_params()
3648
3649 if self.want.insert_metadata:
3650 # Mark the resource as managed by Ansible, this is default behavior
3651 params = mark_managed_by(self.module.ansible_version, params)
3652
3653 uri = "https://{0}:{1}/mgmt/tm/ltm/virtual/{2}".format(
3654 self.client.provider['server'],
3655 self.client.provider['server_port'],
3656 transform_name(self.want.partition, self.want.name)
3657 )
3658 resp = self.client.api.patch(uri, json=params)
3659 try:
3660 response = resp.json()
3661 except ValueError as ex:
3662 raise F5ModuleError(str(ex))
3663
3664 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
3665 return True
3666 raise F5ModuleError(resp.content)
3667
3668 def read_current_from_device(self):
3669 uri = "https://{0}:{1}/mgmt/tm/ltm/virtual/{2}?expandSubcollections=true".format(
3670 self.client.provider['server'],
3671 self.client.provider['server_port'],
3672 transform_name(self.want.partition, self.want.name)
3673 )
3674 resp = self.client.api.get(uri)
3675 try:
3676 response = resp.json()
3677 except ValueError as ex:
3678 raise F5ModuleError(str(ex))
3679
3680 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
3681 return ApiParameters(params=response, client=self.client)
3682 raise F5ModuleError(resp.content)
3683
3684 def create_on_device(self):
3685 params = self.changes.api_params()
3686 params['name'] = self.want.name
3687 params['partition'] = self.want.partition
3688 if 'destination' not in params:
3689 params['destination'] = f"/Common/0.0.0.0:{self.want.port}"
3690 params['mask'] = "255.255.255.255"
3691 if self.want.insert_metadata:
3692 # Mark the resource as managed by Ansible, this is default behavior
3693 params = mark_managed_by(self.module.ansible_version, params)
3694 uri = "https://{0}:{1}/mgmt/tm/ltm/virtual/".format(
3695 self.client.provider['server'],
3696 self.client.provider['server_port']
3697 )
3698 resp = self.client.api.post(uri, json=params)
3699 try:
3700 response = resp.json()
3701 except ValueError as ex:
3702 raise F5ModuleError(str(ex))
3703
3704 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
3705 return True
3706 raise F5ModuleError(resp.content)
3707
3708 def remove_from_device(self):
3709 uri = "https://{0}:{1}/mgmt/tm/ltm/virtual/{2}".format(
3710 self.client.provider['server'],
3711 self.client.provider['server_port'],
3712 transform_name(self.want.partition, self.want.name)
3713 )
3714 response = self.client.api.delete(uri)
3715 if response.status == 200:
3716 return True
3717 raise F5ModuleError(response.content)
3718
3719
3720 class ArgumentSpec(object):
3721 def __init__(self):
3722 self.supports_check_mode = True
3723 argument_spec = dict(
3724 state=dict(
3725 default='present',
3726 choices=['present', 'absent', 'disabled', 'enabled']
3727 ),
3728 name=dict(
3729 required=True,
3730 aliases=['vs']
3731 ),
3732 destination=dict(
3733 aliases=['address', 'ip']
3734 ),
3735 port=dict(),
3736 profiles=dict(
3737 type='raw',
3738 options=dict(
3739 name=dict(),
3740 context=dict(default='all', choices=['all', 'server-side', 'client-side'])
3741 ),
3742 aliases=['all_profiles'],
3743 ),
3744 policies=dict(
3745 type='list',
3746 elements='str',
3747 aliases=['all_policies']
3748 ),
3749 irules=dict(
3750 type='list',
3751 elements='str',
3752 aliases=['all_rules']
3753 ),
3754 enabled_vlans=dict(
3755 type='list',
3756 elements='str',
3757 ),
3758 disabled_vlans=dict(
3759 type='list',
3760 elements='str',
3761 ),
3762 pool=dict(),
3763 description=dict(),
3764 snat=dict(),
3765 serverssl_use_sni=dict(type='bool'),
3766 default_persistence_profile=dict(),
3767 fallback_persistence_profile=dict(),
3768 source=dict(),
3769 metadata=dict(type='raw'),
3770 partition=dict(
3771 default='Common',
3772 fallback=(env_fallback, ['F5_PARTITION'])
3773 ),
3774 address_translation=dict(type='bool'),
3775 port_translation=dict(type='bool'),
3776 source_port=dict(
3777 choices=[
3778 'preserve', 'preserve-strict', 'change'
3779 ]
3780 ),
3781 ip_protocol=dict(
3782 choices=[
3783 'ah', 'any', 'bna', 'esp', 'etherip', 'gre', 'icmp', 'ipencap', 'ipv6',
3784 'ipv6-auth', 'ipv6-crypt', 'ipv6-icmp', 'isp-ip', 'mux', 'ospf',
3785 'sctp', 'tcp', 'udp', 'udplite'
3786 ]
3787 ),
3788 type=dict(
3789 default='standard',
3790 choices=[
3791 'standard', 'forwarding-ip', 'forwarding-l2', 'internal', 'message-routing',
3792 'performance-http', 'performance-l4', 'reject', 'stateless', 'dhcp'
3793 ]
3794 ),
3795 mirror=dict(type='bool'),
3796 auto_last_hop=dict(
3797 choices=['enabled', 'disabled', 'default']
3798 ),
3799 mask=dict(),
3800 firewall_staged_policy=dict(),
3801 firewall_enforced_policy=dict(),
3802 ip_intelligence_policy=dict(),
3803 service_down_immediate_action=dict(
3804 choices=['drop', 'none', 'reset']
3805 ),
3806 per_flow_request_access_policy=dict(),
3807 security_log_profiles=dict(
3808 type='list',
3809 elements='str',
3810 ),
3811 security_nat_policy=dict(
3812 type='dict',
3813 options=dict(
3814 policy=dict(),
3815 use_device_policy=dict(type='bool'),
3816 use_route_domain_policy=dict(type='bool')
3817 )
3818 ),
3819 insert_metadata=dict(
3820 type='bool',
3821 default='yes'
3822 ),
3823 rate_limit=dict(type='int'),
3824 rate_limit_dst_mask=dict(type='int'),
3825 rate_limit_src_mask=dict(type='int'),
3826 rate_limit_mode=dict(
3827 default='object',
3828 choices=[
3829 'destination', 'object-destination', 'object-source-destination',
3830 'source-destination', 'object', 'object-source', 'source'
3831 ]
3832 ),
3833 clone_pools=dict(
3834 type='list',
3835 elements='dict',
3836 options=dict(
3837 pool_name=dict(required=True),
3838 context=dict(
3839 required=True,
3840 choices=[
3841 'clientside', 'serverside'
3842 ]
3843 )
3844 )
3845 ),
3846 check_profiles=dict(
3847 type='bool',
3848 default='yes'
3849 ),
3850 bypass_module_checks=dict(
3851 type='bool',
3852 default='no'
3853 )
3854 )
3855 self.argument_spec = {}
3856 self.argument_spec.update(f5_argument_spec)
3857 self.argument_spec.update(argument_spec)
3858 self.mutually_exclusive = [
3859 ['enabled_vlans', 'disabled_vlans']
3860 ]
3861
3862
3863 def main():
3864 spec = ArgumentSpec()
3865
3866 module = AnsibleModule(
3867 argument_spec=spec.argument_spec,
3868 supports_check_mode=spec.supports_check_mode,
3869 mutually_exclusive=spec.mutually_exclusive
3870 )
3871
3872 if not HAS_PACKAGING:
3873 module.fail_json(
3874 msg=missing_required_lib('packaging'),
3875 exception=PACKAGING_IMPORT_ERROR
3876 )
3877
3878 try:
3879 mm = ModuleManager(module=module)
3880 results = mm.exec_module()
3881 module.exit_json(**results)
3882 except F5ModuleError as ex:
3883 module.fail_json(msg=str(ex))
3884
3885
3886 if __name__ == '__main__':
3887 main()