Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, Lukas Bestle <[email protected]>
4 # Copyright (c) 2017, Michael Heap <[email protected]>
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: mas
12 short_description: Manage Mac App Store applications with mas-cli
13 description:
14 - Installs, uninstalls and updates macOS applications from the Mac App Store using the C(mas-cli).
15 version_added: '0.2.0'
16 author:
17 - Michael Heap (@mheap)
18 - Lukas Bestle (@lukasbestle)
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 id:
28 description:
29 - The Mac App Store identifier of the app(s) you want to manage.
30 - This can be found by running C(mas search APP_NAME) on your machine.
31 type: list
32 elements: int
33 state:
34 description:
35 - Desired state of the app installation.
36 - The V(absent) value requires root permissions, also see the examples.
37 type: str
38 choices:
39 - absent
40 - latest
41 - present
42 default: present
43 upgrade_all:
44 description:
45 - Upgrade all installed Mac App Store apps.
46 type: bool
47 default: false
48 aliases: ["upgrade"]
49 requirements:
50 - macOS 10.11 or higher.
51 - "mas-cli (U(https://github.com/mas-cli/mas)) 1.5.0+ available as C(mas) in the bin path"
52 - The Apple ID to use already needs to be signed in to the Mac App Store (check with C(mas account)).
53 - The feature of "checking if user is signed in" is disabled for anyone using macOS 12.0+.
54 - Users need to sign in to the Mac App Store GUI beforehand for anyone using macOS 12.0+ due to U(https://github.com/mas-cli/mas/issues/417).
55 """
56
57 EXAMPLES = r"""
58 - name: Install Keynote
59 community.general.mas:
60 id: 409183694
61 state: present
62
63 - name: Install Divvy with command mas installed in /usr/local/bin
64 community.general.mas:
65 id: 413857545
66 state: present
67 environment:
68 PATH: /usr/local/bin:{{ ansible_facts.env.PATH }}
69
70 - name: Install a list of apps
71 community.general.mas:
72 id:
73 - 409183694 # Keynote
74 - 413857545 # Divvy
75 state: present
76
77 - name: Ensure the latest Keynote version is installed
78 community.general.mas:
79 id: 409183694
80 state: latest
81
82 - name: Upgrade all installed Mac App Store apps
83 community.general.mas:
84 upgrade_all: true
85
86 - name: Install specific apps and also upgrade all others
87 community.general.mas:
88 id:
89 - 409183694 # Keynote
90 - 413857545 # Divvy
91 state: present
92 upgrade_all: true
93
94 - name: Uninstall Divvy
95 community.general.mas:
96 id: 413857545
97 state: absent
98 become: true # Uninstallation requires root permissions
99 """
100
101 RETURN = r""" # """
102
103 import os
104 import platform
105
106 from ansible.module_utils.basic import AnsibleModule
107
108 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
109
110 NOT_WORKING_MAC_VERSION_MAS_ACCOUNT = "12.0"
111
112
113 class Mas:
114 def __init__(self, module):
115 self.module = module
116
117 # Initialize data properties
118 self.mas_path = self.module.get_bin_path("mas")
119 self._checked_signin = False
120 self._mac_version = platform.mac_ver()[0] or "0.0"
121 self._installed = None # Populated only if needed
122 self._outdated = None # Populated only if needed
123 self.count_install = 0
124 self.count_upgrade = 0
125 self.count_uninstall = 0
126 self.result = {"changed": False}
127
128 self.check_mas_tool()
129
130 def app_command(self, command, id):
131 """Runs a `mas` command on a given app; command can be 'install', 'upgrade' or 'uninstall'"""
132
133 if not self.module.check_mode:
134 if command != "uninstall":
135 self.check_signin()
136
137 rc, out, err = self.run([command, str(id)])
138 if rc != 0:
139 self.module.fail_json(msg=f"Error running command '{command}' on app '{id}': {out.rstrip()}")
140
141 # No error or dry run
142 self.__dict__[f"count_{command}"] += 1
143
144 def check_mas_tool(self):
145 """Verifies that the `mas` tool is available in a recent version"""
146
147 # Is the `mas` tool available at all?
148 if not self.mas_path:
149 self.module.fail_json(msg="Required `mas` tool is not installed")
150
151 # Is the version recent enough?
152 rc, out, err = self.run(["version"])
153 if rc != 0 or not out.strip() or LooseVersion(out.strip()) < LooseVersion("1.5.0"):
154 self.module.fail_json(msg=f"`mas` tool in version 1.5.0+ needed, got {out.strip()}")
155
156 def check_signin(self):
157 """Verifies that the user is signed in to the Mac App Store"""
158 # Only check this once per execution
159 if self._checked_signin:
160 return
161 if LooseVersion(self._mac_version) >= LooseVersion(NOT_WORKING_MAC_VERSION_MAS_ACCOUNT):
162 # Checking if user is signed-in is disabled due to https://github.com/mas-cli/mas/issues/417
163 self.module.log("WARNING: You must be signed in via the Mac App Store GUI beforehand else error will occur")
164 else:
165 rc, out, err = self.run(["account"])
166 if out.split("\n", 1)[0].rstrip() == "Not signed in":
167 self.module.fail_json(msg="You must be signed in to the Mac App Store")
168
169 self._checked_signin = True
170
171 def exit(self):
172 """Exit with the data we have collected over time"""
173
174 msgs = []
175 if self.count_install > 0:
176 msgs.append(f"Installed {self.count_install} app(s)")
177 if self.count_upgrade > 0:
178 msgs.append(f"Upgraded {self.count_upgrade} app(s)")
179 if self.count_uninstall > 0:
180 msgs.append(f"Uninstalled {self.count_uninstall} app(s)")
181
182 if msgs:
183 self.result["changed"] = True
184 self.result["msg"] = ", ".join(msgs)
185
186 self.module.exit_json(**self.result)
187
188 def get_current_state(self, command):
189 """Returns the list of all app IDs; command can either be 'list' or 'outdated'"""
190
191 rc, raw_apps, err = self.run([command])
192 rows = raw_apps.split("\n")
193 if rows[0] == "No installed apps found":
194 rows = []
195 apps = []
196 for r in rows:
197 # mas 2.3.0 and older:
198 # 123456789 App Name (version)
199 # 4567890 App Name Longer (version)
200 #
201 # mas 3.0.0 and newer:
202 # 123456789 App Name (version)
203 # 4567890 App Name Longer (version)
204 r = r.strip().split(" ", 1)
205 if len(r) == 2:
206 apps.append(int(r[0]))
207
208 return apps
209
210 def installed(self):
211 """Returns the list of installed apps"""
212
213 # Populate cache if not already done
214 if self._installed is None:
215 self._installed = self.get_current_state("list")
216
217 return self._installed
218
219 def is_installed(self, id):
220 """Checks whether the given app is installed"""
221
222 return int(id) in self.installed()
223
224 def is_outdated(self, id):
225 """Checks whether the given app is installed, but outdated"""
226
227 return int(id) in self.outdated()
228
229 def outdated(self):
230 """Returns the list of installed, but outdated apps"""
231
232 # Populate cache if not already done
233 if self._outdated is None:
234 self._outdated = self.get_current_state("outdated")
235
236 return self._outdated
237
238 def run(self, cmd):
239 """Runs a command of the `mas` tool"""
240
241 cmd.insert(0, self.mas_path)
242 return self.module.run_command(cmd, False)
243
244 def upgrade_all(self):
245 """Upgrades all installed apps and sets the correct result data"""
246
247 outdated = self.outdated()
248
249 if not self.module.check_mode:
250 self.check_signin()
251
252 rc, out, err = self.run(["upgrade"])
253 if rc != 0:
254 self.module.fail_json(msg=f"Could not upgrade all apps: {out.rstrip()}")
255
256 self.count_upgrade += len(outdated)
257
258
259 def main():
260 module = AnsibleModule(
261 argument_spec=dict(
262 id=dict(type="list", elements="int"),
263 state=dict(type="str", default="present", choices=["absent", "latest", "present"]),
264 upgrade_all=dict(type="bool", default=False, aliases=["upgrade"]),
265 ),
266 supports_check_mode=True,
267 )
268 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
269 mas = Mas(module)
270
271 if module.params["id"]:
272 apps = module.params["id"]
273 else:
274 apps = []
275
276 state = module.params["state"]
277 upgrade = module.params["upgrade_all"]
278
279 # Run operations on the given app IDs
280 for app in sorted(set(apps)):
281 if state == "present":
282 if not mas.is_installed(app):
283 mas.app_command("install", app)
284
285 elif state == "absent":
286 if mas.is_installed(app):
287 # Ensure we are root
288 if os.getuid() != 0:
289 module.fail_json(msg="Uninstalling apps requires root permissions ('become: true')")
290
291 mas.app_command("uninstall", app)
292
293 elif state == "latest":
294 if not mas.is_installed(app):
295 mas.app_command("install", app)
296 elif mas.is_outdated(app):
297 mas.app_command("upgrade", app)
298
299 # Upgrade all apps if requested
300 mas._outdated = None # Clear cache
301 if upgrade and mas.outdated():
302 mas.upgrade_all()
303
304 # Exit with the collected data
305 mas.exit()
306
307
308 if __name__ == "__main__":
309 main()