Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2026, Alexei Znamensky (russoz) <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: snap_connect
11 short_description: Manages snap interface connections
12 version_added: "12.6.0"
13 description:
14 - Manages connections between snap plugs and slots.
15 - Snaps run in a sandbox and need explicit interface connections to access system resources
16 or communicate with other snaps.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: full
24 options:
25 state:
26 description:
27 - Desired state of the connection.
28 type: str
29 choices: [absent, present]
30 default: present
31 plug:
32 description:
33 - The plug endpoint in the format C(<snap>:<plug>).
34 type: str
35 required: true
36 slot:
37 description:
38 - The slot endpoint in the format C(<snap>:<slot>) or C(:<slot>) for system slots.
39 - If not specified, snapd will attempt to find a matching slot automatically.
40 type: str
41 notes:
42 - Privileged operations require root privileges.
43 author:
44 - Alexei Znamensky (@russoz) <[email protected]>
45 seealso:
46 - module: community.general.snap
47 - module: community.general.snap_alias
48 """
49
50 EXAMPLES = r"""
51 - name: Connect firefox camera plug to system camera slot
52 community.general.snap_connect:
53 plug: firefox:camera
54 slot: ":camera"
55
56 - name: Connect snap plug (slot resolved automatically by snapd)
57 community.general.snap_connect:
58 plug: my-app:network
59
60 - name: Disconnect a specific connection
61 community.general.snap_connect:
62 plug: firefox:camera
63 slot: ":camera"
64 state: absent
65 """
66
67 RETURN = r"""
68 snap_connections:
69 description: The list of snap connections after execution.
70 type: list
71 elements: dict
72 returned: always
73 contains:
74 interface:
75 description: The interface name.
76 type: str
77 plug:
78 description: The plug endpoint.
79 type: str
80 slot:
81 description: The slot endpoint.
82 type: str
83 version:
84 description: Versions of snap components as reported by C(snap version).
85 type: dict
86 returned: always
87 """
88
89 import re
90
91 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper
92 from ansible_collections.community.general.plugins.module_utils._snap import get_version, snap_runner
93
94
95 class SnapConnect(StateModuleHelper):
96 _RE_CONNECTIONS = re.compile(r"^(?P<interface>\S+)\s+(?P<plug>\S+)\s+(?P<slot>\S+)\s+.*$")
97
98 module = dict(
99 argument_spec={
100 "state": dict(type="str", choices=["absent", "present"], default="present"),
101 "plug": dict(type="str", required=True),
102 "slot": dict(type="str"),
103 },
104 supports_check_mode=True,
105 )
106
107 def __init_module__(self):
108 self.runner = snap_runner(self.module)
109 self.vars.version = get_version(self.runner)
110 self.vars.set("snap_connections", self._get_connections(), change=True, diff=True)
111
112 def __quit_module__(self):
113 self.vars.snap_connections = self._get_connections()
114
115 def _get_connections(self):
116 def process(rc, out, err):
117 if rc != 0:
118 return []
119 connections = []
120 for line in out.splitlines()[1:]:
121 match = self._RE_CONNECTIONS.match(line.strip())
122 if match:
123 connections.append(match.groupdict())
124 return connections
125
126 with self.runner("_connections", output_process=process) as ctx:
127 return ctx.run()
128
129 def _is_connected(self):
130 plug = self.vars.plug
131 slot = self.vars.slot
132 return any(
133 conn["slot"] != "-" and conn["plug"] == plug and (slot is None or conn["slot"] == slot)
134 for conn in self.vars.snap_connections
135 )
136
137 def state_present(self):
138 if not self._is_connected():
139 self.changed = True
140 if self.check_mode:
141 return
142 with self.runner("_connect slot") as ctx:
143 rc, dummy, err = ctx.run(_connect=self.vars.plug, slot=self.vars.slot)
144 if rc != 0:
145 self.do_raise(msg=f"snap connect failed: {err}")
146
147 def state_absent(self):
148 if self._is_connected():
149 self.changed = True
150 if self.check_mode:
151 return
152 with self.runner("_disconnect slot") as ctx:
153 rc, dummy, err = ctx.run(_disconnect=self.vars.plug, slot=self.vars.slot)
154 if rc != 0:
155 self.do_raise(msg=f"snap disconnect failed: {err}")
156
157
158 def main():
159 SnapConnect.execute()
160
161
162 if __name__ == "__main__":
163 main()