Debian Codegraph @

ansible_collections/community/general/plugins/modules/nmcli.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Chris Long <[email protected]> <[email protected]>
4 # Copyright (c) 2017, Ansible Project
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: nmcli
12 author:
13 - Chris Long (@alcamie101)
14 short_description: Manage Networking
15 requirements:
16 - nmcli
17 extends_documentation_fragment:
18 - community.general._attributes
19 description:
20 - Manage the network devices. Create, modify and manage various connection and device type, for example V(ethernet), V(team),
21 V(bond), V(vlan) and so on.
22 - 'On CentOS 8 and Fedora >=29 like systems, the requirements can be met by installing the following packages: C(NetworkManager).'
23 - 'On CentOS 7 and Fedora <=28 like systems, the requirements can be met by installing the following packages: C(NetworkManager-tui).'
24 - 'On Ubuntu and Debian like systems, the requirements can be met by installing the following packages: C(network-manager).'
25 - 'On openSUSE, the requirements can be met by installing the following packages: C(NetworkManager).'
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: full
31 options:
32 state:
33 description:
34 - Whether the device should exist or not, taking action if the state is different from what is stated.
35 - Using O(state=present) creates connection set to be brought up automatically.
36 - Using O(state=up) and O(state=down) does not modify connection with other parameters. These states have been added
37 in community.general 9.5.0.
38 type: str
39 required: true
40 choices: [absent, present, up, down]
41 autoconnect:
42 description:
43 - Whether the connection should start on boot.
44 - Whether the connection profile can be automatically activated.
45 type: bool
46 default: true
47 autoconnect_priority:
48 description:
49 - The priority of the connection profile for autoconnect. If set, connection profiles with higher priority are preferred.
50 type: int
51 version_added: 11.0.0
52 autoconnect_retries:
53 description:
54 - The number of times to retry autoconnecting.
55 type: int
56 version_added: 11.0.0
57 conn_name:
58 description:
59 - The name used to call the connection. Pattern is V(<type>[-<ifname>][-<num>]).
60 type: str
61 required: true
62 conn_reload:
63 description:
64 - Whether the connection should be reloaded if it was modified.
65 type: bool
66 default: false
67 version_added: 9.5.0
68 ifname:
69 description:
70 - The interface to bind the connection to.
71 - The connection is only applicable to this interface name.
72 - A special value of V(*) can be used for interface-independent connections.
73 - The O(ifname) argument is mandatory for all connection types except bond, team, bridge, vlan and vpn.
74 - This parameter defaults to O(conn_name) when left unset for all connection types except vpn that removes it.
75 type: str
76 type:
77 description:
78 - This is the type of device or network connection that you wish to create or modify.
79 - Type V(dummy) is added in community.general 3.5.0.
80 - Type V(gsm) is added in community.general 3.7.0.
81 - Type V(infiniband) is added in community.general 2.0.0.
82 - Type V(loopback) is added in community.general 8.1.0.
83 - Type V(macvlan) is added in community.general 6.6.0.
84 - Type V(ovs-bridge) is added in community.general 8.6.0.
85 - Type V(ovs-interface) is added in community.general 8.6.0.
86 - Type V(ovs-port) is added in community.general 8.6.0.
87 - Type V(wireguard) is added in community.general 4.3.0.
88 - Type V(vpn) is added in community.general 5.1.0.
89 - Type V(vrf) is added in community.general 10.4.0.
90 - Using V(bond-slave), V(bridge-slave), or V(team-slave) implies V(ethernet) connection type with corresponding O(slave_type)
91 option.
92 - If you want to control non-ethernet connection attached to V(bond), V(bridge), or V(team) consider using O(slave_type)
93 option.
94 type: str
95 choices:
96 - bond
97 - bond-slave
98 - bridge
99 - bridge-slave
100 - dummy
101 - ethernet
102 - generic
103 - gre
104 - infiniband
105 - ipip
106 - macvlan
107 - sit
108 - team
109 - team-slave
110 - vlan
111 - vxlan
112 - wifi
113 - gsm
114 - wireguard
115 - ovs-bridge
116 - ovs-port
117 - ovs-interface
118 - vpn
119 - vrf
120 - loopback
121 mode:
122 description:
123 - This is the type of device or network connection that you wish to create for a bond or bridge.
124 type: str
125 choices: [802.3ad, active-backup, balance-alb, balance-rr, balance-tlb, balance-xor, broadcast]
126 default: balance-rr
127 transport_mode:
128 description:
129 - This option sets the connection type of Infiniband IPoIB devices.
130 type: str
131 choices: [datagram, connected]
132 version_added: 5.8.0
133 infiniband_mac:
134 description:
135 - MAC address of the Infiniband IPoIB devices.
136 type: str
137 version_added: 10.6.0
138 slave_type:
139 description:
140 - Type of the device of this slave's master connection (for example V(bond)).
141 - Type V(ovs-port) is added in community.general 8.6.0.
142 type: str
143 choices: ['bond', 'bridge', 'team', 'ovs-port', 'vrf']
144 version_added: 7.0.0
145 master:
146 description:
147 - Master <master (ifname, or connection UUID or conn_name) of bridge, team, bond, ovs-port master connection profile.
148 - Mandatory if O(slave_type) is defined.
149 type: str
150 ip4:
151 description:
152 - List of IPv4 addresses to this interface.
153 - Use the format V(192.0.2.24/24) or V(192.0.2.24).
154 - If defined and O(method4) is not specified, automatically set C(ipv4.method) to V(manual).
155 type: list
156 elements: str
157 gw4:
158 description:
159 - The IPv4 gateway for this interface.
160 - Use the format V(192.0.2.1).
161 - This parameter is mutually_exclusive with never_default4 parameter.
162 type: str
163 gw4_ignore_auto:
164 description:
165 - Ignore automatically configured IPv4 routes.
166 type: bool
167 default: false
168 version_added: 3.2.0
169 routes4:
170 description:
171 - The list of IPv4 routes.
172 - Use the format V(192.0.3.0/24 192.0.2.1).
173 - To specify more complex routes, use the O(routes4_extended) option.
174 type: list
175 elements: str
176 version_added: 2.0.0
177 routes4_extended:
178 description:
179 - The list of IPv4 routes.
180 type: list
181 elements: dict
182 suboptions:
183 ip:
184 description:
185 - IP or prefix of route.
186 - Use the format V(192.0.3.0/24).
187 type: str
188 required: true
189 next_hop:
190 description:
191 - Use the format V(192.0.2.1).
192 type: str
193 metric:
194 description:
195 - Route metric.
196 type: int
197 table:
198 description:
199 - The table to add this route to.
200 - The default depends on C(ipv4.route-table).
201 type: int
202 cwnd:
203 description:
204 - The clamp for congestion window.
205 type: int
206 mtu:
207 description:
208 - If non-zero, only transmit packets of the specified size or smaller.
209 type: int
210 onlink:
211 description:
212 - Pretend that the nexthop is directly attached to this link, even if it does not match any interface prefix.
213 type: bool
214 tos:
215 description:
216 - The Type Of Service.
217 type: int
218 route_metric4:
219 description:
220 - Set metric level of ipv4 routes configured on interface.
221 type: int
222 version_added: 2.0.0
223 routing_rules4:
224 description:
225 - Is the same as in an C(ip rule add) command, except always requires specifying a priority.
226 type: list
227 elements: str
228 version_added: 3.3.0
229 routing_rules6:
230 description:
231 - Is the same as in an C(ip rule add) command, except always requires specifying a priority.
232 type: list
233 elements: str
234 version_added: 12.3.0
235 never_default4:
236 description:
237 - Set as default route.
238 - This parameter is mutually_exclusive with gw4 parameter.
239 type: bool
240 default: false
241 version_added: 2.0.0
242 dns4:
243 description:
244 - A list of up to 3 DNS servers.
245 - The entries must be IPv4 addresses, for example V(192.0.2.53).
246 elements: str
247 type: list
248 dns4_search:
249 description:
250 - A list of DNS search domains.
251 elements: str
252 type: list
253 dns4_options:
254 description:
255 - A list of DNS options.
256 elements: str
257 type: list
258 version_added: 7.2.0
259 dns4_ignore_auto:
260 description:
261 - Ignore automatically configured IPv4 name servers.
262 type: bool
263 default: false
264 version_added: 3.2.0
265 method4:
266 description:
267 - Configuration method to be used for IPv4.
268 - If O(ip4) is set, C(ipv4.method) is automatically set to V(manual) and this parameter is not needed.
269 type: str
270 choices: [auto, link-local, manual, shared, disabled]
271 version_added: 2.2.0
272 may_fail4:
273 description:
274 - If you need O(ip4) configured before C(network-online.target) is reached, set this option to V(false).
275 - This option applies when O(method4) is not V(disabled).
276 type: bool
277 default: true
278 version_added: 3.3.0
279 ip6:
280 description:
281 - List of IPv6 addresses to this interface.
282 - Use the format V(abbe::cafe/128) or V(abbe::cafe).
283 - If defined and O(method6) is not specified, automatically set C(ipv6.method) to V(manual).
284 type: list
285 elements: str
286 gw6:
287 description:
288 - The IPv6 gateway for this interface.
289 - Use the format V(2001:db8::1).
290 type: str
291 gw6_ignore_auto:
292 description:
293 - Ignore automatically configured IPv6 routes.
294 type: bool
295 default: false
296 version_added: 3.2.0
297 routes6:
298 description:
299 - The list of IPv6 routes.
300 - Use the format V(fd12:3456:789a:1::/64 2001:dead:beef::1).
301 - To specify more complex routes, use the O(routes6_extended) option.
302 type: list
303 elements: str
304 version_added: 4.4.0
305 routes6_extended:
306 description:
307 - The list of IPv6 routes but with parameters.
308 type: list
309 elements: dict
310 suboptions:
311 ip:
312 description:
313 - IP or prefix of route.
314 - Use the format V(fd12:3456:789a:1::/64).
315 type: str
316 required: true
317 next_hop:
318 description:
319 - Use the format V(2001:dead:beef::1).
320 type: str
321 metric:
322 description:
323 - Route metric.
324 type: int
325 table:
326 description:
327 - The table to add this route to.
328 - The default depends on C(ipv6.route-table).
329 type: int
330 cwnd:
331 description:
332 - The clamp for congestion window.
333 type: int
334 mtu:
335 description:
336 - If non-zero, only transmit packets of the specified size or smaller.
337 type: int
338 onlink:
339 description:
340 - Pretend that the nexthop is directly attached to this link, even if it does not match any interface prefix.
341 type: bool
342 route_metric6:
343 description:
344 - Set metric level of IPv6 routes configured on interface.
345 type: int
346 version_added: 4.4.0
347 dns6:
348 description:
349 - A list of up to 3 DNS servers.
350 - The entries must be IPv6 addresses, for example V(2001:4860:4860::8888).
351 elements: str
352 type: list
353 dns6_search:
354 description:
355 - A list of DNS search domains.
356 elements: str
357 type: list
358 dns6_options:
359 description:
360 - A list of DNS options.
361 elements: str
362 type: list
363 version_added: 7.2.0
364 dns6_ignore_auto:
365 description:
366 - Ignore automatically configured IPv6 name servers.
367 type: bool
368 default: false
369 version_added: 3.2.0
370 method6:
371 description:
372 - Configuration method to be used for IPv6.
373 - If O(ip6) is set, C(ipv6.method) is automatically set to V(manual) and this parameter is not needed.
374 - V(disabled) was added in community.general 3.3.0.
375 type: str
376 choices: [ignore, auto, dhcp, link-local, manual, shared, disabled]
377 version_added: 2.2.0
378 ip_privacy6:
379 description:
380 - If enabled, it makes the kernel generate a temporary IPv6 address in addition to the public one.
381 type: str
382 choices: [disabled, prefer-public-addr, prefer-temp-addr, unknown]
383 version_added: 4.2.0
384 addr_gen_mode6:
385 description:
386 - Configure method for creating the address for use with IPv6 Stateless Address Autoconfiguration.
387 - V(default) and V(default-or-eui64) have been added in community.general 6.5.0.
388 type: str
389 choices: [default, default-or-eui64, eui64, stable-privacy]
390 version_added: 4.2.0
391 mtu:
392 description:
393 - The connection MTU, for example V(9000). This can not be applied when creating the interface and is done once the
394 interface has been created.
395 - Can be used when modifying Team, VLAN, Ethernet (Future plans to implement wifi, gsm, pppoe, infiniband).
396 - This parameter defaults to V(1500) when unset.
397 type: int
398 dhcp_client_id:
399 description:
400 - DHCP Client Identifier sent to the DHCP server.
401 type: str
402 primary:
403 description:
404 - This is only used with bond and is the primary interface name (for "active-backup" mode), this is the usually the
405 'ifname'.
406 type: str
407 miimon:
408 description:
409 - This is only used with bond - miimon.
410 - This parameter defaults to V(100) when unset.
411 type: int
412 downdelay:
413 description:
414 - This is only used with bond - downdelay.
415 type: int
416 updelay:
417 description:
418 - This is only used with bond - updelay.
419 type: int
420 xmit_hash_policy:
421 description:
422 - This is only used with bond - xmit_hash_policy type.
423 type: str
424 version_added: 5.6.0
425 fail_over_mac:
426 description:
427 - This is only used with bond - fail_over_mac.
428 type: str
429 choices: [none, active, follow]
430 version_added: 10.3.0
431 arp_interval:
432 description:
433 - This is only used with bond - ARP interval.
434 type: int
435 arp_ip_target:
436 description:
437 - This is only used with bond - ARP IP target.
438 type: str
439 stp:
440 description:
441 - This is only used with bridge and controls whether Spanning Tree Protocol (STP) is enabled for this bridge.
442 type: bool
443 default: true
444 priority:
445 description:
446 - This is only used with 'bridge' - sets STP priority.
447 type: int
448 default: 128
449 forwarddelay:
450 description:
451 - This is only used with bridge - [forward-delay <2-30>] STP forwarding delay, in seconds.
452 type: int
453 default: 15
454 hellotime:
455 description:
456 - This is only used with bridge - [hello-time <1-10>] STP hello time, in seconds.
457 type: int
458 default: 2
459 maxage:
460 description:
461 - This is only used with bridge - [max-age <6-42>] STP maximum message age, in seconds.
462 type: int
463 default: 20
464 ageingtime:
465 description:
466 - This is only used with bridge - [ageing-time <0-1000000>] the Ethernet MAC address aging time, in seconds.
467 type: int
468 default: 300
469 mac:
470 description:
471 - MAC address of the connection.
472 - Note this requires a recent kernel feature, originally introduced in 3.15 upstream kernel.
473 type: str
474 slavepriority:
475 description:
476 - This is only used with 'bridge-slave' - [<0-63>] - STP priority of this slave.
477 type: int
478 default: 32
479 path_cost:
480 description:
481 - This is only used with 'bridge-slave' - [<1-65535>] - STP port cost for destinations using this slave.
482 type: int
483 default: 100
484 hairpin:
485 description:
486 - This is only used with 'bridge-slave' - 'hairpin mode' for the slave, which allows frames to be sent back out through
487 the slave the frame was received on.
488 - The default change to V(false) in community.general 7.0.0. It used to be V(true) before.
489 type: bool
490 default: false
491 runner:
492 description:
493 - This is the type of device or network connection that you wish to create for a team.
494 type: str
495 choices: [broadcast, roundrobin, activebackup, loadbalance, lacp]
496 default: roundrobin
497 version_added: 3.4.0
498 runner_hwaddr_policy:
499 description:
500 - This defines the policy of how hardware addresses of team device and port devices should be set during the team lifetime.
501 type: str
502 choices: [same_all, by_active, only_active]
503 version_added: 3.4.0
504 runner_fast_rate:
505 description:
506 - Option specifies the rate at which our link partner is asked to transmit LACPDU packets. If this is V(true) then packets
507 are sent once per second. Otherwise they are sent every 30 seconds.
508 - Only allowed for O(runner=lacp).
509 type: bool
510 version_added: 6.5.0
511 vlanid:
512 description:
513 - This is only used with VLAN - VLAN ID in range <0-4095>.
514 type: int
515 vlandev:
516 description:
517 - This is only used with VLAN - parent device this VLAN is on, can use ifname.
518 type: str
519 flags:
520 description:
521 - This is only used with VLAN - flags.
522 type: str
523 ingress:
524 description:
525 - This is only used with VLAN - VLAN ingress priority mapping.
526 type: str
527 egress:
528 description:
529 - This is only used with VLAN - VLAN egress priority mapping.
530 type: str
531 vxlan_id:
532 description:
533 - This is only used with VXLAN - VXLAN ID.
534 type: int
535 vxlan_remote:
536 description:
537 - This is only used with VXLAN - VXLAN destination IP address.
538 type: str
539 vxlan_parent:
540 description:
541 - This is only used with VXLAN - VXLAN parent device (required when using a multicast remote address).
542 type: str
543 version_added: 12.2.0
544 vxlan_local:
545 description:
546 - This is only used with VXLAN - VXLAN local IP address.
547 type: str
548 ip_tunnel_dev:
549 description:
550 - This is used with GRE/IPIP/SIT - parent device this GRE/IPIP/SIT tunnel, can use ifname.
551 type: str
552 ip_tunnel_remote:
553 description:
554 - This is used with GRE/IPIP/SIT - GRE/IPIP/SIT destination IP address.
555 type: str
556 ip_tunnel_local:
557 description:
558 - This is used with GRE/IPIP/SIT - GRE/IPIP/SIT local IP address.
559 type: str
560 ip_tunnel_input_key:
561 description:
562 - The key used for tunnel input packets.
563 - Only used when O(type=gre).
564 type: str
565 version_added: 3.6.0
566 ip_tunnel_output_key:
567 description:
568 - The key used for tunnel output packets.
569 - Only used when O(type=gre).
570 type: str
571 version_added: 3.6.0
572 table:
573 description:
574 - This is only used with VRF - VRF table number.
575 type: int
576 version_added: 10.4.0
577 zone:
578 description:
579 - The trust level of the connection.
580 - When updating this property on a currently activated connection, the change takes effect immediately.
581 type: str
582 version_added: 2.0.0
583 wifi_sec:
584 description:
585 - The security configuration of the WiFi connection.
586 - Note the list of suboption attributes may vary depending on which version of NetworkManager/nmcli is installed on
587 the host.
588 - 'An up-to-date list of supported attributes can be found here: U(https://networkmanager.dev/docs/api/latest/settings-802-11-wireless-security.html).'
589 - 'For instance to use common WPA-PSK auth with a password: V({key-mgmt: wpa-psk, psk: my_password}).'
590 type: dict
591 suboptions:
592 auth-alg:
593 description:
594 - When WEP is used (that is, if O(wifi_sec.key-mgmt) is V(none) or V(ieee8021x)) indicate the 802.11 authentication
595 algorithm required by the AP here.
596 - One of V(open) for Open System, V(shared) for Shared Key, or V(leap) for Cisco LEAP.
597 - When using Cisco LEAP (that is, if O(wifi_sec.key-mgmt=ieee8021x) and O(wifi_sec.auth-alg=leap)) the O(wifi_sec.leap-username)
598 and O(wifi_sec.leap-password) properties must be specified.
599 type: str
600 choices: [open, shared, leap]
601 fils:
602 description:
603 - Indicates whether Fast Initial Link Setup (802.11ai) must be enabled for the connection.
604 - One of V(0) (use global default value), V(1) (disable FILS), V(2) (enable FILS if the supplicant and the access
605 point support it) or V(3) (enable FILS and fail if not supported).
606 - When set to V(0) and no global default is set, FILS is optionally enabled.
607 type: int
608 choices: [0, 1, 2, 3]
609 default: 0
610 group:
611 description:
612 - A list of group/broadcast encryption algorithms which prevents connections to Wi-Fi networks that do not utilize
613 one of the algorithms in the list.
614 - For maximum compatibility leave this property empty.
615 type: list
616 elements: str
617 choices: [wep40, wep104, tkip, ccmp]
618 key-mgmt:
619 description:
620 - Key management used for the connection.
621 - One of V(none) (WEP or no password protection), V(ieee8021x) (Dynamic WEP), V(owe) (Opportunistic Wireless Encryption),
622 V(wpa-psk) (WPA2 + WPA3 personal), V(sae) (WPA3 personal only), V(wpa-eap) (WPA2 + WPA3 enterprise) or V(wpa-eap-suite-b-192)
623 (WPA3 enterprise only).
624 - This property must be set for any Wi-Fi connection that uses security.
625 type: str
626 choices: [none, ieee8021x, owe, wpa-psk, sae, wpa-eap, wpa-eap-suite-b-192]
627 leap-password-flags:
628 description: Flags indicating how to handle the O(wifi_sec.leap-password) property.
629 type: list
630 elements: int
631 leap-password:
632 description: The login password for legacy LEAP connections (that is, if O(wifi_sec.key-mgmt=ieee8021x) and O(wifi_sec.auth-alg=leap)).
633 type: str
634 leap-username:
635 description: The login username for legacy LEAP connections (that is, if O(wifi_sec.key-mgmt=ieee8021x) and O(wifi_sec.auth-alg=leap)).
636 type: str
637 pairwise:
638 description:
639 - A list of pairwise encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one
640 of the algorithms in the list.
641 - For maximum compatibility leave this property empty.
642 type: list
643 elements: str
644 choices: [tkip, ccmp]
645 pmf:
646 description:
647 - Indicates whether Protected Management Frames (802.11w) must be enabled for the connection.
648 - One of V(0) (use global default value), V(1) (disable PMF), V(2) (enable PMF if the supplicant and the access
649 point support it) or V(3) (enable PMF and fail if not supported).
650 - When set to V(0) and no global default is set, PMF is optionally enabled.
651 type: int
652 choices: [0, 1, 2, 3]
653 default: 0
654 proto:
655 description:
656 - List of strings specifying the allowed WPA protocol versions to use.
657 - Each element may be V(wpa) (allow WPA) or V(rsn) (allow WPA2/RSN).
658 - If not specified, both WPA and RSN connections are allowed.
659 type: list
660 elements: str
661 choices: [wpa, rsn]
662 psk-flags:
663 description: Flags indicating how to handle the O(wifi_sec.psk) property.
664 type: list
665 elements: int
666 psk:
667 description:
668 - Pre-Shared-Key for WPA networks.
669 - For WPA-PSK, it is either an ASCII passphrase of 8 to 63 characters that is (as specified in the 802.11i standard)
670 hashed to derive the actual key, or the key in form of 64 hexadecimal character.
671 - The WPA3-Personal networks use a passphrase of any length for SAE authentication.
672 type: str
673 wep-key-flags:
674 description:
675 - Flags indicating how to handle the O(wifi_sec.wep-key0), O(wifi_sec.wep-key1), O(wifi_sec.wep-key2), and O(wifi_sec.wep-key3)
676 properties.
677 type: list
678 elements: int
679 wep-key-type:
680 description:
681 - Controls the interpretation of WEP keys.
682 - Allowed values are V(1), in which case the key is either a 10- or 26-character hexadecimal string, or a 5- or
683 13-character ASCII password; or V(2), in which case the passphrase is provided as a string and it is hashed using
684 the de-facto MD5 method to derive the actual WEP key.
685 type: int
686 choices: [1, 2]
687 wep-key0:
688 description:
689 - Index 0 WEP key. This is the WEP key used in most networks.
690 - See the O(wifi_sec.wep-key-type) property for a description of how this key is interpreted.
691 type: str
692 wep-key1:
693 description:
694 - Index 1 WEP key. This WEP index is not used by most networks.
695 - See the O(wifi_sec.wep-key-type) property for a description of how this key is interpreted.
696 type: str
697 wep-key2:
698 description:
699 - Index 2 WEP key. This WEP index is not used by most networks.
700 - See the O(wifi_sec.wep-key-type) property for a description of how this key is interpreted.
701 type: str
702 wep-key3:
703 description:
704 - Index 3 WEP key. This WEP index is not used by most networks.
705 - See the O(wifi_sec.wep-key-type) property for a description of how this key is interpreted.
706 type: str
707 wep-tx-keyidx:
708 description:
709 - When static WEP is used (that is, if O(wifi_sec.key-mgmt=none)) and a non-default WEP key index is used by the
710 AP, put that WEP key index here.
711 - Valid values are V(0) (default key) through V(3).
712 - Note that some consumer access points (like the Linksys WRT54G) number the keys V(1) to V(4).
713 type: int
714 choices: [0, 1, 2, 3]
715 default: 0
716 wps-method:
717 description:
718 - Flags indicating which mode of WPS is to be used if any.
719 - There is little point in changing the default setting as NetworkManager automatically determines whether it is
720 feasible to start WPS enrollment from the Access Point capabilities.
721 - WPS can be disabled by setting this property to a value of V(1).
722 type: int
723 default: 0
724 version_added: 3.0.0
725 ssid:
726 description:
727 - Name of the Wireless router or the access point.
728 type: str
729 version_added: 3.0.0
730 wifi:
731 description:
732 - The configuration of the WiFi connection.
733 - Note the list of suboption attributes may vary depending on which version of NetworkManager/nmcli is installed on
734 the host.
735 - 'An up-to-date list of supported attributes can be found here: U(https://networkmanager.dev/docs/api/latest/settings-802-11-wireless.html).'
736 - 'For instance to create a hidden AP mode WiFi connection: V({hidden: true, mode: ap}).'
737 type: dict
738 suboptions:
739 ap-isolation:
740 description:
741 - Configures AP isolation, which prevents communication between wireless devices connected to this AP.
742 - This property can be set to a value different from V(-1) only when the interface is configured in AP mode.
743 - If set to V(1), devices are not able to communicate with each other. This increases security because it protects
744 devices against attacks from other clients in the network. At the same time, it prevents devices to access resources
745 on the same wireless networks as file shares, printers, and so on.
746 - If set to V(0), devices can talk to each other.
747 - When set to V(-1), the global default is used; in case the global default is unspecified it is assumed to be V(0).
748 type: int
749 choices: [-1, 0, 1]
750 default: -1
751 assigned-mac-address:
752 description:
753 - The new field for the cloned MAC address.
754 - It can be either a hardware address in ASCII representation, or one of the special values V(preserve), V(permanent),
755 V(random) or V(stable).
756 - This field replaces the deprecated O(wifi.cloned-mac-address) on D-Bus, which can only contain explicit hardware
757 addresses.
758 - Note that this property only exists in D-Bus API. libnm and nmcli continue to call this property C(cloned-mac-address).
759 type: str
760 band:
761 description:
762 - 802.11 frequency band of the network.
763 - One of V(a) for 5GHz 802.11a or V(bg) for 2.4GHz 802.11.
764 - This locks associations to the Wi-Fi network to the specific band, so for example, if V(a) is specified, the device
765 does not associate with the same network in the 2.4GHz band even if the network's settings are compatible.
766 - This setting depends on specific driver capability and may not work with all drivers.
767 type: str
768 choices: [a, bg]
769 bssid:
770 description:
771 - If specified, directs the device to only associate with the given access point.
772 - This capability is highly driver dependent and not supported by all devices.
773 - Note this property does not control the BSSID used when creating an Ad-Hoc network and is unlikely to in the future.
774 type: str
775 channel:
776 description:
777 - Wireless channel to use for the Wi-Fi connection.
778 - The device only joins (or creates for Ad-Hoc networks) a Wi-Fi network on the specified channel.
779 - Because channel numbers overlap between bands, this property also requires the O(wifi.band) property to be set.
780 type: int
781 default: 0
782 cloned-mac-address:
783 description:
784 - This D-Bus field is deprecated in favor of O(wifi.assigned-mac-address) which is more flexible and allows specifying
785 special variants like V(random).
786 - For libnm and nmcli, this field is called C(cloned-mac-address).
787 type: str
788 generate-mac-address-mask:
789 description:
790 - With O(wifi.cloned-mac-address) setting V(random) or V(stable), by default all bits of the MAC address are scrambled
791 and a locally-administered, unicast MAC address is created. This property allows to specify that certain bits
792 are fixed.
793 - Note that the least significant bit of the first MAC address is always unset to create a unicast MAC address.
794 - If the property is V(null), it is eligible to be overwritten by a default connection setting.
795 - If the value is still V(null) or an empty string, the default is to create a locally-administered, unicast MAC
796 address.
797 - If the value contains one MAC address, this address is used as mask. The set bits of the mask are to be filled
798 with the current MAC address of the device, while the unset bits are subject to randomization.
799 - Setting V(FE:FF:FF:00:00:00) means to preserve the OUI of the current MAC address and only randomize the lower
800 3 bytes using the V(random) or V(stable) algorithm.
801 - If the value contains one additional MAC address after the mask, this address is used instead of the current MAC
802 address to fill the bits that shall not be randomized.
803 - For example, a value of V(FE:FF:FF:00:00:00 68:F7:28:00:00:00) sets the OUI of the MAC address to 68:F7:28, while
804 the lower bits are randomized.
805 - A value of V(02:00:00:00:00:00 00:00:00:00:00:00) creates a fully scrambled globally-administered, burned-in MAC
806 address.
807 - If the value contains more than one additional MAC addresses, one of them is chosen randomly. For example, V(02:00:00:00:00:00
808 00:00:00:00:00:00 02:00:00:00:00:00) creates a fully scrambled MAC address, randomly locally or globally administered.
809 type: str
810 hidden:
811 description:
812 - If V(true), indicates that the network is a non-broadcasting network that hides its SSID. This works both in infrastructure
813 and AP mode.
814 - In infrastructure mode, various workarounds are used for a more reliable discovery of hidden networks, such as
815 probe-scanning the SSID. However, these workarounds expose inherent insecurities with hidden SSID networks, and
816 thus hidden SSID networks should be used with caution.
817 - In AP mode, the created network does not broadcast its SSID.
818 - Note that marking the network as hidden may be a privacy issue for you (in infrastructure mode) or client stations
819 (in AP mode), as the explicit probe-scans are distinctly recognizable on the air.
820 type: bool
821 default: false
822 mac-address-blacklist:
823 description:
824 - A list of permanent MAC addresses of Wi-Fi devices to which this connection should never apply.
825 - Each MAC address should be given in the standard hex-digits-and-colons notation (for example, V(00:11:22:33:44:55)).
826 type: list
827 elements: str
828 mac-address-randomization:
829 description:
830 - One of V(0) (never randomize unless the user has set a global default to randomize and the supplicant supports
831 randomization), V(1) (never randomize the MAC address), or V(2) (always randomize the MAC address).
832 - This property is deprecated for O(wifi.cloned-mac-address).
833 type: int
834 default: 0
835 choices: [0, 1, 2]
836 mac-address:
837 description:
838 - If specified, this connection only applies to the Wi-Fi device whose permanent MAC address matches.
839 - This property does not change the MAC address of the device (for example for MAC spoofing).
840 type: str
841 mode:
842 description: Wi-Fi network mode. If blank, V(infrastructure) is assumed.
843 type: str
844 choices: [infrastructure, mesh, adhoc, ap]
845 default: infrastructure
846 mtu:
847 description: If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into
848 multiple Ethernet frames.
849 type: int
850 default: 0
851 powersave:
852 description:
853 - One of V(2) (disable Wi-Fi power saving), V(3) (enable Wi-Fi power saving), V(1) (do not touch currently configure
854 setting) or V(0) (use the globally configured value).
855 - All other values are reserved.
856 type: int
857 default: 0
858 choices: [0, 1, 2, 3]
859 rate:
860 description:
861 - If non-zero, directs the device to only use the specified bitrate for communication with the access point.
862 - Units are in Kb/s, so for example V(5500) = 5.5 Mbit/s.
863 - This property is highly driver dependent and not all devices support setting a static bitrate.
864 type: int
865 default: 0
866 tx-power:
867 description:
868 - If non-zero, directs the device to use the specified transmit power.
869 - Units are dBm.
870 - This property is highly driver dependent and not all devices support setting a static transmit power.
871 type: int
872 default: 0
873 wake-on-wlan:
874 description:
875 - The NMSettingWirelessWakeOnWLan options to enable. Not all devices support all options.
876 - May be any combination of C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_ANY) (V(0x2)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_DISCONNECT)
877 (V(0x4)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_MAGIC) (V(0x8)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_GTK_REKEY_FAILURE)
878 (V(0x10)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_EAP_IDENTITY_REQUEST) (V(0x20)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_4WAY_HANDSHAKE)
879 (V(0x40)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_RFKILL_RELEASE) (V(0x80)), C(NM_SETTING_WIRELESS_WAKE_ON_WLAN_TCP)
880 (V(0x100)) or the special values V(0x1) (to use global settings) and V(0x8000) (to disable management of Wake-on-LAN
881 in NetworkManager).
882 - Note the option values' sum must be specified in order to combine multiple options.
883 type: int
884 default: 1
885 version_added: 3.5.0
886 ignore_unsupported_suboptions:
887 description:
888 - Ignore suboptions which are invalid or unsupported by the version of NetworkManager/nmcli installed on the host.
889 - Only O(wifi) and O(wifi_sec) options are currently affected.
890 type: bool
891 default: false
892 version_added: 3.6.0
893 gsm:
894 description:
895 - The configuration of the GSM connection.
896 - Note the list of suboption attributes may vary depending on which version of NetworkManager/nmcli is installed on
897 the host.
898 - 'An up-to-date list of supported attributes can be found here: U(https://networkmanager.dev/docs/api/latest/settings-gsm.html).'
899 - 'For instance to use apn, pin, username and password: V({apn: provider.apn, pin: 1234, username: apn.username, password:
900 apn.password}).'
901 type: dict
902 version_added: 3.7.0
903 suboptions:
904 apn:
905 description:
906 - The GPRS Access Point Name specifying the APN used when establishing a data session with the GSM-based network.
907 - The APN often determines how the user is billed for their network usage and whether the user has access to the
908 Internet or just a provider-specific walled-garden, so it is important to use the correct APN for the user's mobile
909 broadband plan.
910 - The APN may only be composed of the characters a-z, 0-9, ., and - per GSM 03.60 Section 14.9.
911 type: str
912 auto-config:
913 description: When V(true), the settings such as O(gsm.apn), O(gsm.username), or O(gsm.password) default to values
914 that match the network the modem registers to in the Mobile Broadband Provider database.
915 type: bool
916 default: false
917 device-id:
918 description:
919 - The device unique identifier (as given by the V(WWAN) management service) which this connection applies to.
920 - If given, the connection only applies to the specified device.
921 type: str
922 home-only:
923 description:
924 - When V(true), only connections to the home network are allowed.
925 - Connections to roaming networks are not made.
926 type: bool
927 default: false
928 mtu:
929 description: If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into
930 multiple Ethernet frames.
931 type: int
932 default: 0
933 network-id:
934 description:
935 - The Network ID (GSM LAI format, ie MCC-MNC) to force specific network registration.
936 - If the Network ID is specified, NetworkManager attempts to force the device to register only on the specified
937 network.
938 - This can be used to ensure that the device does not roam when direct roaming control of the device is not otherwise
939 possible.
940 type: str
941 number:
942 description: Legacy setting that used to help establishing PPP data sessions for GSM-based modems.
943 type: str
944 password:
945 description:
946 - The password used to authenticate with the network, if required.
947 - Many providers do not require a password, or accept any password.
948 - But if a password is required, it is specified here.
949 type: str
950 password-flags:
951 description:
952 - NMSettingSecretFlags indicating how to handle the O(gsm.password) property.
953 - 'Following choices are allowed: V(0) B(NONE): The system is responsible for providing and storing this secret
954 (default), V(1) B(AGENT_OWNED): A user secret agent is responsible for providing and storing this secret; when
955 it is required agents are asked to retrieve it V(2) B(NOT_SAVED): This secret should not be saved, but should
956 be requested from the user each time it is needed V(4) B(NOT_REQUIRED): In situations where it cannot be automatically
957 determined that the secret is required (some VPNs and PPP providers do not require all secrets) this flag indicates
958 that the specific secret is not required.'
959 type: int
960 choices: [0, 1, 2, 4]
961 default: 0
962 pin:
963 description:
964 - If the SIM is locked with a PIN it must be unlocked before any other operations are requested.
965 - Specify the PIN here to allow operation of the device.
966 type: str
967 pin-flags:
968 description:
969 - NMSettingSecretFlags indicating how to handle the O(gsm.pin) property.
970 - See O(gsm.password-flags) for NMSettingSecretFlags choices.
971 type: int
972 choices: [0, 1, 2, 4]
973 default: 0
974 sim-id:
975 description:
976 - The SIM card unique identifier (as given by the C(WWAN) management service) which this connection applies to.
977 - If given, the connection applies to any device also allowed by O(gsm.device-id) which contains a SIM card matching
978 the given identifier.
979 type: str
980 sim-operator-id:
981 description:
982 - A MCC/MNC string like V(310260) or V(21601I) identifying the specific mobile network operator which this connection
983 applies to.
984 - If given, the connection applies to any device also allowed by O(gsm.device-id) and O(gsm.sim-id) which contains
985 a SIM card provisioned by the given operator.
986 type: str
987 username:
988 description:
989 - The username used to authenticate with the network, if required.
990 - Many providers do not require a username, or accept any username.
991 - But if a username is required, it is specified here.
992 macvlan:
993 description:
994 - The configuration of the MAC VLAN connection.
995 - Note the list of suboption attributes may vary depending on which version of NetworkManager/nmcli is installed on
996 the host.
997 - 'An up-to-date list of supported attributes can be found here: U(https://networkmanager.dev/docs/api/latest/settings-macvlan.html).'
998 type: dict
999 version_added: 6.6.0
1000 suboptions:
1001 mode:
1002 description:
1003 - The macvlan mode, which specifies the communication mechanism between multiple macvlans on the same lower device.
1004 - 'Following choices are allowed: V(1) B(vepa), V(2) B(bridge), V(3) B(private), V(4) B(passthru) and V(5) B(source).'
1005 type: int
1006 choices: [1, 2, 3, 4, 5]
1007 required: true
1008 parent:
1009 description:
1010 - If given, specifies the parent interface name or parent connection UUID from which this MAC-VLAN interface should
1011 be created. If this property is not specified, the connection must contain an "802-3-ethernet" setting with a
1012 "mac-address" property.
1013 type: str
1014 required: true
1015 promiscuous:
1016 description:
1017 - Whether the interface should be put in promiscuous mode.
1018 type: bool
1019 tap:
1020 description:
1021 - Whether the interface should be a MACVTAP.
1022 type: bool
1023 wireguard:
1024 description:
1025 - The configuration of the Wireguard connection.
1026 - Note the list of suboption attributes may vary depending on which version of NetworkManager/nmcli is installed on
1027 the host.
1028 - 'An up-to-date list of supported attributes can be found here: U(https://networkmanager.dev/docs/api/latest/settings-wireguard.html).'
1029 - 'For instance to configure a listen port: V({listen-port: 12345}).'
1030 type: dict
1031 version_added: 4.3.0
1032 suboptions:
1033 fwmark:
1034 description:
1035 - The 32-bit fwmark for outgoing packets.
1036 - The use of fwmark is optional and is by default off. Setting it to 0 disables it.
1037 - Note that O(wireguard.ip4-auto-default-route) or O(wireguard.ip6-auto-default-route) enabled, implies to automatically
1038 choose a fwmark.
1039 type: int
1040 ip4-auto-default-route:
1041 description:
1042 - Whether to enable special handling of the IPv4 default route.
1043 - If enabled, the IPv4 default route from O(wireguard.peer-routes) is placed to a dedicated routing-table and two
1044 policy routing rules are added.
1045 - The fwmark number is also used as routing-table for the default-route, and if fwmark is zero, an unused fwmark/table
1046 is chosen automatically. This corresponds to what wg-quick does with Table=auto and what WireGuard calls "Improved
1047 Rule-based Routing".
1048 type: bool
1049 ip6-auto-default-route:
1050 description:
1051 - Like O(wireguard.ip4-auto-default-route), but for the IPv6 default route.
1052 type: bool
1053 listen-port:
1054 description: The WireGuard connection listen-port. If not specified, the port is chosen randomly when the interface
1055 comes up.
1056 type: int
1057 mtu:
1058 description:
1059 - If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple
1060 fragments.
1061 - If zero a default MTU is used. Note that contrary to wg-quick's MTU setting, this does not take into account the
1062 current routes at the time of activation.
1063 type: int
1064 peer-routes:
1065 description:
1066 - Whether to automatically add routes for the AllowedIPs ranges of the peers.
1067 - If V(true) (the default), NetworkManager automatically adds routes in the routing tables according to C(ipv4.route-table)
1068 and C(ipv6.route-table). Usually you want this automatism enabled.
1069 - If V(false), no such routes are added automatically. In this case, the user may want to configure static routes
1070 in C(ipv4.routes) and C(ipv6.routes), respectively.
1071 - Note that if the peer's AllowedIPs is V(0.0.0.0/0) or V(::/0) and the profile's C(ipv4.never-default) or C(ipv6.never-default)
1072 setting is enabled, the peer route for this peer is not added automatically.
1073 type: bool
1074 private-key:
1075 description: The 256 bit private-key in base64 encoding.
1076 type: str
1077 private-key-flags:
1078 description: C(NMSettingSecretFlags) indicating how to handle the O(wireguard.private-key) property.
1079 type: int
1080 choices: [0, 1, 2]
1081 vpn:
1082 description:
1083 - Configuration of a VPN connection (PPTP and L2TP).
1084 - In order to use L2TP you need to be sure that C(network-manager-l2tp) - and C(network-manager-l2tp-gnome) if host
1085 has UI - are installed on the host.
1086 type: dict
1087 version_added: 5.1.0
1088 suboptions:
1089 permissions:
1090 description: User that has permission to use the connection.
1091 type: str
1092 required: true
1093 service-type:
1094 description: This defines the service type of connection.
1095 type: str
1096 required: true
1097 gateway:
1098 description: The gateway to connection. It can be an IP address (for example V(192.0.2.1)) or a FQDN address (for
1099 example V(vpn.example.com)).
1100 type: str
1101 required: true
1102 password-flags:
1103 description:
1104 - NMSettingSecretFlags indicating how to handle the C(vpn.password) property.
1105 - 'Following choices are allowed: V(0) B(NONE): The system is responsible for providing and storing this secret
1106 (default); V(1) B(AGENT_OWNED): A user secret agent is responsible for providing and storing this secret; when
1107 it is required agents are asked to retrieve it; V(2) B(NOT_SAVED): This secret should not be saved, but should
1108 be requested from the user each time it is needed; V(4) B(NOT_REQUIRED): In situations where it cannot be automatically
1109 determined that the secret is required (some VPNs and PPP providers do not require all secrets) this flag indicates
1110 that the specific secret is not required.'
1111 type: int
1112 choices: [0, 1, 2, 4]
1113 default: 0
1114 user:
1115 description: Username provided by VPN administrator.
1116 type: str
1117 required: true
1118 ipsec-enabled:
1119 description:
1120 - Enable or disable IPSec tunnel to L2TP host.
1121 - This option is need when O(vpn.service-type) is V(org.freedesktop.NetworkManager.l2tp).
1122 type: bool
1123 ipsec-psk:
1124 description:
1125 - The pre-shared key in base64 encoding.
1126 - >
1127 You can encode using this Ansible Jinja2 expression: V("0s{{ '[YOUR PRE-SHARED KEY]' | ansible.builtin.b64encode }}").
1128 - This is only used when O(vpn.ipsec-enabled=true).
1129 type: str
1130 sriov:
1131 description:
1132 - Allow to configure SR-IOV settings.
1133 - 'An up-to-date list of supported attributes can be found here:
1134 U(https://networkmanager.pages.freedesktop.org/NetworkManager/NetworkManager/settings-sriov.html).'
1135 type: dict
1136 version_added: 10.1.0
1137 suboptions:
1138 autoprobe-drivers:
1139 description:
1140 - Whether to autoprobe virtual functions by a compatible driver.
1141 type: int
1142 eswitch-encap-mode:
1143 description:
1144 - Select the eswitch encapsulation support.
1145 type: int
1146 eswitch-inline-mode:
1147 description:
1148 - Select the eswitch inline-mode of the device.
1149 type: int
1150 eswitch-mode:
1151 description:
1152 - Select the eswitch mode of the device.
1153 type: int
1154 total-vfs:
1155 description: Number of virtual functions to create. Consult your NIC documentation for the maximum number of VFs supported.
1156 type: int
1157 vfs:
1158 description:
1159 - 'Virtual function descriptors in the form: V(INDEX [ATTR=VALUE[ ATTR=VALUE]...]).'
1160 - Multiple VFs can be specified using a comma as separator, for example V(2 mac=00:11:22:33:44:55 spoof-check=true,3
1161 vlans=100).
1162 type: str
1163 """
1164
1165 EXAMPLES = r"""
1166 # These examples are using the following inventory:
1167 #
1168 # ## Directory layout:
1169 #
1170 # |_/inventory/cloud-hosts
1171 # | /group_vars/openstack-stage.yml
1172 # | /host_vars/controller-01.openstack.host.com
1173 # | /host_vars/controller-02.openstack.host.com
1174 # |_/playbook/library/nmcli.py
1175 # | /playbook-add.yml
1176 # | /playbook-del.yml
1177 # ```
1178 #
1179 # ## inventory examples
1180 # ### groups_vars
1181 # ```yml
1182 # ---
1183 # #devops_os_define_network
1184 # storage_gw: "192.0.2.254"
1185 # external_gw: "198.51.100.254"
1186 # tenant_gw: "203.0.113.254"
1187 #
1188 # #Team vars
1189 # nmcli_team:
1190 # - conn_name: tenant
1191 # ip4: '{{ tenant_ip }}'
1192 # gw4: '{{ tenant_gw }}'
1193 # - conn_name: external
1194 # ip4: '{{ external_ip }}'
1195 # gw4: '{{ external_gw }}'
1196 # - conn_name: storage
1197 # ip4: '{{ storage_ip }}'
1198 # gw4: '{{ storage_gw }}'
1199 # nmcli_team_slave:
1200 # - conn_name: em1
1201 # ifname: em1
1202 # master: tenant
1203 # - conn_name: em2
1204 # ifname: em2
1205 # master: tenant
1206 # - conn_name: p2p1
1207 # ifname: p2p1
1208 # master: storage
1209 # - conn_name: p2p2
1210 # ifname: p2p2
1211 # master: external
1212 #
1213 # #bond vars
1214 # nmcli_bond:
1215 # - conn_name: tenant
1216 # ip4: '{{ tenant_ip }}'
1217 # gw4: ''
1218 # mode: balance-rr
1219 # - conn_name: external
1220 # ip4: '{{ external_ip }}'
1221 # gw4: ''
1222 # mode: balance-rr
1223 # - conn_name: storage
1224 # ip4: '{{ storage_ip }}'
1225 # gw4: '{{ storage_gw }}'
1226 # mode: balance-rr
1227 # nmcli_bond_slave:
1228 # - conn_name: em1
1229 # ifname: em1
1230 # master: tenant
1231 # - conn_name: em2
1232 # ifname: em2
1233 # master: tenant
1234 # - conn_name: p2p1
1235 # ifname: p2p1
1236 # master: storage
1237 # - conn_name: p2p2
1238 # ifname: p2p2
1239 # master: external
1240 #
1241 # #ethernet vars
1242 # nmcli_ethernet:
1243 # - conn_name: em1
1244 # ifname: em1
1245 # ip4:
1246 # - '{{ tenant_ip }}'
1247 # - '{{ second_tenant_ip }}'
1248 # gw4: '{{ tenant_gw }}'
1249 # - conn_name: em2
1250 # ifname: em2
1251 # ip4: '{{ tenant_ip1 }}'
1252 # gw4: '{{ tenant_gw }}'
1253 # - conn_name: p2p1
1254 # ifname: p2p1
1255 # ip4: '{{ storage_ip }}'
1256 # gw4: '{{ storage_gw }}'
1257 # - conn_name: p2p2
1258 # ifname: p2p2
1259 # ip4: '{{ external_ip }}'
1260 # gw4: '{{ external_gw }}'
1261 # ```
1262 #
1263 # ### host_vars
1264 # ```yml
1265 # ---
1266 # storage_ip: "192.0.2.91/23"
1267 # external_ip: "198.51.100.23/21"
1268 # tenant_ip: "203.0.113.77/23"
1269 # second_tenant_ip: "204.0.113.77/23"
1270 # ```
1271
1272
1273 ## playbook-add.yml example
1274
1275 - hosts: openstack-stage
1276 remote_user: root
1277 tasks:
1278
1279 - name: Install needed network manager libs
1280 ansible.builtin.package:
1281 name:
1282 - NetworkManager-libnm
1283 - nm-connection-editor
1284 - libsemanage-python
1285 - policycoreutils-python
1286 state: present
1287
1288 ##### Working with all cloud nodes - Teaming
1289 - name: Try nmcli add team - conn_name only & ip4 gw4
1290 community.general.nmcli:
1291 type: team
1292 conn_name: '{{ item.conn_name }}'
1293 ip4: '{{ item.ip4 }}'
1294 gw4: '{{ item.gw4 }}'
1295 state: present
1296 with_items:
1297 - '{{ nmcli_team }}'
1298
1299 - name: Try nmcli add teams-slave
1300 community.general.nmcli:
1301 type: team-slave
1302 conn_name: '{{ item.conn_name }}'
1303 ifname: '{{ item.ifname }}'
1304 master: '{{ item.master }}'
1305 state: present
1306 with_items:
1307 - '{{ nmcli_team_slave }}'
1308
1309 ##### Working with all cloud nodes - Bonding
1310 - name: Try nmcli add bond - conn_name only & ip4 gw4 mode
1311 community.general.nmcli:
1312 type: bond
1313 conn_name: '{{ item.conn_name }}'
1314 ip4: '{{ item.ip4 }}'
1315 gw4: '{{ item.gw4 }}'
1316 mode: '{{ item.mode }}'
1317 state: present
1318 with_items:
1319 - '{{ nmcli_bond }}'
1320
1321 - name: Try nmcli add bond-slave
1322 community.general.nmcli:
1323 type: bond-slave
1324 conn_name: '{{ item.conn_name }}'
1325 ifname: '{{ item.ifname }}'
1326 master: '{{ item.master }}'
1327 state: present
1328 with_items:
1329 - '{{ nmcli_bond_slave }}'
1330
1331 ##### Working with all cloud nodes - Ethernet
1332 - name: Try nmcli add Ethernet - conn_name only & ip4 gw4
1333 community.general.nmcli:
1334 type: ethernet
1335 conn_name: '{{ item.conn_name }}'
1336 ip4: '{{ item.ip4 }}'
1337 gw4: '{{ item.gw4 }}'
1338 state: present
1339 with_items:
1340 - '{{ nmcli_ethernet }}'
1341
1342 ## playbook-del.yml example
1343 - hosts: openstack-stage
1344 remote_user: root
1345 tasks:
1346
1347 - name: Try nmcli del team - multiple
1348 community.general.nmcli:
1349 conn_name: '{{ item.conn_name }}'
1350 state: absent
1351 with_items:
1352 - conn_name: em1
1353 - conn_name: em2
1354 - conn_name: p1p1
1355 - conn_name: p1p2
1356 - conn_name: p2p1
1357 - conn_name: p2p2
1358 - conn_name: tenant
1359 - conn_name: storage
1360 - conn_name: external
1361 - conn_name: team-em1
1362 - conn_name: team-em2
1363 - conn_name: team-p1p1
1364 - conn_name: team-p1p2
1365 - conn_name: team-p2p1
1366 - conn_name: team-p2p2
1367
1368 - name: Add an Ethernet connection with static IP configuration
1369 community.general.nmcli:
1370 conn_name: my-eth1
1371 ifname: eth1
1372 type: ethernet
1373 ip4: 192.0.2.100/24
1374 gw4: 192.0.2.1
1375 state: present
1376
1377 - name: Add an Team connection with static IP configuration
1378 community.general.nmcli:
1379 conn_name: my-team1
1380 ifname: my-team1
1381 type: team
1382 ip4: 192.0.2.100/24
1383 gw4: 192.0.2.1
1384 state: present
1385 autoconnect: true
1386
1387 - name: Optionally, at the same time specify IPv6 addresses for the device
1388 community.general.nmcli:
1389 conn_name: my-eth1
1390 ifname: eth1
1391 type: ethernet
1392 ip4: 192.0.2.100/24
1393 gw4: 192.0.2.1
1394 ip6: 2001:db8::cafe
1395 gw6: 2001:db8::1
1396 state: present
1397
1398 - name: Add two IPv4 DNS server addresses
1399 community.general.nmcli:
1400 conn_name: my-eth1
1401 type: ethernet
1402 dns4:
1403 - 192.0.2.53
1404 - 198.51.100.53
1405 state: present
1406
1407 - name: Make a profile usable for all compatible Ethernet interfaces
1408 community.general.nmcli:
1409 ctype: ethernet
1410 name: my-eth1
1411 ifname: '*'
1412 state: present
1413
1414 - name: Change the property of a setting e.g. MTU
1415 community.general.nmcli:
1416 conn_name: my-eth1
1417 mtu: 9000
1418 type: ethernet
1419 state: present
1420
1421 - name: Change the property of a setting e.g. MTU and reload connection
1422 community.general.nmcli:
1423 conn_name: my-eth1
1424 mtu: 1500
1425 type: ethernet
1426 state: present
1427 conn_reload: true
1428
1429 - name: Disable connection
1430 community.general.nmcli:
1431 conn_name: my-eth1
1432 state: down
1433
1434 - name: Reload and enable connection
1435 community.general.nmcli:
1436 conn_name: my-eth1
1437 state: up
1438 conn_reload: true
1439
1440 - name: Add second ip4 address
1441 community.general.nmcli:
1442 conn_name: my-eth1
1443 ifname: eth1
1444 type: ethernet
1445 ip4:
1446 - 192.0.2.100/24
1447 - 192.0.3.100/24
1448 state: present
1449
1450 - name: Add second ip6 address
1451 community.general.nmcli:
1452 conn_name: my-eth1
1453 ifname: eth1
1454 type: ethernet
1455 ip6:
1456 - 2001:db8::cafe
1457 - 2002:db8::cafe
1458 state: present
1459
1460 - name: Add VxLan
1461 community.general.nmcli:
1462 type: vxlan
1463 conn_name: vxlan_test1
1464 vxlan_id: 16
1465 vxlan_local: 192.168.1.2
1466 vxlan_remote: 192.168.1.5
1467
1468 - name: Add VxLan via multicast on a bridge
1469 community.general.nmcli:
1470 type: vxlan
1471 conn_name: vxlan_test2
1472 vxlan_id: 17
1473 vxlan_parent: eth1
1474 vxlan_local: 192.168.1.2
1475 vxlan_remote: 239.192.0.17
1476 slave_type: bridge
1477 master: br0
1478
1479 - name: Add gre
1480 community.general.nmcli:
1481 type: gre
1482 conn_name: gre_test1
1483 ip_tunnel_dev: eth0
1484 ip_tunnel_local: 192.168.1.2
1485 ip_tunnel_remote: 192.168.1.5
1486
1487 - name: Add ipip
1488 community.general.nmcli:
1489 type: ipip
1490 conn_name: ipip_test1
1491 ip_tunnel_dev: eth0
1492 ip_tunnel_local: 192.168.1.2
1493 ip_tunnel_remote: 192.168.1.5
1494
1495 - name: Add sit
1496 community.general.nmcli:
1497 type: sit
1498 conn_name: sit_test1
1499 ip_tunnel_dev: eth0
1500 ip_tunnel_local: 192.168.1.2
1501 ip_tunnel_remote: 192.168.1.5
1502
1503 - name: Add zone
1504 community.general.nmcli:
1505 type: ethernet
1506 conn_name: my-eth1
1507 zone: external
1508 state: present
1509
1510 # nmcli exits with status 0 if it succeeds and exits with a status greater
1511 # than zero when there is a failure. The following list of status codes may be
1512 # returned:
1513 #
1514 # - 0 Success - indicates the operation succeeded
1515 # - 1 Unknown or unspecified error
1516 # - 2 Invalid user input, wrong nmcli invocation
1517 # - 3 Timeout expired (see --wait option)
1518 # - 4 Connection activation failed
1519 # - 5 Connection deactivation failed
1520 # - 6 Disconnecting device failed
1521 # - 7 Connection deletion failed
1522 # - 8 NetworkManager is not running
1523 # - 9 nmcli and NetworkManager versions mismatch
1524 # - 10 Connection, device, or access point does not exist.
1525
1526 - name: Create the wifi connection
1527 community.general.nmcli:
1528 type: wifi
1529 conn_name: Brittany
1530 ifname: wlp4s0
1531 ssid: Brittany
1532 wifi_sec:
1533 key-mgmt: wpa-psk
1534 psk: my_password
1535 autoconnect: true
1536 state: present
1537
1538 - name: Create a hidden AP mode wifi connection
1539 community.general.nmcli:
1540 type: wifi
1541 conn_name: ChocoMaster
1542 ifname: wlo1
1543 ssid: ChocoMaster
1544 wifi:
1545 hidden: true
1546 mode: ap
1547 autoconnect: true
1548 state: present
1549
1550 - name: Create a gsm connection
1551 community.general.nmcli:
1552 type: gsm
1553 conn_name: my-gsm-provider
1554 ifname: cdc-wdm0
1555 gsm:
1556 apn: my.provider.apn
1557 username: my-provider-username
1558 password: my-provider-password
1559 pin: my-sim-pin
1560 autoconnect: true
1561 state: present
1562
1563 - name: Create a macvlan connection
1564 community.general.nmcli:
1565 type: macvlan
1566 conn_name: my-macvlan-connection
1567 ifname: mymacvlan0
1568 macvlan:
1569 mode: 2
1570 parent: eth1
1571 autoconnect: true
1572 state: present
1573
1574 - name: Create a wireguard connection
1575 community.general.nmcli:
1576 type: wireguard
1577 conn_name: my-wg-provider
1578 ifname: mywg0
1579 wireguard:
1580 listen-port: 51820
1581 private-key: my-private-key
1582 autoconnect: true
1583 state: present
1584
1585 - name: >-
1586 Create a VPN L2TP connection for ansible_user to connect on vpn.example.com
1587 authenticating with user 'brittany' and pre-shared key as 'Brittany123'
1588 community.general.nmcli:
1589 type: vpn
1590 conn_name: my-vpn-connection
1591 vpn:
1592 permissions: "{{ ansible_user }}"
1593 service-type: org.freedesktop.NetworkManager.l2tp
1594 gateway: vpn.example.com
1595 password-flags: 2
1596 user: brittany
1597 ipsec-enabled: true
1598 ipsec-psk: "0s{{ 'Brittany123' | ansible.builtin.b64encode }}"
1599 autoconnect: false
1600 state: present
1601
1602 ## Creating bond attached to bridge example
1603 - name: Create bond attached to bridge
1604 community.general.nmcli:
1605 type: bond
1606 conn_name: bond0
1607 slave_type: bridge
1608 master: br0
1609 state: present
1610
1611 - name: Create master bridge
1612 community.general.nmcli:
1613 type: bridge
1614 conn_name: br0
1615 method4: disabled
1616 method6: disabled
1617 state: present
1618
1619 ## Creating vlan connection attached to bridge
1620 - name: Create master bridge
1621 community.general.nmcli:
1622 type: bridge
1623 conn_name: br0
1624 state: present
1625
1626 - name: Create VLAN 5
1627 community.general.nmcli:
1628 type: vlan
1629 conn_name: eth0.5
1630 slave_type: bridge
1631 master: br0
1632 vlandev: eth0
1633 vlanid: 5
1634 state: present
1635
1636 ## Creating VRF and adding VLAN interface to it
1637 - name: Create VRF
1638 community.general.nmcli:
1639 type: vrf
1640 ifname: vrf10
1641 table: 10
1642 state: present
1643 conn_name: vrf10
1644 method4: disabled
1645 method6: disabled
1646
1647 - name: Create VLAN interface inside VRF
1648 community.general.nmcli:
1649 conn_name: "eth0.124"
1650 type: vlan
1651 vlanid: "124"
1652 vlandev: "eth0"
1653 master: "vrf10"
1654 slave_type: vrf
1655 state: "present"
1656 ip4: '192.168.124.50'
1657 gw4: '192.168.124.1'
1658
1659 ## Defining ip rules while setting a static IP
1660 ## table 'production' is set with id 200 in this example.
1661 - name: Set Static ips for interface with ip rules and routes
1662 community.general.nmcli:
1663 type: ethernet
1664 conn_name: 'eth0'
1665 ip4: '192.168.1.50'
1666 gw4: '192.168.1.1'
1667 state: present
1668 routes4_extended:
1669 - ip: "0.0.0.0/0"
1670 next_hop: "192.168.1.1"
1671 table: "production"
1672 routing_rules4:
1673 - "priority 0 from 192.168.1.50 table 200"
1674
1675 ## Creating an OVS bridge and attaching a port
1676 - name: Create OVS Bridge
1677 community.general.nmcli:
1678 conn_name: ovs-br-conn
1679 ifname: ovs-br
1680 type: ovs-bridge
1681 state: present
1682
1683 - name: Create OVS Port for OVS Bridge Interface
1684 community.general.nmcli:
1685 conn_name: ovs-br-interface-port-conn
1686 ifname: ovs-br-interface-port
1687 master: ovs-br
1688 type: ovs-port
1689 state: present
1690
1691 ## Adding an ethernet interface to an OVS bridge port
1692 - name: Add Ethernet Interface to OVS Port
1693 community.general.nmcli:
1694 conn_name: eno1
1695 ifname: eno1
1696 master: ovs-br-interface-port
1697 slave_type: ovs-port
1698 type: ethernet
1699 state: present
1700 """
1701
1702 RETURN = r"""#
1703 """
1704
1705 import re
1706
1707 from ansible.module_utils.basic import AnsibleModule
1708 from ansible.module_utils.common.locale import get_best_parsable_locale
1709 from ansible.module_utils.common.text.converters import to_text
1710
1711
1712 class NmcliModuleError(Exception):
1713 pass
1714
1715
1716 class Nmcli:
1717 """
1718 This is the generic nmcli manipulation class that is subclassed based on platform.
1719 A subclass may wish to override the following action methods:-
1720 - create_connection()
1721 - delete_connection()
1722 - edit_connection()
1723 - modify_connection()
1724 - show_connection()
1725 - up_connection()
1726 - down_connection()
1727 All subclasses MUST define platform and distribution (which may be None).
1728 """
1729
1730 platform = "Generic"
1731 distribution = None
1732
1733 SECRET_OPTIONS = (
1734 "802-11-wireless-security.leap-password",
1735 "802-11-wireless-security.psk",
1736 "802-11-wireless-security.wep-key0",
1737 "802-11-wireless-security.wep-key1",
1738 "802-11-wireless-security.wep-key2",
1739 "802-11-wireless-security.wep-key3",
1740 )
1741
1742 def __init__(self, module):
1743 self.module = module
1744 self.state = module.params["state"]
1745 self.ignore_unsupported_suboptions = module.params["ignore_unsupported_suboptions"]
1746 self.autoconnect = module.params["autoconnect"]
1747 self.autoconnect_priority = module.params["autoconnect_priority"]
1748 self.autoconnect_retries = module.params["autoconnect_retries"]
1749 self.conn_name = module.params["conn_name"]
1750 self.conn_reload = module.params["conn_reload"]
1751 self.slave_type = module.params["slave_type"]
1752 self.master = module.params["master"]
1753 self.ifname = module.params["ifname"]
1754 self.type = module.params["type"]
1755 self.ip4 = module.params["ip4"]
1756 self.gw4 = module.params["gw4"]
1757 self.gw4_ignore_auto = module.params["gw4_ignore_auto"]
1758 self.routes4 = module.params["routes4"]
1759 self.routes4_extended = module.params["routes4_extended"]
1760 self.route_metric4 = module.params["route_metric4"]
1761 self.routing_rules4 = module.params["routing_rules4"]
1762 self.never_default4 = module.params["never_default4"]
1763 self.dns4 = module.params["dns4"]
1764 self.dns4_search = module.params["dns4_search"]
1765 self.dns4_options = module.params["dns4_options"]
1766 self.dns4_ignore_auto = module.params["dns4_ignore_auto"]
1767 self.method4 = module.params["method4"]
1768 self.may_fail4 = module.params["may_fail4"]
1769 self.ip6 = module.params["ip6"]
1770 self.gw6 = module.params["gw6"]
1771 self.gw6_ignore_auto = module.params["gw6_ignore_auto"]
1772 self.routes6 = module.params["routes6"]
1773 self.routes6_extended = module.params["routes6_extended"]
1774 self.route_metric6 = module.params["route_metric6"]
1775 self.routing_rules6 = module.params["routing_rules6"]
1776 self.dns6 = module.params["dns6"]
1777 self.dns6_search = module.params["dns6_search"]
1778 self.dns6_options = module.params["dns6_options"]
1779 self.dns6_ignore_auto = module.params["dns6_ignore_auto"]
1780 self.method6 = module.params["method6"]
1781 self.ip_privacy6 = module.params["ip_privacy6"]
1782 self.addr_gen_mode6 = module.params["addr_gen_mode6"]
1783 self.mtu = module.params["mtu"]
1784 self.stp = module.params["stp"]
1785 self.priority = module.params["priority"]
1786 self.mode = module.params["mode"]
1787 self.miimon = module.params["miimon"]
1788 self.primary = module.params["primary"]
1789 self.downdelay = module.params["downdelay"]
1790 self.updelay = module.params["updelay"]
1791 self.xmit_hash_policy = module.params["xmit_hash_policy"]
1792 self.fail_over_mac = module.params["fail_over_mac"]
1793 self.arp_interval = module.params["arp_interval"]
1794 self.arp_ip_target = module.params["arp_ip_target"]
1795 self.slavepriority = module.params["slavepriority"]
1796 self.forwarddelay = module.params["forwarddelay"]
1797 self.hellotime = module.params["hellotime"]
1798 self.maxage = module.params["maxage"]
1799 self.ageingtime = module.params["ageingtime"]
1800 self.hairpin = module.params["hairpin"]
1801 self.path_cost = module.params["path_cost"]
1802 self.mac = module.params["mac"]
1803 self.runner = module.params["runner"]
1804 self.runner_hwaddr_policy = module.params["runner_hwaddr_policy"]
1805 self.runner_fast_rate = module.params["runner_fast_rate"]
1806 self.vlanid = module.params["vlanid"]
1807 self.vlandev = module.params["vlandev"]
1808 self.flags = module.params["flags"]
1809 self.ingress = module.params["ingress"]
1810 self.egress = module.params["egress"]
1811 self.vxlan_id = module.params["vxlan_id"]
1812 self.vxlan_parent = module.params["vxlan_parent"]
1813 self.vxlan_local = module.params["vxlan_local"]
1814 self.vxlan_remote = module.params["vxlan_remote"]
1815 self.ip_tunnel_dev = module.params["ip_tunnel_dev"]
1816 self.ip_tunnel_local = module.params["ip_tunnel_local"]
1817 self.ip_tunnel_remote = module.params["ip_tunnel_remote"]
1818 self.ip_tunnel_input_key = module.params["ip_tunnel_input_key"]
1819 self.ip_tunnel_output_key = module.params["ip_tunnel_output_key"]
1820 self.nmcli_bin = self.module.get_bin_path("nmcli", True)
1821 self.dhcp_client_id = module.params["dhcp_client_id"]
1822 self.zone = module.params["zone"]
1823 self.ssid = module.params["ssid"]
1824 self.wifi = module.params["wifi"]
1825 self.wifi_sec = module.params["wifi_sec"]
1826 self.gsm = module.params["gsm"]
1827 self.macvlan = module.params["macvlan"]
1828 self.wireguard = module.params["wireguard"]
1829 self.vpn = module.params["vpn"]
1830 self.transport_mode = module.params["transport_mode"]
1831 self.infiniband_mac = module.params["infiniband_mac"]
1832 self.sriov = module.params["sriov"]
1833
1834 if self.method4:
1835 self.ipv4_method = self.method4
1836 elif self.type in ("dummy", "macvlan", "wireguard") and not self.ip4:
1837 self.ipv4_method = "disabled"
1838 elif self.ip4:
1839 self.ipv4_method = "manual"
1840 else:
1841 self.ipv4_method = None
1842
1843 if self.method6:
1844 self.ipv6_method = self.method6
1845 elif self.type in ("dummy", "macvlan", "wireguard") and not self.ip6:
1846 self.ipv6_method = "disabled"
1847 elif self.ip6:
1848 self.ipv6_method = "manual"
1849 else:
1850 self.ipv6_method = None
1851
1852 if self.type == "vrf":
1853 self.table = module.params["table"]
1854
1855 self.edit_commands = []
1856
1857 self.extra_options_validation()
1858
1859 def extra_options_validation(self):
1860 """Additional validation of options set passed to module that cannot be implemented in module's argspecs."""
1861 if self.type not in ("bridge-slave", "team-slave", "bond-slave"):
1862 if self.master is None and self.slave_type is not None:
1863 self.module.fail_json(msg="'master' option is required when 'slave_type' is specified.")
1864
1865 def execute_command(self, cmd, use_unsafe_shell=False, data=None):
1866 cmd = [to_text(item) for item in cmd]
1867 return self.module.run_command(cmd, use_unsafe_shell=use_unsafe_shell, data=data)
1868
1869 def execute_edit_commands(self, commands, arguments):
1870 arguments = arguments or []
1871 cmd = [self.nmcli_bin, "con", "edit"] + arguments
1872 data = "\n".join(commands)
1873 return self.execute_command(cmd, data=data)
1874
1875 def connection_options(self, detect_change=False):
1876 # Options common to multiple connection types.
1877 options = {
1878 "connection.autoconnect": self.autoconnect,
1879 "connection.autoconnect-priority": self.autoconnect_priority,
1880 "connection.autoconnect-retries": self.autoconnect_retries,
1881 "connection.zone": self.zone,
1882 }
1883
1884 # IP address options.
1885 # The ovs-interface type can be both ip_conn_type and have a master
1886 # An interface that has a master but is of slave type vrf can have an IP address
1887 if (self.ip_conn_type and (not self.master or self.slave_type == "vrf")) or self.type == "ovs-interface":
1888 options.update(
1889 {
1890 "ipv4.addresses": self.enforce_ipv4_cidr_notation(self.ip4),
1891 "ipv4.dhcp-client-id": self.dhcp_client_id,
1892 "ipv4.dns": self.dns4,
1893 "ipv4.dns-search": self.dns4_search,
1894 "ipv4.dns-options": self.dns4_options,
1895 "ipv4.ignore-auto-dns": self.dns4_ignore_auto,
1896 "ipv4.gateway": self.gw4,
1897 "ipv4.ignore-auto-routes": self.gw4_ignore_auto,
1898 "ipv4.routes": self.enforce_routes_format(self.routes4, self.routes4_extended),
1899 "ipv4.route-metric": self.route_metric4,
1900 "ipv4.routing-rules": self.routing_rules4,
1901 "ipv4.never-default": self.never_default4,
1902 "ipv4.method": self.ipv4_method,
1903 "ipv4.may-fail": self.may_fail4,
1904 "ipv6.addresses": self.enforce_ipv6_cidr_notation(self.ip6),
1905 "ipv6.dns": self.dns6,
1906 "ipv6.dns-search": self.dns6_search,
1907 "ipv6.dns-options": self.dns6_options,
1908 "ipv6.ignore-auto-dns": self.dns6_ignore_auto,
1909 "ipv6.gateway": self.gw6,
1910 "ipv6.ignore-auto-routes": self.gw6_ignore_auto,
1911 "ipv6.routes": self.enforce_routes_format(self.routes6, self.routes6_extended),
1912 "ipv6.route-metric": self.route_metric6,
1913 "ipv6.routing-rules": self.routing_rules6,
1914 "ipv6.method": self.ipv6_method,
1915 "ipv6.ip6-privacy": self.ip_privacy6,
1916 "ipv6.addr-gen-mode": self.addr_gen_mode6,
1917 }
1918 )
1919 # when 'method' is disabled the 'may_fail' no make sense but accepted by nmcli with keeping 'yes'
1920 # force ignoring to save idempotency
1921 if self.ipv4_method and self.ipv4_method != "disabled":
1922 options.update({"ipv4.may-fail": self.may_fail4})
1923
1924 # Layer 2 options.
1925 if self.mac:
1926 options.update({self.mac_setting: self.mac})
1927
1928 if self.mtu_conn_type:
1929 options.update({self.mtu_setting: self.mtu})
1930
1931 # Connections that can have a master.
1932 if self.slave_conn_type:
1933 options.update(
1934 {
1935 "connection.master": self.master,
1936 "connection.slave-type": self.slave_type,
1937 }
1938 )
1939
1940 # Options specific to a connection type.
1941 if self.type == "bond":
1942 options.update(
1943 {
1944 "arp_interval": self.arp_interval,
1945 "arp_ip_target": self.arp_ip_target,
1946 "downdelay": self.downdelay,
1947 "miimon": self.miimon,
1948 "mode": self.mode,
1949 "primary": self.primary,
1950 "updelay": self.updelay,
1951 "xmit_hash_policy": self.xmit_hash_policy,
1952 "fail_over_mac": self.fail_over_mac,
1953 }
1954 )
1955 elif self.type == "bond-slave":
1956 if self.slave_type and self.slave_type != "bond":
1957 self.module.fail_json(
1958 msg=(
1959 f"Connection type '{self.type}' cannot be combined with '{self.slave_type}' slave-type. "
1960 f"Allowed slave-type for '{self.type}' is 'bond'."
1961 )
1962 )
1963 if not self.slave_type:
1964 self.module.warn(
1965 "Connection 'slave-type' property automatically set to 'bond' "
1966 "because of using 'bond-slave' connection type."
1967 )
1968 options.update(
1969 {
1970 "connection.slave-type": "bond",
1971 }
1972 )
1973 elif self.type == "bridge":
1974 options.update(
1975 {
1976 "bridge.ageing-time": self.ageingtime,
1977 "bridge.forward-delay": self.forwarddelay,
1978 "bridge.hello-time": self.hellotime,
1979 "bridge.max-age": self.maxage,
1980 "bridge.priority": self.priority,
1981 "bridge.stp": self.stp,
1982 }
1983 )
1984 # priority make sense when stp enabled, otherwise nmcli keeps bridge-priority to 32768 regrdless of input.
1985 # force ignoring to save idempotency
1986 if self.stp:
1987 options.update({"bridge.priority": self.priority})
1988 elif self.type == "team":
1989 options.update(
1990 {
1991 "team.runner": self.runner,
1992 "team.runner-hwaddr-policy": self.runner_hwaddr_policy,
1993 }
1994 )
1995 if self.runner_fast_rate is not None:
1996 options.update(
1997 {
1998 "team.runner-fast-rate": self.runner_fast_rate,
1999 }
2000 )
2001 elif self.type == "bridge-slave":
2002 if self.slave_type and self.slave_type != "bridge":
2003 self.module.fail_json(
2004 msg=(
2005 f"Connection type '{self.type}' cannot be combined with '{self.slave_type}' slave-type. "
2006 f"Allowed slave-type for '{self.type}' is 'bridge'."
2007 )
2008 )
2009 if not self.slave_type:
2010 self.module.warn(
2011 "Connection 'slave-type' property automatically set to 'bridge' "
2012 "because of using 'bridge-slave' connection type."
2013 )
2014 options.update({"connection.slave-type": "bridge"})
2015 self.module.warn(
2016 "Connection type as 'bridge-slave' implies 'ethernet' connection with 'bridge' slave-type. "
2017 "Consider using slave_type='bridge' with necessary type."
2018 )
2019 options.update(
2020 {
2021 "bridge-port.path-cost": self.path_cost,
2022 "bridge-port.hairpin-mode": self.hairpin,
2023 "bridge-port.priority": self.slavepriority,
2024 }
2025 )
2026 elif self.type == "team-slave":
2027 if self.slave_type and self.slave_type != "team":
2028 self.module.fail_json(
2029 msg=(
2030 f"Connection type '{self.type}' cannot be combined with '{self.slave_type}' slave-type. "
2031 f"Allowed slave-type for '{self.type}' is 'team'."
2032 )
2033 )
2034 if not self.slave_type:
2035 self.module.warn(
2036 "Connection 'slave-type' property automatically set to 'team' "
2037 "because of using 'team-slave' connection type."
2038 )
2039 options.update(
2040 {
2041 "connection.slave-type": "team",
2042 }
2043 )
2044 elif self.tunnel_conn_type:
2045 options.update(
2046 {
2047 "ip-tunnel.local": self.ip_tunnel_local,
2048 "ip-tunnel.mode": self.type,
2049 "ip-tunnel.parent": self.ip_tunnel_dev,
2050 "ip-tunnel.remote": self.ip_tunnel_remote,
2051 }
2052 )
2053 if self.type == "gre":
2054 options.update(
2055 {"ip-tunnel.input-key": self.ip_tunnel_input_key, "ip-tunnel.output-key": self.ip_tunnel_output_key}
2056 )
2057 elif self.type == "vlan":
2058 options.update(
2059 {
2060 "vlan.id": self.vlanid,
2061 "vlan.parent": self.vlandev,
2062 "vlan.flags": self.flags,
2063 "vlan.ingress": self.ingress,
2064 "vlan.egress": self.egress,
2065 }
2066 )
2067 elif self.type == "vxlan":
2068 options.update(
2069 {
2070 "vxlan.id": self.vxlan_id,
2071 "vxlan.parent": self.vxlan_parent,
2072 "vxlan.local": self.vxlan_local,
2073 "vxlan.remote": self.vxlan_remote,
2074 }
2075 )
2076 elif self.type == "wifi":
2077 options.update(
2078 {
2079 "802-11-wireless.ssid": self.ssid,
2080 "connection.slave-type": ("bond" if self.slave_type is None else self.slave_type)
2081 if self.master
2082 else None,
2083 }
2084 )
2085 if self.wifi:
2086 for name, value in self.wifi.items():
2087 options.update({f"802-11-wireless.{name}": value})
2088 if self.wifi_sec:
2089 for name, value in self.wifi_sec.items():
2090 options.update({f"802-11-wireless-security.{name}": value})
2091 elif self.type == "gsm":
2092 if self.gsm:
2093 for name, value in self.gsm.items():
2094 options.update(
2095 {
2096 f"gsm.{name}": value,
2097 }
2098 )
2099 elif self.type == "macvlan":
2100 if self.macvlan:
2101 for name, value in self.macvlan.items():
2102 options.update(
2103 {
2104 f"macvlan.{name}": value,
2105 }
2106 )
2107 elif self.state == "present":
2108 raise NmcliModuleError("type is macvlan but all of the following are missing: macvlan")
2109 elif self.type == "wireguard":
2110 if self.wireguard:
2111 for name, value in self.wireguard.items():
2112 options.update(
2113 {
2114 f"wireguard.{name}": value,
2115 }
2116 )
2117 elif self.type == "vpn":
2118 if self.vpn:
2119 vpn_data_values = ""
2120 for name, value in self.vpn.items():
2121 if name == "service-type":
2122 options.update(
2123 {
2124 "vpn.service-type": value,
2125 }
2126 )
2127 elif name == "permissions":
2128 options.update(
2129 {
2130 "connection.permissions": value,
2131 }
2132 )
2133 else:
2134 if vpn_data_values != "":
2135 vpn_data_values += ", "
2136
2137 if isinstance(value, bool):
2138 value = self.bool_to_string(value)
2139
2140 vpn_data_values += f"{name}={value}"
2141 options.update(
2142 {
2143 "vpn.data": vpn_data_values,
2144 }
2145 )
2146 elif self.type == "infiniband":
2147 options.update(
2148 {
2149 "infiniband.transport-mode": self.transport_mode,
2150 }
2151 )
2152 if self.infiniband_mac:
2153 options["infiniband.mac-address"] = self.infiniband_mac
2154 elif self.type == "vrf":
2155 options.update(
2156 {
2157 "table": self.table,
2158 }
2159 )
2160
2161 if self.type == "ethernet":
2162 if self.sriov:
2163 for name, value in self.sriov.items():
2164 options.update(
2165 {
2166 f"sriov.{name}": value,
2167 }
2168 )
2169
2170 # Convert settings values based on the situation.
2171 for setting, value in options.items():
2172 setting_type = self.settings_type(setting)
2173 convert_func = None
2174 if setting_type is bool:
2175 # Convert all bool options to yes/no.
2176 convert_func = self.bool_to_string
2177 if detect_change:
2178 if setting in ("vlan.id", "vxlan.id"):
2179 # Convert VLAN/VXLAN IDs to text when detecting changes.
2180 convert_func = to_text
2181 elif setting == self.mtu_setting:
2182 # MTU is 'auto' by default when detecting changes.
2183 convert_func = self.mtu_to_string
2184 elif setting == "ipv6.ip6-privacy":
2185 convert_func = self.ip6_privacy_to_num
2186 elif setting_type is list:
2187 # Convert lists to strings for nmcli create/modify commands.
2188 convert_func = self.list_to_string
2189
2190 if callable(convert_func):
2191 options[setting] = convert_func(value)
2192
2193 return options
2194
2195 @property
2196 def ip_conn_type(self):
2197 return self.type in (
2198 "bond",
2199 "bridge",
2200 "dummy",
2201 "ethernet",
2202 "802-3-ethernet",
2203 "generic",
2204 "gre",
2205 "infiniband",
2206 "ipip",
2207 "sit",
2208 "team",
2209 "vlan",
2210 "wifi",
2211 "802-11-wireless",
2212 "gsm",
2213 "macvlan",
2214 "wireguard",
2215 "vpn",
2216 "loopback",
2217 "ovs-interface",
2218 "vrf",
2219 )
2220
2221 @property
2222 def mac_setting(self):
2223 if self.type == "bridge":
2224 return "bridge.mac-address"
2225 else:
2226 return "802-3-ethernet.cloned-mac-address"
2227
2228 @property
2229 def mtu_conn_type(self):
2230 return self.type in (
2231 "bond",
2232 "bond-slave",
2233 "dummy",
2234 "ethernet",
2235 "infiniband",
2236 "team-slave",
2237 "vlan",
2238 )
2239
2240 @property
2241 def mtu_setting(self):
2242 if self.type == "infiniband":
2243 return "infiniband.mtu"
2244 else:
2245 return "802-3-ethernet.mtu"
2246
2247 @staticmethod
2248 def mtu_to_string(mtu):
2249 if not mtu:
2250 return "auto"
2251 else:
2252 return to_text(mtu)
2253
2254 @staticmethod
2255 def ip6_privacy_to_num(privacy):
2256 ip6_privacy_values = {
2257 "disabled": "0",
2258 "prefer-public-addr": "1 (enabled, prefer public IP)",
2259 "prefer-temp-addr": "2 (enabled, prefer temporary IP)",
2260 "unknown": "-1",
2261 }
2262
2263 if privacy is None:
2264 return None
2265
2266 if privacy not in ip6_privacy_values:
2267 raise AssertionError(f"{privacy} is invalid ip_privacy6 option")
2268
2269 return ip6_privacy_values[privacy]
2270
2271 @property
2272 def slave_conn_type(self):
2273 return self.type in (
2274 "ethernet",
2275 "bridge",
2276 "bond",
2277 "vlan",
2278 "team",
2279 "wifi",
2280 "bond-slave",
2281 "bridge-slave",
2282 "team-slave",
2283 "wifi",
2284 "infiniband",
2285 "ovs-port",
2286 "ovs-interface",
2287 "vxlan",
2288 )
2289
2290 @property
2291 def tunnel_conn_type(self):
2292 return self.type in (
2293 "gre",
2294 "ipip",
2295 "sit",
2296 )
2297
2298 @staticmethod
2299 def enforce_ipv4_cidr_notation(ip4_addresses):
2300 if ip4_addresses is None:
2301 return None
2302 return [address if "/" in address else f"{address}/32" for address in ip4_addresses]
2303
2304 @staticmethod
2305 def enforce_ipv6_cidr_notation(ip6_addresses):
2306 if ip6_addresses is None:
2307 return None
2308 return [address if "/" in address else f"{address}/128" for address in ip6_addresses]
2309
2310 def enforce_routes_format(self, routes, routes_extended):
2311 if routes is not None:
2312 return routes
2313 elif routes_extended is not None:
2314 return [self.route_to_string(route) for route in routes_extended]
2315 else:
2316 return None
2317
2318 @staticmethod
2319 def route_to_string(route):
2320 result_str = ""
2321 result_str += route["ip"]
2322 if route.get("next_hop") is not None:
2323 result_str += f" {route['next_hop']}"
2324 if route.get("metric") is not None:
2325 result_str += f" {route['metric']!s}"
2326
2327 for attribute, value in sorted(route.items()):
2328 if attribute not in ("ip", "next_hop", "metric") and value is not None:
2329 result_str += f" {attribute}={str(value).lower()}"
2330
2331 return result_str
2332
2333 @staticmethod
2334 def bool_to_string(boolean):
2335 if boolean:
2336 return "yes"
2337 else:
2338 return "no"
2339
2340 @staticmethod
2341 def list_to_string(lst):
2342 if lst is None:
2343 return None
2344 else:
2345 return ",".join(lst)
2346
2347 @staticmethod
2348 def settings_type(setting):
2349 if setting in {
2350 "bridge.stp",
2351 "bridge-port.hairpin-mode",
2352 "connection.autoconnect",
2353 "ipv4.never-default",
2354 "ipv4.ignore-auto-dns",
2355 "ipv4.ignore-auto-routes",
2356 "ipv4.may-fail",
2357 "ipv6.ignore-auto-dns",
2358 "ipv6.ignore-auto-routes",
2359 "802-11-wireless.hidden",
2360 "team.runner-fast-rate",
2361 "macvlan.tap",
2362 }:
2363 return bool
2364 elif setting in {
2365 "ipv4.addresses",
2366 "ipv6.addresses",
2367 "ipv4.dns",
2368 "ipv4.dns-search",
2369 "ipv4.dns-options",
2370 "ipv4.routes",
2371 "ipv4.routing-rules",
2372 "ipv6.dns",
2373 "ipv6.dns-search",
2374 "ipv6.dns-options",
2375 "ipv6.routes",
2376 "ipv6.routing-rules",
2377 "802-11-wireless-security.group",
2378 "802-11-wireless-security.leap-password-flags",
2379 "802-11-wireless-security.pairwise",
2380 "802-11-wireless-security.proto",
2381 "802-11-wireless-security.psk-flags",
2382 "802-11-wireless-security.wep-key-flags",
2383 "802-11-wireless.mac-address-blacklist",
2384 }:
2385 return list
2386 elif setting in {"connection.autoconnect-priority", "connection.autoconnect-retries"}:
2387 return int
2388 return str
2389
2390 def get_route_params(self, raw_values):
2391 routes_params = []
2392 for raw_value in raw_values:
2393 route_params = {}
2394 for parameter, value in re.findall(r"([\w-]*)\s?=\s?([^\s,}]*)", raw_value):
2395 if parameter == "nh":
2396 route_params["next_hop"] = value
2397 elif parameter == "mt":
2398 route_params["metric"] = value
2399 else:
2400 route_params[parameter] = value
2401 routes_params.append(route_params)
2402 return [self.route_to_string(route_params) for route_params in routes_params]
2403
2404 def list_connection_info(self):
2405 cmd = [self.nmcli_bin, "--fields", "name", "--terse", "con", "show"]
2406 (rc, out, err) = self.execute_command(cmd)
2407 if rc != 0:
2408 raise NmcliModuleError(err)
2409 return out.splitlines()
2410
2411 def connection_exists(self):
2412 return self.conn_name in self.list_connection_info()
2413
2414 def down_connection(self):
2415 cmd = [self.nmcli_bin, "con", "down", self.conn_name]
2416 return self.execute_command(cmd)
2417
2418 def get_connection_state(self):
2419 """Get the current state of the connection"""
2420 cmd = [self.nmcli_bin, "--terse", "--fields", "GENERAL.STATE", "con", "show", self.conn_name]
2421 (rc, out, err) = self.execute_command(cmd)
2422 if rc != 0:
2423 raise NmcliModuleError(err)
2424
2425 lines = [ll.strip() for ll in out.splitlines() if "GENERAL.STATE" in ll]
2426 return lines[0].split(":")[1] if lines else None
2427
2428 def is_connection_active(self):
2429 """Check if the connection is currently active"""
2430 state = self.get_connection_state()
2431 return state == "activated"
2432
2433 def up_connection(self):
2434 cmd = [self.nmcli_bin, "con", "up", self.conn_name]
2435 return self.execute_command(cmd)
2436
2437 def reload_connection(self):
2438 cmd = [self.nmcli_bin, "con", "reload"]
2439 return self.execute_command(cmd)
2440
2441 def connection_update(self, nmcli_command):
2442 if nmcli_command == "create":
2443 cmd = [self.nmcli_bin, "con", "add", "type"]
2444 if self.tunnel_conn_type:
2445 cmd.append("ip-tunnel")
2446 else:
2447 cmd.append(self.type)
2448 cmd.append("con-name")
2449 elif nmcli_command == "modify":
2450 cmd = [self.nmcli_bin, "con", "modify"]
2451 else:
2452 self.module.fail_json(msg="Invalid nmcli command.")
2453 cmd.append(self.conn_name)
2454
2455 # Use connection name as default for interface name on creation.
2456 if nmcli_command == "create" and self.ifname is None:
2457 ifname = self.conn_name
2458 else:
2459 ifname = self.ifname
2460
2461 options = {
2462 "connection.interface-name": ifname,
2463 }
2464
2465 # VPN doesn't need an interface but if sended it must be a valid interface.
2466 if self.type == "vpn" and self.ifname is None:
2467 del options["connection.interface-name"]
2468
2469 options.update(self.connection_options())
2470
2471 # Constructing the command.
2472 for key, value in options.items():
2473 if value is not None:
2474 if key in self.SECRET_OPTIONS:
2475 self.edit_commands += [f"set {key} {value}"]
2476 continue
2477 if key in ("xmit_hash_policy", "fail_over_mac", "arp_interval", "arp_ip_target"):
2478 cmd.extend(["+bond.options", f"{key}={value}"])
2479 continue
2480 cmd.extend([key, value])
2481
2482 return self.execute_command(cmd)
2483
2484 def create_connection(self):
2485 status = self.connection_update("create")
2486 if status[0] == 0 and self.edit_commands:
2487 status = self.edit_connection()
2488 if self.create_connection_up:
2489 status = self.up_connection()
2490 return status
2491
2492 @property
2493 def create_connection_up(self):
2494 if self.type in ("bond", "dummy", "ethernet", "infiniband", "wifi"):
2495 if (self.mtu is not None) or (self.dns4 is not None) or (self.dns6 is not None):
2496 return True
2497 elif self.type == "team":
2498 if (self.dns4 is not None) or (self.dns6 is not None):
2499 return True
2500 return False
2501
2502 def remove_connection(self):
2503 # self.down_connection()
2504 cmd = [self.nmcli_bin, "con", "del", self.conn_name]
2505 return self.execute_command(cmd)
2506
2507 def modify_connection(self):
2508 status = self.connection_update("modify")
2509 if status[0] == 0 and self.edit_commands:
2510 status = self.edit_connection()
2511 return status
2512
2513 def edit_connection(self):
2514 commands = self.edit_commands + ["save", "quit"]
2515 return self.execute_edit_commands(commands, arguments=[self.conn_name])
2516
2517 def show_connection(self):
2518 cmd = [self.nmcli_bin, "--show-secrets", "con", "show", self.conn_name]
2519
2520 (rc, out, err) = self.execute_command(cmd)
2521
2522 if rc != 0:
2523 raise NmcliModuleError(err)
2524
2525 p_enum_value = re.compile(r"^([-]?\d+) \((\w+)\)$")
2526
2527 conn_info = dict()
2528 for line in out.splitlines():
2529 pair = line.split(":", 1)
2530 key = pair[0].strip()
2531 key_type = self.settings_type(key)
2532 if key and len(pair) > 1:
2533 raw_value = pair[1].lstrip()
2534 if raw_value == "--":
2535 if key_type is list:
2536 conn_info[key] = []
2537 else:
2538 conn_info[key] = None
2539 elif key == "bond.options":
2540 # Aliases such as 'miimon', 'downdelay' are equivalent to the +bond.options 'option=value' syntax.
2541 opts = raw_value.split(",")
2542 for opt in opts:
2543 alias_pair = opt.split("=", 1)
2544 if len(alias_pair) > 1:
2545 alias_key = alias_pair[0]
2546 alias_value = alias_pair[1]
2547 conn_info[alias_key] = alias_value
2548 elif key in ("ipv4.routes", "ipv6.routes"):
2549 conn_info[key] = [s.strip() for s in raw_value.split(";")]
2550 elif key_type is list:
2551 conn_info[key] = [s.strip() for s in raw_value.split(",")]
2552 else:
2553 m_enum = p_enum_value.match(raw_value)
2554 if m_enum is not None:
2555 value = m_enum.group(1)
2556 else:
2557 value = raw_value
2558 conn_info[key] = value
2559
2560 return conn_info
2561
2562 def get_supported_properties(self, setting):
2563 properties = []
2564
2565 if setting == "802-11-wireless-security":
2566 set_property = "psk"
2567 set_value = "FAKEVALUE"
2568 commands = [f"set {setting}.{set_property} {set_value}"]
2569 else:
2570 commands = []
2571
2572 commands += [f"print {setting}", "quit", "yes"]
2573
2574 (rc, out, err) = self.execute_edit_commands(commands, arguments=["type", self.type])
2575
2576 if rc != 0:
2577 raise NmcliModuleError(err)
2578
2579 for line in out.splitlines():
2580 prefix = f"{setting}."
2581 if line.startswith(prefix):
2582 pair = line.split(":", 1)
2583 property = pair[0].strip().replace(prefix, "")
2584 properties.append(property)
2585
2586 return properties
2587
2588 def check_for_unsupported_properties(self, setting):
2589 if setting == "802-11-wireless":
2590 setting_key = "wifi"
2591 elif setting == "802-11-wireless-security":
2592 setting_key = "wifi_sec"
2593 else:
2594 setting_key = setting
2595
2596 supported_properties = self.get_supported_properties(setting)
2597 unsupported_properties = []
2598
2599 for property in getattr(self, setting_key):
2600 if property not in supported_properties:
2601 unsupported_properties.append(property)
2602
2603 if unsupported_properties:
2604 msg_options = []
2605 for property in unsupported_properties:
2606 msg_options.append(f"{setting_key}.{property}")
2607
2608 str_msg_options = '", "'.join(msg_options)
2609 msg = f'Invalid or unsupported option(s): "{str_msg_options}"'
2610 if self.ignore_unsupported_suboptions:
2611 self.module.warn(msg)
2612 else:
2613 self.module.fail_json(msg=msg)
2614
2615 return unsupported_properties
2616
2617 def _compare_conn_params(self, conn_info, options):
2618 changed = False
2619 diff_before = dict()
2620 diff_after = dict()
2621
2622 for key, value in options.items():
2623 # We can't just do `if not value` because then if there's a value
2624 # of 0 specified as an integer it'll be interpreted as empty when
2625 # it actually isn't.
2626 if value not in (0, []) and not value:
2627 continue
2628
2629 if key in conn_info:
2630 current_value = conn_info[key]
2631 if key == "802-11-wireless.wake-on-wlan" and current_value is not None:
2632 match = re.match("0x([0-9A-Fa-f]+)", current_value)
2633 if match:
2634 current_value = str(int(match.group(1), 16))
2635 if key in ("ipv4.routes", "ipv6.routes") and current_value is not None:
2636 current_value = self.get_route_params(current_value)
2637 if key == self.mac_setting:
2638 # MAC addresses are case insensitive, nmcli always reports them in uppercase
2639 value = value.upper()
2640 # ensure current_value is also converted to uppercase in case nmcli changes behaviour
2641 if current_value:
2642 current_value = current_value.upper()
2643 if key == "gsm.apn":
2644 # Depending on version nmcli adds double-qoutes to gsm.apn
2645 # Need to strip them in order to compare both
2646 if current_value:
2647 current_value = current_value.strip('"')
2648 if key == self.mtu_setting and self.mtu is None:
2649 self.mtu = 0
2650 if key == "vpn.data":
2651 if current_value:
2652 current_value = sorted(
2653 re.sub(r"\s*=\s*", "=", part.strip(), count=1) for part in current_value.split(",")
2654 )
2655 value = sorted(part.strip() for part in value.split(","))
2656 else:
2657 # parameter does not exist
2658 current_value = None
2659
2660 if isinstance(current_value, list) and isinstance(value, list):
2661 # compare values between two lists
2662 if key in (
2663 "ipv4.addresses",
2664 "ipv6.addresses",
2665 "ipv4.dns",
2666 "ipv6.dns",
2667 "ipv4.dns-search",
2668 "ipv6.dns-search",
2669 ):
2670 # The order of IP addresses matters because the first one
2671 # is the default source address for outbound connections.
2672 # Similarly, the order of DNS nameservers and search
2673 # suffixes is important.
2674 changed |= current_value != value
2675 else:
2676 changed |= sorted(current_value) != sorted(value)
2677 elif all(
2678 [
2679 key == self.mtu_setting,
2680 self.type in ("bond", "bond-slave", "dummy"),
2681 current_value is None,
2682 value == "auto",
2683 self.mtu is None,
2684 ]
2685 ):
2686 value = None
2687 else:
2688 value = to_text(value)
2689 if current_value != value:
2690 changed = True
2691
2692 diff_before[key] = current_value
2693 diff_after[key] = value
2694
2695 diff = {
2696 "before": diff_before,
2697 "after": diff_after,
2698 }
2699 return (changed, diff)
2700
2701 def is_connection_changed(self):
2702 options = {
2703 "connection.interface-name": self.ifname,
2704 }
2705
2706 # VPN doesn't need an interface but if sended it must be a valid interface.
2707 if self.type == "vpn" and self.ifname is None:
2708 del options["connection.interface-name"]
2709
2710 if not self.type:
2711 current_con_type = self.show_connection().get("connection.type")
2712 if current_con_type:
2713 if current_con_type == "802-11-wireless":
2714 current_con_type = "wifi"
2715 self.type = current_con_type
2716
2717 options.update(self.connection_options(detect_change=True))
2718 return self._compare_conn_params(self.show_connection(), options)
2719
2720
2721 def create_module() -> AnsibleModule:
2722 module = AnsibleModule(
2723 argument_spec=dict(
2724 ignore_unsupported_suboptions=dict(type="bool", default=False),
2725 autoconnect=dict(type="bool", default=True),
2726 autoconnect_priority=dict(type="int"),
2727 autoconnect_retries=dict(type="int"),
2728 state=dict(type="str", required=True, choices=["absent", "present", "up", "down"]),
2729 conn_name=dict(type="str", required=True),
2730 conn_reload=dict(type="bool", default=False),
2731 master=dict(type="str"),
2732 slave_type=dict(type="str", choices=["bond", "bridge", "team", "ovs-port", "vrf"]),
2733 ifname=dict(type="str"),
2734 type=dict(
2735 type="str",
2736 choices=[
2737 "bond",
2738 "bond-slave",
2739 "bridge",
2740 "bridge-slave",
2741 "dummy",
2742 "ethernet",
2743 "generic",
2744 "gre",
2745 "infiniband",
2746 "ipip",
2747 "sit",
2748 "team",
2749 "team-slave",
2750 "vlan",
2751 "vxlan",
2752 "wifi",
2753 "gsm",
2754 "macvlan",
2755 "wireguard",
2756 "vpn",
2757 "loopback",
2758 "ovs-interface",
2759 "ovs-bridge",
2760 "ovs-port",
2761 "vrf",
2762 ],
2763 ),
2764 ip4=dict(type="list", elements="str"),
2765 gw4=dict(type="str"),
2766 gw4_ignore_auto=dict(type="bool", default=False),
2767 routes4=dict(type="list", elements="str"),
2768 routes4_extended=dict(
2769 type="list",
2770 elements="dict",
2771 options=dict(
2772 ip=dict(type="str", required=True),
2773 next_hop=dict(type="str"),
2774 metric=dict(type="int"),
2775 table=dict(type="int"),
2776 tos=dict(type="int"),
2777 cwnd=dict(type="int"),
2778 mtu=dict(type="int"),
2779 onlink=dict(type="bool"),
2780 ),
2781 ),
2782 route_metric4=dict(type="int"),
2783 routing_rules4=dict(type="list", elements="str"),
2784 never_default4=dict(type="bool", default=False),
2785 dns4=dict(type="list", elements="str"),
2786 dns4_search=dict(type="list", elements="str"),
2787 dns4_options=dict(type="list", elements="str"),
2788 dns4_ignore_auto=dict(type="bool", default=False),
2789 method4=dict(type="str", choices=["auto", "link-local", "manual", "shared", "disabled"]),
2790 may_fail4=dict(type="bool", default=True),
2791 dhcp_client_id=dict(type="str"),
2792 ip6=dict(type="list", elements="str"),
2793 gw6=dict(type="str"),
2794 gw6_ignore_auto=dict(type="bool", default=False),
2795 dns6=dict(type="list", elements="str"),
2796 dns6_search=dict(type="list", elements="str"),
2797 dns6_options=dict(type="list", elements="str"),
2798 dns6_ignore_auto=dict(type="bool", default=False),
2799 routes6=dict(type="list", elements="str"),
2800 routes6_extended=dict(
2801 type="list",
2802 elements="dict",
2803 options=dict(
2804 ip=dict(type="str", required=True),
2805 next_hop=dict(type="str"),
2806 metric=dict(type="int"),
2807 table=dict(type="int"),
2808 cwnd=dict(type="int"),
2809 mtu=dict(type="int"),
2810 onlink=dict(type="bool"),
2811 ),
2812 ),
2813 route_metric6=dict(type="int"),
2814 routing_rules6=dict(type="list", elements="str"),
2815 method6=dict(type="str", choices=["ignore", "auto", "dhcp", "link-local", "manual", "shared", "disabled"]),
2816 ip_privacy6=dict(type="str", choices=["disabled", "prefer-public-addr", "prefer-temp-addr", "unknown"]),
2817 addr_gen_mode6=dict(type="str", choices=["default", "default-or-eui64", "eui64", "stable-privacy"]),
2818 # Bond Specific vars
2819 mode=dict(
2820 type="str",
2821 default="balance-rr",
2822 choices=[
2823 "802.3ad",
2824 "active-backup",
2825 "balance-alb",
2826 "balance-rr",
2827 "balance-tlb",
2828 "balance-xor",
2829 "broadcast",
2830 ],
2831 ),
2832 miimon=dict(type="int"),
2833 downdelay=dict(type="int"),
2834 updelay=dict(type="int"),
2835 xmit_hash_policy=dict(type="str"),
2836 fail_over_mac=dict(type="str", choices=["none", "active", "follow"]),
2837 arp_interval=dict(type="int"),
2838 arp_ip_target=dict(type="str"),
2839 primary=dict(type="str"),
2840 # general usage
2841 mtu=dict(type="int"),
2842 mac=dict(type="str"),
2843 zone=dict(type="str"),
2844 # bridge specific vars
2845 stp=dict(type="bool", default=True),
2846 priority=dict(type="int", default=128),
2847 slavepriority=dict(type="int", default=32),
2848 forwarddelay=dict(type="int", default=15),
2849 hellotime=dict(type="int", default=2),
2850 maxage=dict(type="int", default=20),
2851 ageingtime=dict(type="int", default=300),
2852 hairpin=dict(type="bool", default=False),
2853 path_cost=dict(type="int", default=100),
2854 # team specific vars
2855 runner=dict(
2856 type="str",
2857 default="roundrobin",
2858 choices=["broadcast", "roundrobin", "activebackup", "loadbalance", "lacp"],
2859 ),
2860 # team active-backup runner specific options
2861 runner_hwaddr_policy=dict(type="str", choices=["same_all", "by_active", "only_active"]),
2862 # team lacp runner specific options
2863 runner_fast_rate=dict(type="bool"),
2864 # vlan specific vars
2865 vlanid=dict(type="int"),
2866 vlandev=dict(type="str"),
2867 flags=dict(type="str"),
2868 ingress=dict(type="str"),
2869 egress=dict(type="str"),
2870 # vxlan specific vars
2871 vxlan_id=dict(type="int"),
2872 vxlan_parent=dict(type="str"),
2873 vxlan_local=dict(type="str"),
2874 vxlan_remote=dict(type="str"),
2875 # ip-tunnel specific vars
2876 ip_tunnel_dev=dict(type="str"),
2877 ip_tunnel_local=dict(type="str"),
2878 ip_tunnel_remote=dict(type="str"),
2879 # ip-tunnel type gre specific vars
2880 ip_tunnel_input_key=dict(type="str", no_log=True),
2881 ip_tunnel_output_key=dict(type="str", no_log=True),
2882 # 802-11-wireless* specific vars
2883 ssid=dict(type="str"),
2884 wifi=dict(type="dict"),
2885 wifi_sec=dict(type="dict", no_log=True),
2886 gsm=dict(type="dict"),
2887 macvlan=dict(
2888 type="dict",
2889 options=dict(
2890 mode=dict(type="int", choices=[1, 2, 3, 4, 5], required=True),
2891 parent=dict(type="str", required=True),
2892 promiscuous=dict(type="bool"),
2893 tap=dict(type="bool"),
2894 ),
2895 ),
2896 wireguard=dict(type="dict"),
2897 vpn=dict(type="dict"),
2898 sriov=dict(type="dict"),
2899 table=dict(type="int"),
2900 # infiniband specific vars
2901 transport_mode=dict(type="str", choices=["datagram", "connected"]),
2902 infiniband_mac=dict(type="str"),
2903 ),
2904 mutually_exclusive=[
2905 ["never_default4", "gw4"],
2906 ["routes4_extended", "routes4"],
2907 ["routes6_extended", "routes6"],
2908 ],
2909 required_if=[
2910 ("type", "wifi", ["ssid"]),
2911 ("type", "team-slave", ["master", "ifname"]),
2912 ("slave_type", "team", ["master", "ifname"]),
2913 ],
2914 supports_check_mode=True,
2915 )
2916 locale = get_best_parsable_locale(module)
2917 module.run_command_environ_update = dict(LANGUAGE=locale, LC_ALL=locale)
2918 return module
2919
2920
2921 def main():
2922 # Parsing argument file
2923 module = create_module()
2924
2925 nmcli = Nmcli(module)
2926
2927 (rc, out, err) = (None, "", "")
2928 result = {"conn_name": nmcli.conn_name, "state": nmcli.state}
2929
2930 # team checks
2931 if nmcli.type == "team":
2932 if nmcli.runner_hwaddr_policy and nmcli.runner != "activebackup":
2933 nmcli.module.fail_json(msg="Runner-hwaddr-policy is only allowed for runner activebackup")
2934 if nmcli.runner_fast_rate is not None and nmcli.runner != "lacp":
2935 nmcli.module.fail_json(msg="runner-fast-rate is only allowed for runner lacp")
2936 if nmcli.type == "wifi":
2937 unsupported_properties = {}
2938 if nmcli.wifi:
2939 if "ssid" in nmcli.wifi:
2940 module.warn("Ignoring option 'wifi.ssid', it must be specified with option 'ssid'")
2941 del nmcli.wifi["ssid"]
2942 unsupported_properties["wifi"] = nmcli.check_for_unsupported_properties("802-11-wireless")
2943 if nmcli.wifi_sec:
2944 unsupported_properties["wifi_sec"] = nmcli.check_for_unsupported_properties("802-11-wireless-security")
2945 if nmcli.ignore_unsupported_suboptions and unsupported_properties:
2946 for setting_key, properties in unsupported_properties.items():
2947 for property in properties:
2948 del getattr(nmcli, setting_key)[property]
2949
2950 try:
2951 if nmcli.state == "absent":
2952 if nmcli.connection_exists():
2953 if module.check_mode:
2954 module.exit_json(changed=True)
2955 (rc, out, err) = nmcli.down_connection()
2956 (rc, out, err) = nmcli.remove_connection()
2957 if rc != 0:
2958 module.fail_json(name=f"Error removing connection named {nmcli.conn_name}", msg=err, rc=rc)
2959
2960 elif nmcli.state == "present":
2961 if nmcli.connection_exists():
2962 changed, diff = nmcli.is_connection_changed()
2963 if module._diff:
2964 result["diff"] = diff
2965
2966 if changed:
2967 # modify connection (note: this function is check mode aware)
2968 # result['Connection']=('Connection %s of Type %s is not being added' % (nmcli.conn_name, nmcli.type))
2969 result["Exists"] = "Connections do exist so we are modifying them"
2970 if module.check_mode:
2971 module.exit_json(changed=True, **result)
2972 (rc, out, err) = nmcli.modify_connection()
2973 if nmcli.conn_reload:
2974 (rc, out, err) = nmcli.reload_connection()
2975 else:
2976 result["Exists"] = "Connections already exist and no changes made"
2977 if module.check_mode:
2978 module.exit_json(changed=False, **result)
2979 if not nmcli.connection_exists():
2980 result["Connection"] = f"Connection {nmcli.conn_name} of Type {nmcli.type} is being added"
2981 if module.check_mode:
2982 module.exit_json(changed=True, **result)
2983 (rc, out, err) = nmcli.create_connection()
2984 if rc is not None and rc != 0:
2985 module.fail_json(name=nmcli.conn_name, msg=err, rc=rc)
2986
2987 elif nmcli.state == "up":
2988 if nmcli.connection_exists():
2989 is_active = nmcli.is_connection_active()
2990
2991 if is_active and not nmcli.conn_reload:
2992 result["changed"] = False
2993 result["msg"] = f"Connection {nmcli.conn_name} is already active"
2994 module.exit_json(**result)
2995 else:
2996 if module.check_mode:
2997 module.exit_json(changed=True, **result)
2998
2999 if nmcli.conn_reload:
3000 (rc, out, err) = nmcli.reload_connection()
3001 if rc != 0:
3002 module.fail_json(msg=f"Error reloading connection named {nmcli.conn_name}: {err}", rc=rc)
3003
3004 (rc, out, err) = nmcli.up_connection()
3005 if rc != 0:
3006 module.fail_json(msg=f"Error bringing up connection named {nmcli.conn_name}: {err}", rc=rc)
3007 result["changed"] = True
3008 else:
3009 module.fail_json(
3010 name=nmcli.conn_name,
3011 msg="Connection does not exist",
3012 )
3013
3014 elif nmcli.state == "down":
3015 if nmcli.connection_exists():
3016 is_active = nmcli.is_connection_active()
3017
3018 if not is_active and not nmcli.conn_reload:
3019 result["changed"] = False
3020 result["msg"] = f"Connection {nmcli.conn_name} is already inactive"
3021 module.exit_json(**result)
3022 else:
3023 if module.check_mode:
3024 module.exit_json(changed=True, **result)
3025
3026 if nmcli.conn_reload:
3027 (rc, out, err) = nmcli.reload_connection()
3028 if rc != 0:
3029 module.fail_json(name=f"Error reloading connection {nmcli.conn_name}", msg=err, rc=rc)
3030
3031 (rc, out, err) = nmcli.down_connection()
3032 if rc != 0:
3033 module.fail_json(name=f"Error bringing down connection named {nmcli.conn_name}", msg=err, rc=rc)
3034 result["changed"] = True
3035 else:
3036 module.fail_json(msg=f"Connection {nmcli.conn_name} does not exist")
3037
3038 except NmcliModuleError as e:
3039 module.fail_json(name=nmcli.conn_name, msg=str(e))
3040
3041 if "changed" not in result:
3042 result["changed"] = rc is not None
3043 if out:
3044 result["stdout"] = out
3045 if err:
3046 result["stderr"] = err
3047
3048 module.exit_json(**result)
3049
3050
3051 if __name__ == "__main__":
3052 main()