Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2022, Alexei Znamensky <[email protected]>
4 # Copyright (c) 2013, Scott Anderson <[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: django_manage
12 short_description: Manages a Django application
13 description:
14 - Manages a Django application using the C(manage.py) application frontend to C(django-admin). With the O(virtualenv) parameter,
15 all management commands are executed by the given C(virtualenv) installation.
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: none
21 diff_mode:
22 support: none
23 options:
24 command:
25 description:
26 - The name of the Django management command to run. The commands listed below are built in this module and have some
27 basic parameter validation.
28 - V(collectstatic) - Collects the static files into C(STATIC_ROOT).
29 - V(createcachetable) - Creates the cache tables for use with the database cache backend.
30 - V(flush) - Removes all data from the database.
31 - V(loaddata) - Searches for and loads the contents of the named O(fixtures) into the database.
32 - V(migrate) - Synchronizes the database state with models and migrations.
33 - V(test) - Runs tests for all installed apps.
34 - Custom commands can be entered, but they fail unless they are known to Django. Custom commands that may prompt for
35 user input should be run with the C(--noinput) flag.
36 - Support for the values V(cleanup), V(syncdb), V(validate) was removed in community.general 9.0.0. See note about supported
37 versions of Django.
38 type: str
39 required: true
40 project_path:
41 description:
42 - The path to the root of the Django application where C(manage.py) lives.
43 type: path
44 required: true
45 aliases: [app_path, chdir]
46 settings:
47 description:
48 - The Python path to the application's settings module, such as V(myapp.settings).
49 type: path
50 pythonpath:
51 description:
52 - A directory to add to the Python path. Typically used to include the settings module if it is located external to
53 the application directory.
54 - This would be equivalent to adding O(pythonpath)'s value to the E(PYTHONPATH) environment variable.
55 type: path
56 aliases: [python_path]
57 virtualenv:
58 description:
59 - An optional path to a C(virtualenv) installation to use while running the manage application.
60 - The virtual environment must exist, otherwise the module fails.
61 type: path
62 aliases: [virtual_env]
63 apps:
64 description:
65 - A list of space-delimited apps to target. Used by the V(test) command.
66 type: str
67 cache_table:
68 description:
69 - The name of the table used for database-backed caching. Used by the V(createcachetable) command.
70 type: str
71 clear:
72 description:
73 - Clear the existing files before trying to copy or link the original file.
74 - Used only with the V(collectstatic) command. The C(--noinput) argument is added automatically.
75 default: false
76 type: bool
77 database:
78 description:
79 - The database to target. Used by the V(createcachetable), V(flush), V(loaddata), V(syncdb), and V(migrate) commands.
80 type: str
81 failfast:
82 description:
83 - Fail the command immediately if a test fails. Used by the V(test) command.
84 default: false
85 type: bool
86 aliases: [fail_fast]
87 fixtures:
88 description:
89 - A space-delimited list of fixture file names to load in the database. B(Required) by the V(loaddata) command.
90 type: str
91 skip:
92 description:
93 - Skips over out-of-order missing migrations, you can only use this parameter with V(migrate) command.
94 type: bool
95 merge:
96 description:
97 - Runs out-of-order or missing migrations as they are not rollback migrations, you can only use this parameter with
98 V(migrate) command.
99 type: bool
100 link:
101 description:
102 - Creates links to the files instead of copying them, you can only use this parameter with V(collectstatic) command.
103 type: bool
104 testrunner:
105 description:
106 - Controls the test runner class that is used to execute tests.
107 - This parameter is passed as-is to C(manage.py).
108 type: str
109 aliases: [test_runner]
110
111 notes:
112 - 'B(ATTENTION): Support for Django releases older than 4.1 has been removed in community.general version 9.0.0. While the
113 module allows for free-form commands, not verifying the version of Django being used, it is B(strongly recommended) to
114 use a more recent version of the framework.'
115 - Please notice that Django 4.1 requires Python 3.8 or greater.
116 - This module does not create a virtualenv if the O(virtualenv) parameter is specified and a virtual environment does not
117 already exist at the given location. This behavior changed in community.general version 9.0.0.
118 - The recommended way to create a virtual environment in Ansible is by using M(ansible.builtin.pip).
119 - This module assumes English error messages for the V(createcachetable) command to detect table existence, unfortunately.
120 - To be able to use the V(collectstatic) command, you must have enabled C(staticfiles) in your settings.
121 - Your C(manage.py) application must be executable (C(rwxr-xr-x)), and must have a valid shebang, for example C(#!/usr/bin/env
122 python), for invoking the appropriate Python interpreter.
123 seealso:
124 - name: django-admin and manage.py Reference
125 description: Reference for C(django-admin) or C(manage.py) commands.
126 link: https://docs.djangoproject.com/en/4.1/ref/django-admin/
127 - name: Django Download page
128 description: The page showing how to get Django and the timeline of supported releases.
129 link: https://www.djangoproject.com/download/
130 - name: What Python version can I use with Django?
131 description: From the Django FAQ, the response to Python requirements for the framework.
132 link: https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django
133 requirements: ["django >= 4.1"]
134 author:
135 - Alexei Znamensky (@russoz)
136 - Scott Anderson (@tastychutney)
137 """
138
139 EXAMPLES = r"""
140 - name: Run cleanup on the application installed in django_dir
141 community.general.django_manage:
142 command: clearsessions
143 project_path: "{{ django_dir }}"
144
145 - name: Load the initial_data fixture into the application
146 community.general.django_manage:
147 command: loaddata
148 project_path: "{{ django_dir }}"
149 fixtures: "{{ initial_data }}"
150
151 - name: Run syncdb on the application
152 community.general.django_manage:
153 command: migrate
154 project_path: "{{ django_dir }}"
155 settings: "{{ settings_app_name }}"
156 pythonpath: "{{ settings_dir }}"
157 virtualenv: "{{ virtualenv_dir }}"
158
159 - name: Run the SmokeTest test case from the main app. Useful for testing deploys
160 community.general.django_manage:
161 command: test
162 project_path: "{{ django_dir }}"
163 apps: main.SmokeTest
164
165 - name: Create an initial superuser
166 community.general.django_manage:
167 command: "createsuperuser --noinput --username=admin [email protected]"
168 project_path: "{{ django_dir }}"
169 """
170
171 import os
172 import shlex
173 import sys
174
175 from ansible.module_utils.basic import AnsibleModule
176
177
178 def _fail(module, cmd, out, err, **kwargs):
179 msg = ""
180 if out:
181 msg += f"stdout: {out}"
182 if err:
183 msg += f"\n:stderr: {err}"
184 module.fail_json(cmd=cmd, msg=msg, **kwargs)
185
186
187 def _ensure_virtualenv(module):
188 venv_param = module.params["virtualenv"]
189 if venv_param is None:
190 return
191
192 vbin = os.path.join(venv_param, "bin")
193 activate = os.path.join(vbin, "activate")
194
195 if not os.path.exists(activate):
196 module.fail_json(msg=f"{venv_param} does not point to a valid virtual environment")
197
198 os.environ["PATH"] = f"{vbin}:{os.environ['PATH']}"
199 os.environ["VIRTUAL_ENV"] = venv_param
200
201
202 def createcachetable_check_changed(output):
203 return "already exists" not in output
204
205
206 def flush_filter_output(line):
207 return "Installed" in line and "Installed 0 object" not in line
208
209
210 def loaddata_filter_output(line):
211 return "Installed" in line and "Installed 0 object" not in line
212
213
214 def migrate_filter_output(line):
215 return (
216 ("Migrating forwards " in line)
217 or ("Installed" in line and "Installed 0 object" not in line)
218 or ("Applying" in line)
219 )
220
221
222 def collectstatic_filter_output(line):
223 return line and "0 static files" not in line
224
225
226 def main():
227 command_allowed_param_map = dict(
228 createcachetable=(
229 "cache_table",
230 "database",
231 ),
232 flush=("database",),
233 loaddata=(
234 "database",
235 "fixtures",
236 ),
237 test=(
238 "failfast",
239 "testrunner",
240 "apps",
241 ),
242 migrate=(
243 "apps",
244 "skip",
245 "merge",
246 "database",
247 ),
248 collectstatic=(
249 "clear",
250 "link",
251 ),
252 )
253
254 command_required_param_map = dict(
255 loaddata=("fixtures",),
256 )
257
258 # forces --noinput on every command that needs it
259 noinput_commands = (
260 "flush",
261 "migrate",
262 "test",
263 "collectstatic",
264 )
265
266 # These params are allowed for certain commands only
267 specific_params = ("apps", "clear", "database", "failfast", "fixtures", "testrunner")
268
269 # These params are automatically added to the command if present
270 general_params = (
271 "settings",
272 "pythonpath",
273 "database",
274 )
275 specific_boolean_params = ("clear", "failfast", "skip", "merge", "link")
276 end_of_command_params = ("apps", "cache_table", "fixtures")
277
278 module = AnsibleModule(
279 argument_spec=dict(
280 command=dict(required=True, type="str"),
281 project_path=dict(required=True, type="path", aliases=["app_path", "chdir"]),
282 settings=dict(type="path"),
283 pythonpath=dict(type="path", aliases=["python_path"]),
284 virtualenv=dict(type="path", aliases=["virtual_env"]),
285 apps=dict(),
286 cache_table=dict(type="str"),
287 clear=dict(default=False, type="bool"),
288 database=dict(type="str"),
289 failfast=dict(default=False, type="bool", aliases=["fail_fast"]),
290 fixtures=dict(type="str"),
291 testrunner=dict(type="str", aliases=["test_runner"]),
292 skip=dict(type="bool"),
293 merge=dict(type="bool"),
294 link=dict(type="bool"),
295 ),
296 )
297
298 command_split = shlex.split(module.params["command"])
299 command_bin = command_split[0]
300 project_path = module.params["project_path"]
301 virtualenv = module.params["virtualenv"]
302
303 for param in specific_params:
304 value = module.params[param]
305 if value and param not in command_allowed_param_map[command_bin]:
306 module.fail_json(msg=f"{param} param is incompatible with command={command_bin}")
307
308 for param in command_required_param_map.get(command_bin, ()):
309 if not module.params[param]:
310 module.fail_json(msg=f"{param} param is required for command={command_bin}")
311
312 _ensure_virtualenv(module)
313
314 run_cmd_args = ["./manage.py"] + command_split
315
316 if command_bin in noinput_commands and "--noinput" not in command_split:
317 run_cmd_args.append("--noinput")
318
319 for param in general_params:
320 if module.params[param]:
321 run_cmd_args.append(f"--{param}={module.params[param]}")
322
323 for param in specific_boolean_params:
324 if module.params[param]:
325 run_cmd_args.append(f"--{param}")
326
327 # these params always get tacked on the end of the command
328 for param in end_of_command_params:
329 if module.params[param]:
330 if param in ("fixtures", "apps"):
331 run_cmd_args.extend(shlex.split(module.params[param]))
332 else:
333 run_cmd_args.append(module.params[param])
334
335 rc, out, err = module.run_command(run_cmd_args, cwd=project_path)
336 if rc != 0:
337 if command_bin == "createcachetable" and "table" in err and "already exists" in err:
338 out = "already exists."
339 else:
340 if "Unknown command:" in err:
341 _fail(module, run_cmd_args, err, f"Unknown django command: {command_bin}")
342 _fail(module, run_cmd_args, out, err, path=os.environ["PATH"], syspath=sys.path)
343
344 changed = False
345
346 lines = out.split("\n")
347 filt = globals().get(f"{command_bin}_filter_output", None)
348 if filt:
349 filtered_output = list(filter(filt, lines))
350 if len(filtered_output):
351 changed = True
352 check_changed = globals().get(f"{command_bin}_check_changed", None)
353 if check_changed:
354 changed = check_changed(out)
355
356 module.exit_json(
357 changed=changed,
358 out=out,
359 cmd=run_cmd_args,
360 app_path=project_path,
361 project_path=project_path,
362 virtualenv=virtualenv,
363 settings=module.params["settings"],
364 pythonpath=module.params["pythonpath"],
365 )
366
367
368 if __name__ == "__main__":
369 main()