Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_system_connection.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2025 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6
7 __metaclass__ = type
8
9 DOCUMENTATION = r"""
10 module: podman_system_connection
11 author:
12 - "Sagi Shnaidman (@sshnaidm)"
13 version_added: '1.18.0'
14 short_description: Manage podman system connections
15 notes: []
16 description:
17 - Manage podman system connections with podman system connection command.
18 - Add, remove, rename and set default connections to Podman services.
19 requirements:
20 - podman
21 options:
22 name:
23 description:
24 - Name of the connection
25 type: str
26 required: True
27 state:
28 description:
29 - State of the connection
30 type: str
31 choices:
32 - present
33 - absent
34 default: present
35 executable:
36 description:
37 - Path to C(podman) executable if it is not in the C($PATH) on the
38 machine running C(podman)
39 default: 'podman'
40 type: str
41 destination:
42 description:
43 - Destination for the connection. Required when I(state=present).
44 - Can be in the format C([user@]hostname[:port]), C(ssh://[user@]hostname[:port]),
45 C(unix://path), C(tcp://hostname:port)
46 type: str
47 default:
48 description:
49 - Make this connection the default for this user
50 type: bool
51 identity:
52 description:
53 - Path to SSH identity file
54 type: str
55 port:
56 description:
57 - SSH port (default is 22)
58 type: int
59 socket_path:
60 description:
61 - Path to the Podman service unix domain socket on the ssh destination host
62 type: str
63 new_name:
64 description:
65 - New name for the connection when renaming (used with I(state=present))
66 type: str
67 """
68
69 EXAMPLES = r"""
70 - name: Add a basic SSH connection
71 containers.podman.podman_system_connection:
72 name: production
73 destination: [email protected]
74 state: present
75
76 - name: Add SSH connection with custom port and identity
77 containers.podman.podman_system_connection:
78 name: staging
79 destination: [email protected]
80 port: 2222
81 identity: ~/.ssh/staging_rsa
82 state: present
83
84 - name: Add connection and set as default
85 containers.podman.podman_system_connection:
86 name: development
87 destination: [email protected]
88 default: true
89 state: present
90
91 - name: Add unix socket connection
92 containers.podman.podman_system_connection:
93 name: local
94 destination: unix:///run/podman/podman.sock
95 state: present
96
97 - name: Add TCP connection
98 containers.podman.podman_system_connection:
99 name: remote_tcp
100 destination: tcp://remote.example.com:8080
101 state: present
102
103 - name: Rename a connection
104 containers.podman.podman_system_connection:
105 name: old_name
106 new_name: new_name
107 state: present
108
109 - name: Remove a connection
110 containers.podman.podman_system_connection:
111 name: old_connection
112 state: absent
113 """
114
115 RETURN = r"""
116 connection:
117 description: Connection information in podman JSON format
118 returned: always
119 type: dict
120 sample: {
121 "Name": "production",
122 "URI": "ssh://[email protected]:22/run/user/0/podman/podman.sock",
123 "Default": true,
124 "ReadWrite": true
125 }
126 actions:
127 description: Actions performed on the connection
128 returned: always
129 type: list
130 sample:
131 - "Connection 'production' added"
132 - "Connection 'production' set as default"
133 """
134
135 import json
136 from ansible.module_utils.basic import AnsibleModule
137
138
139 def get_connection_info(module, executable, name):
140 """Get specific connection information from podman system connection list.
141
142 Retrieves connection information by executing 'podman system connection list --format json'
143 and searches for a connection with the specified name.
144
145 Args:
146 module (AnsibleModule): The Ansible module instance for running commands and error handling
147 executable (str): Path to the podman executable
148 name (str): Name of the specific connection to search for
149
150 Returns:
151 dict or None: Connection dictionary if found, None if not found
152
153 Connection dictionary may contain:
154 - Name (str): Connection name
155 - URI (str): Connection URI (ssh://, unix://, tcp://)
156 - Default (bool): Whether this is the default connection
157 - ReadWrite (bool, optional): Read/write access (Podman version dependent)
158 - Identity (str, optional): SSH identity file path (Podman version dependent)
159 - IsMachine (bool, optional): Whether this is a machine connection (Podman version dependent)
160
161 Raises:
162 AnsibleFailJson: If the podman command fails or JSON parsing fails
163
164 Note:
165 This function differs from the _info module's get_connection_info by returning
166 a single connection dict or None, rather than a list of connections.
167 """
168 command = [executable, "system", "connection", "list", "--format", "json"]
169 rc, out, err = module.run_command(command)
170 if rc != 0:
171 module.fail_json(msg="Failed to list connections: %s" % err)
172
173 try:
174 connections = json.loads(out) if out.strip() else []
175 for conn in connections:
176 if conn.get("Name") == name:
177 return conn
178 return None
179 except json.JSONDecodeError as e:
180 module.fail_json(msg="Failed to parse connection list JSON: %s" % str(e))
181
182
183 def connections_are_identical(conn1, conn2):
184 """Check if two connections are identical by comparing their attributes (excluding Name).
185
186 Compares all relevant connection attributes to determine if two connections
187 represent the same configuration. The Name field is excluded from comparison
188 to allow for rename operations.
189
190 Args:
191 conn1 (dict or None): First connection dictionary to compare
192 conn2 (dict or None): Second connection dictionary to compare
193
194 Returns:
195 bool: True if connections have identical attributes, False otherwise
196
197 Compared attributes:
198 - URI (str): Connection URI (must match exactly)
199 - Default (bool): Default status (must match)
200 - ReadWrite (bool, optional): Read/write access (Podman version dependent)
201 - Identity (str, optional): SSH identity file path (Podman version dependent)
202 - IsMachine (bool, optional): Machine connection flag (Podman version dependent)
203
204 Note:
205 Returns False if either connection is None or empty. Optional fields
206 (ReadWrite, Identity, IsMachine) are handled gracefully - missing fields
207 are treated as None for comparison purposes.
208 """
209 if not conn1 or not conn2:
210 return False
211 # Compare all relevant attributes except Name
212 return {**conn1, "Name": None} == {**conn2, "Name": None}
213
214
215 def destination_matches_uri(destination, current_uri):
216 """Check if a destination specification matches an existing connection URI.
217
218 Compares a user-provided destination with the current connection URI,
219 handling both full protocol URIs and simplified hostname formats.
220
221 Args:
222 destination (str): User-provided destination specification
223 current_uri (str): Existing connection URI from podman
224
225 Returns:
226 bool: True if destination matches the current URI, False otherwise
227
228 Matching logic:
229 - Full URIs (ssh://, unix://, tcp://): Requires exact match
230 - Simple format (user@host): Checks if contained in expanded URI
231
232 Examples:
233 destination_matches_uri("ssh://user@host:22", "ssh://user@host:22/path") -> True
234 destination_matches_uri("user@host", "ssh://user@host:22/path") -> True
235 destination_matches_uri("unix:///tmp/sock", "unix:///tmp/sock") -> True
236 destination_matches_uri("user@host", "ssh://other@host:22/path") -> False
237
238 Note:
239 Podman typically expands simple formats like "user@host" into full URIs
240 like "ssh://user@host:22/run/user/uid/podman/podman.sock", so this
241 function allows matching against the simplified form.
242 """
243 if destination.startswith(("ssh://", "unix://", "tcp://")):
244 # Exact protocol match required for full URIs
245 return current_uri == destination
246 # Simple hostname format - check if it's contained in the expanded URI
247 # podman expands "user@host" to "ssh://user@host:22/run/user/uid/podman/podman.sock"
248 return destination in current_uri
249
250
251 def connection_needs_update(current_conn, params):
252 """Check if a connection needs to be updated based on current vs desired state.
253
254 Compares the current connection configuration with the desired module parameters
255 to determine if changes are needed. Generates diff information for changed fields.
256
257 Args:
258 current_conn (dict or None): Current connection dictionary from podman, or None if not exists
259 params (dict): Module parameters containing desired connection configuration
260
261 Returns:
262 tuple: A tuple containing:
263 - needs_update (bool): True if connection needs changes, False if current state matches desired
264 - diffs (dict): Dictionary with 'before' and 'after' keys containing changed fields
265
266 Checked parameters:
267 - destination: Compared against current URI using destination_matches_uri()
268 - default: Compared against current Default field
269 - identity: Compared against current Identity field (if provided)
270
271 Examples:
272 # Connection doesn't exist
273 connection_needs_update(None, {...}) -> (True, {"before": {}, "after": {}})
274
275 # URI change needed
276 connection_needs_update({"URI": "old"}, {"destination": "new"}) ->
277 (True, {"before": {"URI": "old"}, "after": {"URI": "new"}})
278
279 # No changes needed
280 connection_needs_update({"URI": "same", "Default": False}, {"destination": "same", "default": False}) ->
281 (False, {"before": {}, "after": {}})
282
283 Note:
284 The identity parameter is only checked if explicitly provided (not None).
285 Missing identity in params is not treated as a change requirement.
286 """
287 if not current_conn:
288 return True, {"before": {}, "after": {}}
289
290 destination = params["destination"]
291 default = params["default"]
292 diffs = {"before": {}, "after": {}}
293
294 # Check if URI matches the expected destination format
295 current_uri = current_conn.get("URI", "")
296 if not destination_matches_uri(destination, current_uri):
297 diffs["before"]["URI"] = current_uri
298 diffs["after"]["URI"] = destination
299
300 # Check if default status needs to change
301 # Compare "Default" only when it's set explicitly in parameters,
302 # first system connection is always default
303 if default is not None and default != current_conn.get("Default"):
304 diffs["before"]["Default"] = current_conn.get("Default")
305 diffs["after"]["Default"] = default
306
307 # Check Identity if provided
308 identity = params.get("identity")
309 if identity is not None and identity != current_conn.get("Identity", ""):
310 diffs["before"]["Identity"] = current_conn.get("Identity", "")
311 diffs["after"]["Identity"] = identity
312
313 if diffs["before"] or diffs["after"]:
314 return True, diffs
315
316 return False, diffs
317
318
319 def add_connection(module, executable, name, destination, default, identity, port, socket_path):
320 """Add a new podman system connection with specified parameters.
321
322 Executes 'podman system connection add' with the provided configuration parameters.
323 Supports all connection options including SSH settings and default flag.
324
325 Args:
326 module (AnsibleModule): The Ansible module instance for running commands and error handling
327 executable (str): Path to the podman executable
328 name (str): Name for the new connection
329 destination (str): Connection destination (URI or simple hostname format)
330 default (bool): Whether to set this connection as the default
331 identity (str or None): Path to SSH identity file (optional)
332 port (int or None): SSH port number (optional, defaults to 22 for SSH)
333 socket_path (str or None): Path to podman socket on remote host (optional)
334
335 Returns:
336 tuple: A tuple containing:
337 - changed (bool): Always True since a connection is being added
338 - actions (list): List of action messages describing what was done
339
340 Command construction:
341 Base: 'podman system connection add'
342 Options added conditionally:
343 --default (if default=True)
344 --identity <path> (if identity provided)
345 --port <port> (if port provided)
346 --socket-path <path> (if socket_path provided)
347 Arguments: <name> <destination>
348
349 Actions generated:
350 - "Connection '<name>' added" (always)
351 - "Connection '<name>' set as default" (if default=True)
352
353 Raises:
354 AnsibleFailJson: If the podman command fails
355
356 Note:
357 In check mode, the command is not executed but actions are still generated
358 to show what would happen. This allows for proper diff and change reporting.
359 """
360 actions = []
361 command = [executable, "system", "connection", "add"]
362
363 if default:
364 command.extend(["--default"])
365
366 if identity:
367 command.extend(["--identity", identity])
368
369 if port:
370 command.extend(["--port", str(port)])
371
372 if socket_path:
373 command.extend(["--socket-path", socket_path])
374
375 command.extend([name, destination])
376
377 if not module.check_mode:
378 rc, out, err = module.run_command(command)
379 if rc != 0:
380 module.fail_json(msg="Failed to add connection '%s': %s" % (name, err))
381
382 actions.append("Connection '%s' added" % name)
383
384 if default:
385 actions.append("Connection '%s' set as default" % name)
386
387 return True, actions
388
389
390 def remove_connection(module, executable, name):
391 """Remove an existing podman system connection.
392
393 Executes 'podman system connection remove' to delete the specified connection.
394
395 Args:
396 module (AnsibleModule): The Ansible module instance for running commands and error handling
397 executable (str): Path to the podman executable
398 name (str): Name of the connection to remove
399
400 Returns:
401 tuple: A tuple containing:
402 - changed (bool): Always True since a connection is being removed
403 - actions (list): List containing single action message about the removal
404
405 Command executed:
406 'podman system connection remove <name>'
407
408 Actions generated:
409 - "Connection '<name>' removed"
410
411 Raises:
412 AnsibleFailJson: If the podman command fails (e.g., connection doesn't exist)
413
414 Note:
415 In check mode, the command is not executed but the action message is still
416 generated to show what would happen. The caller should verify the connection
417 exists before calling this function if idempotent behavior is required.
418 """
419 command = [executable, "system", "connection", "remove", name]
420
421 if not module.check_mode:
422 rc, out, err = module.run_command(command)
423 if rc != 0:
424 module.fail_json(msg="Failed to remove connection '%s': %s" % (name, err))
425
426 return True, ["Connection '%s' removed" % name]
427
428
429 def rename_connection(module, executable, old_name, new_name):
430 """Rename an existing podman system connection.
431
432 Executes 'podman system connection rename' to change the name of an existing connection.
433 All connection attributes (URI, default status, etc.) remain unchanged.
434
435 Args:
436 module (AnsibleModule): The Ansible module instance for running commands and error handling
437 executable (str): Path to the podman executable
438 old_name (str): Current name of the connection to rename
439 new_name (str): New name for the connection
440
441 Returns:
442 tuple: A tuple containing:
443 - changed (bool): Always True since a connection is being renamed
444 - actions (list): List containing single action message about the rename
445
446 Command executed:
447 'podman system connection rename <old_name> <new_name>'
448
449 Actions generated:
450 - "Connection '<old_name>' renamed to '<new_name>'"
451
452 Raises:
453 AnsibleFailJson: If the podman command fails (e.g., old connection doesn't exist,
454 new name already exists, etc.)
455
456 Note:
457 In check mode, the command is not executed but the action message is still
458 generated to show what would happen. The caller should verify the old connection
459 exists and the new name is available before calling this function.
460 """
461 command = [executable, "system", "connection", "rename", old_name, new_name]
462
463 if not module.check_mode:
464 rc, out, err = module.run_command(command)
465 if rc != 0:
466 module.fail_json(msg="Failed to rename connection '%s' to '%s': %s" % (old_name, new_name, err))
467
468 return True, ["Connection '%s' renamed to '%s'" % (old_name, new_name)]
469
470
471 def set_default_connection(module, executable, name):
472 """Set an existing connection as the default connection.
473
474 Executes 'podman system connection default' to mark the specified connection
475 as the default for the current user. Any previously default connection will
476 no longer be the default.
477
478 Args:
479 module (AnsibleModule): The Ansible module instance for running commands and error handling
480 executable (str): Path to the podman executable
481 name (str): Name of the connection to set as default
482
483 Returns:
484 tuple: A tuple containing:
485 - changed (bool): Always True since default status is being changed
486 - actions (list): List containing single action message about setting default
487
488 Command executed:
489 'podman system connection default <name>'
490
491 Actions generated:
492 - "Connection '<name>' set as default"
493
494 Raises:
495 AnsibleFailJson: If the podman command fails (e.g., connection doesn't exist)
496
497 Note:
498 In check mode, the command is not executed but the action message is still
499 generated to show what would happen. This function does not verify that
500 the connection exists - the caller should handle that validation.
501
502 Setting a connection as default automatically unsets any previous default
503 connection, but this function only reports the action for the specified connection.
504 """
505 command = [executable, "system", "connection", "default", name]
506
507 if not module.check_mode:
508 rc, out, err = module.run_command(command)
509 if rc != 0:
510 module.fail_json(msg="Failed to set connection '%s' as default: %s" % (name, err))
511
512 return True, ["Connection '%s' set as default" % name]
513
514
515 def main():
516 """Main entry point for the podman_system_connection Ansible module.
517
518 This function sets up the Ansible module, validates parameters, and orchestrates
519 the management of podman system connections based on the desired state.
520
521 The module supports the following operations:
522 - Creating new connections (state=present with destination)
523 - Updating existing connections (state=present with different parameters)
524 - Renaming connections (state=present with new_name)
525 - Removing connections (state=absent)
526 - Setting connections as default (default=true)
527
528 Module Parameters:
529 name (str, required): Name of the connection
530 state (str): 'present' or 'absent' (default: 'present')
531 executable (str): Path to podman executable (default: 'podman')
532 destination (str): Connection destination (required for state=present, except rename)
533 default (bool): Set as default connection (default: False)
534 identity (str): SSH identity file path (optional)
535 port (int): SSH port number (optional)
536 socket_path (str): Remote podman socket path (optional)
537 new_name (str): New name for rename operation (optional)
538
539 Parameter constraints:
540 - destination and new_name are mutually exclusive
541 - destination is required when state=present (except for rename operations)
542
543 Operation logic:
544 state=present with new_name: Rename operation
545 - Fails if source connection doesn't exist
546 - Idempotent if target name exists with identical configuration
547 - Performs rename if target name doesn't exist
548
549 state=present with destination: Add/update operation
550 - Checks if connection needs update using connection_needs_update()
551 - Removes existing connection if changes needed
552 - Adds new connection with desired parameters
553 - Idempotent if existing connection matches desired state
554
555 state=absent: Remove operation
556 - Removes connection if it exists
557 - Idempotent if connection doesn't exist
558
559 Cross-version compatibility:
560 Handles optional fields (ReadWrite, Identity, IsMachine) that may not be
561 present in all Podman versions. Missing fields are treated gracefully.
562
563 Note:
564 The module follows the 'always require full description of desired state'
565 design pattern, requiring destination for all present operations except rename.
566 """
567 module = AnsibleModule(
568 argument_spec=dict(
569 name=dict(type="str", required=True),
570 state=dict(type="str", choices=["present", "absent"], default="present"),
571 executable=dict(type="str", default="podman"),
572 destination=dict(type="str"),
573 default=dict(type="bool"),
574 identity=dict(type="str"),
575 port=dict(type="int"),
576 socket_path=dict(type="str"),
577 new_name=dict(type="str"),
578 ),
579 supports_check_mode=True,
580 mutually_exclusive=[
581 ("destination", "new_name"),
582 ],
583 )
584
585 name = module.params["name"]
586 state = module.params["state"]
587 executable = module.get_bin_path(module.params["executable"], required=True)
588 destination = module.params["destination"]
589 default = module.params["default"]
590 identity = module.params["identity"]
591 port = module.params["port"]
592 socket_path = module.params["socket_path"]
593 new_name = module.params["new_name"]
594
595 # Validate required parameters - always require destination when state=present (except for rename)
596 if state == "present" and not new_name and not destination:
597 module.fail_json(msg="destination is required when state=present")
598
599 # Get current connection state
600 current_conn = get_connection_info(module, executable, name)
601
602 changed = False
603 actions = []
604 connection_info = {}
605 diff = {"before": {}, "after": {}}
606
607 if state == "present":
608 if new_name:
609 # Handle rename operation
610 if not current_conn:
611 module.fail_json(msg="Cannot rename non-existent connection '%s'" % name)
612
613 # Check if new name already exists
614 new_conn = get_connection_info(module, executable, new_name)
615 if new_conn:
616 # Check if the existing connection with new_name is identical to current_conn
617 if connections_are_identical(current_conn, new_conn):
618 # Connections are identical - idempotent, no changes needed
619 connection_info = new_conn
620 else:
621 # Different connection exists with the same name - fail
622 module.fail_json(msg="Connection with name '%s' already exists and is different" % new_name)
623 else:
624 # Perform rename
625 changed, rename_actions = rename_connection(module, executable, name, new_name)
626 actions.extend(rename_actions)
627
628 # Get connection info after rename
629 if not module.check_mode:
630 final_conn = get_connection_info(module, executable, new_name)
631 connection_info = final_conn
632 else:
633 old_conn_info = get_connection_info(module, executable, name)
634 old_conn_info["Name"] = new_name
635 connection_info = old_conn_info
636
637 else:
638 # Handle add/update operation (destination is always provided)
639 needs_update, diff = connection_needs_update(current_conn, module.params)
640 if needs_update:
641 # Remove existing connection if it exists with different parameters
642 if current_conn:
643 changed, remove_actions = remove_connection(module, executable, name)
644 actions.extend(remove_actions)
645
646 # Add the connection with desired parameters
647 changed, add_actions = add_connection(
648 module, executable, name, destination, default, identity, port, socket_path
649 )
650 actions.extend(add_actions)
651
652 # Get final connection state
653 if not module.check_mode:
654 final_conn = get_connection_info(module, executable, name)
655 connection_info = final_conn
656 else:
657 # In check mode, provide expected values
658 connection_info = {
659 "Name": name,
660 "URI": destination,
661 "Default": default,
662 }
663
664 else:
665 # Connection exists and matches desired state - idempotent
666 connection_info = current_conn
667
668 elif state == "absent":
669 if current_conn:
670 changed, remove_actions = remove_connection(module, executable, name)
671 actions.extend(remove_actions)
672 connection_info = {}
673 module.log("PODMAN-SYSTEM-CONNECTION: changed=%s, actions=%s, diff=%s" % (changed, actions, diff))
674 diff_info = {}
675 if diff["before"] or diff["after"]:
676 diff_info = {
677 "before": "\n".join(["%s - %s" % (k, v) for k, v in sorted(diff["before"].items())]) + "\n",
678 "after": "\n".join(["%s - %s" % (k, v) for k, v in sorted(diff["after"].items())]) + "\n",
679 }
680 module.exit_json(
681 changed=changed,
682 connection=connection_info,
683 actions=actions,
684 diff=diff_info,
685 )
686
687
688 if __name__ == "__main__":
689 main()