Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Jasper N. Brouwer <[email protected]>
4 # Copyright (c) 2014, Ramon de la Fuente <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: deploy_helper
13 author: "Ramon de la Fuente (@ramondelafuente)"
14 short_description: Manages some of the steps common in deploying projects
15 description:
16 - The Deploy Helper manages some of the steps common in deploying software. It creates a folder structure, manages a symlink
17 for the current release and cleans up old releases.
18 - Running it with the O(state=query) or O(state=present) returns the C(deploy_helper) fact. C(project_path), whatever you
19 set in the O(path) parameter, C(current_path), the path to the symlink that points to the active release, C(releases_path),
20 the path to the folder to keep releases in, C(shared_path), the path to the folder to keep shared resources in, C(unfinished_filename),
21 the file to check for to recognize unfinished builds, C(previous_release), the release the 'current' symlink is pointing
22 to, C(previous_release_path), the full path to the 'current' symlink target, C(new_release), either the O(release) parameter
23 or a generated timestamp, C(new_release_path), the path to the new release folder (not created by the module).
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29
30 options:
31 path:
32 type: path
33 required: true
34 aliases: ['dest']
35 description:
36 - The root path of the project. Returned in the C(deploy_helper.project_path) fact.
37 state:
38 type: str
39 description:
40 - The state of the project.
41 - V(query) gathers facts.
42 - V(present) creates the project C(root) folder, and in it the C(releases) and C(shared) folders.
43 - V(finalize) removes the unfinished_filename file, creates a symlink to the newly deployed release and optionally cleans
44 old releases.
45 - V(clean) removes failed & old releases.
46 - V(absent) removes the project folder (synonymous to the M(ansible.builtin.file) module with O(state=absent)).
47 choices: [present, finalize, absent, clean, query]
48 default: present
49
50 release:
51 type: str
52 description:
53 - The release version that is being deployed. Defaults to a timestamp format C(%Y%m%d%H%M%S) (for example V(20141119223359)).
54 This parameter is optional during O(state=present), but needs to be set explicitly for O(state=finalize). You can
55 use the generated fact C(release={{ deploy_helper.new_release }}).
56 releases_path:
57 type: str
58 description:
59 - The name of the folder that holds the releases. This can be relative to O(path) or absolute. Returned in the C(deploy_helper.releases_path)
60 fact.
61 default: releases
62
63 shared_path:
64 type: path
65 description:
66 - The name of the folder that holds the shared resources. This can be relative to O(path) or absolute. If this is set
67 to an empty string, no shared folder is created. Returned in the C(deploy_helper.shared_path) fact.
68 default: shared
69
70 current_path:
71 type: path
72 description:
73 - The name of the symlink that is created when the deploy is finalized. Used in O(state=finalize) and O(state=clean).
74 Returned in the C(deploy_helper.current_path) fact.
75 default: current
76
77 unfinished_filename:
78 type: str
79 description:
80 - The name of the file that indicates a deploy has not finished. All folders in the O(releases_path) that contain this
81 file are deleted on O(state=finalize) with O(clean=true), or O(state=clean). This file is automatically deleted from
82 the C(new_release_path) during O(state=finalize).
83 default: DEPLOY_UNFINISHED
84
85 clean:
86 description:
87 - Whether to run the clean procedure in case of O(state=finalize).
88 type: bool
89 default: true
90
91 keep_releases:
92 type: int
93 description:
94 - The number of old releases to keep when cleaning. Used in O(state=finalize) and O(state=clean). Any unfinished builds
95 are deleted first, so only correct releases count. The current version does not count.
96 default: 5
97
98 notes:
99 - Facts are only returned for O(state=query) and O(state=present). If you use both, you should pass any overridden parameters
100 to both calls, otherwise the second call overwrites the facts of the first one.
101 - When using O(state=clean), the releases are ordered by I(creation date). You should be able to switch to a new naming
102 strategy without problems.
103 - Because of the default behaviour of generating the C(new_release) fact, this module is not idempotent unless you pass
104 your own release name with O(release). Due to the nature of deploying software, this should not be much of a problem.
105 extends_documentation_fragment:
106 - ansible.builtin.files
107 - community.general._attributes
108 """
109
110 EXAMPLES = r"""
111 # General explanation, starting with an example folder structure for a project:
112
113 # root:
114 # releases:
115 # - 20140415234508
116 # - 20140415235146
117 # - 20140416082818
118 #
119 # shared:
120 # - sessions
121 # - uploads
122 #
123 # current: releases/20140416082818
124
125
126 # The 'releases' folder holds all the available releases. A release is a complete build of the application being
127 # deployed. This can be a clone of a repository for example, or a sync of a local folder on your filesystem.
128 # Having timestamped folders is one way of having distinct releases, but you could choose your own strategy like
129 # git tags or commit hashes.
130 #
131 # During a deploy, a new folder should be created in the releases folder and any build steps required should be
132 # performed. Once the new build is ready, the deploy procedure is 'finalized' by replacing the 'current' symlink
133 # with a link to this build.
134 #
135 # The 'shared' folder holds any resource that is shared between releases. Examples of this are web-server
136 # session files, or files uploaded by users of your application. It's quite common to have symlinks from a release
137 # folder pointing to a shared/subfolder, and creating these links would be automated as part of the build steps.
138 #
139 # The 'current' symlink points to one of the releases. Probably the latest one, unless a deploy is in progress.
140 # The web-server's root for the project will go through this symlink, so the 'downtime' when switching to a new
141 # release is reduced to the time it takes to switch the link.
142 #
143 # To distinguish between successful builds and unfinished ones, a file can be placed in the folder of the release
144 # that is currently in progress. The existence of this file will mark it as unfinished, and allow an automated
145 # procedure to remove it during cleanup.
146
147
148 # Typical usage
149 - name: Initialize the deploy root and gather facts
150 community.general.deploy_helper:
151 path: /path/to/root
152 - name: Clone the project to the new release folder
153 ansible.builtin.git:
154 repo: ansible.builtin.git://foosball.example.org/path/to/repo.git
155 dest: '{{ deploy_helper.new_release_path }}'
156 version: v1.1.1
157 - name: Add an unfinished file, to allow cleanup on successful finalize
158 ansible.builtin.file:
159 path: '{{ deploy_helper.new_release_path }}/{{ deploy_helper.unfinished_filename }}'
160 state: touch
161 - name: Perform some build steps, like running your dependency manager for example
162 composer:
163 command: install
164 working_dir: '{{ deploy_helper.new_release_path }}'
165 - name: Create some folders in the shared folder
166 ansible.builtin.file:
167 path: '{{ deploy_helper.shared_path }}/{{ item }}'
168 state: directory
169 with_items:
170 - sessions
171 - uploads
172 - name: Add symlinks from the new release to the shared folder
173 ansible.builtin.file:
174 path: '{{ deploy_helper.new_release_path }}/{{ item.path }}'
175 src: '{{ deploy_helper.shared_path }}/{{ item.src }}'
176 state: link
177 with_items:
178 - path: app/sessions
179 src: sessions
180 - path: web/uploads
181 src: uploads
182 - name: Finalize the deploy, removing the unfinished file and switching the symlink
183 community.general.deploy_helper:
184 path: /path/to/root
185 release: '{{ deploy_helper.new_release }}'
186 state: finalize
187
188 # Retrieving facts before running a deploy
189 - name: Run 'state=query' to gather facts without changing anything
190 community.general.deploy_helper:
191 path: /path/to/root
192 state: query
193 # Remember to set the 'release' parameter when you actually call 'state=present' later
194 - name: Initialize the deploy root
195 community.general.deploy_helper:
196 path: /path/to/root
197 release: '{{ deploy_helper.new_release }}'
198 state: present
199
200 # all paths can be absolute or relative (to the 'path' parameter)
201 - community.general.deploy_helper:
202 path: /path/to/root
203 releases_path: /var/www/project/releases
204 shared_path: /var/www/shared
205 current_path: /var/www/active
206
207 # Using your own naming strategy for releases (a version tag in this case):
208 - community.general.deploy_helper:
209 path: /path/to/root
210 release: v1.1.1
211 state: present
212 - community.general.deploy_helper:
213 path: /path/to/root
214 release: '{{ deploy_helper.new_release }}'
215 state: finalize
216
217 # Using a different unfinished_filename:
218 - community.general.deploy_helper:
219 path: /path/to/root
220 unfinished_filename: README.md
221 release: '{{ deploy_helper.new_release }}'
222 state: finalize
223
224 # Postponing the cleanup of older builds:
225 - community.general.deploy_helper:
226 path: /path/to/root
227 release: '{{ deploy_helper.new_release }}'
228 state: finalize
229 clean: false
230 - community.general.deploy_helper:
231 path: /path/to/root
232 state: clean
233 # Or running the cleanup ahead of the new deploy
234 - community.general.deploy_helper:
235 path: /path/to/root
236 state: clean
237 - community.general.deploy_helper:
238 path: /path/to/root
239 state: present
240
241 # Keeping more old releases:
242 - community.general.deploy_helper:
243 path: /path/to/root
244 release: '{{ deploy_helper.new_release }}'
245 state: finalize
246 keep_releases: 10
247 # Or, if you use 'clean=false' on finalize:
248 - community.general.deploy_helper:
249 path: /path/to/root
250 state: clean
251 keep_releases: 10
252
253 # Removing the entire project root folder
254 - community.general.deploy_helper:
255 path: /path/to/root
256 state: absent
257
258 # Debugging the facts returned by the module
259 - community.general.deploy_helper:
260 path: /path/to/root
261 - ansible.builtin.debug:
262 var: deploy_helper
263 """
264
265 import os
266 import shutil
267 import time
268 import traceback
269
270 from ansible.module_utils.basic import AnsibleModule
271
272
273 class DeployHelper:
274 def __init__(self, module):
275 self.module = module
276 self.file_args = module.load_file_common_arguments(module.params)
277
278 self.clean = module.params["clean"]
279 self.current_path = module.params["current_path"]
280 self.keep_releases = module.params["keep_releases"]
281 self.path = module.params["path"]
282 self.release = module.params["release"]
283 self.releases_path = module.params["releases_path"]
284 self.shared_path = module.params["shared_path"]
285 self.state = module.params["state"]
286 self.unfinished_filename = module.params["unfinished_filename"]
287
288 def gather_facts(self):
289 current_path = os.path.join(self.path, self.current_path)
290 releases_path = os.path.join(self.path, self.releases_path)
291 if self.shared_path:
292 shared_path = os.path.join(self.path, self.shared_path)
293 else:
294 shared_path = None
295
296 previous_release, previous_release_path = self._get_last_release(current_path)
297
298 if not self.release and (self.state == "query" or self.state == "present"):
299 self.release = time.strftime("%Y%m%d%H%M%S")
300
301 if self.release:
302 new_release_path = os.path.join(releases_path, self.release)
303 else:
304 new_release_path = None
305
306 return {
307 "project_path": self.path,
308 "current_path": current_path,
309 "releases_path": releases_path,
310 "shared_path": shared_path,
311 "previous_release": previous_release,
312 "previous_release_path": previous_release_path,
313 "new_release": self.release,
314 "new_release_path": new_release_path,
315 "unfinished_filename": self.unfinished_filename,
316 }
317
318 def delete_path(self, path):
319 if not os.path.lexists(path):
320 return False
321
322 if not os.path.isdir(path):
323 self.module.fail_json(msg=f"{path} exists but is not a directory")
324
325 if not self.module.check_mode:
326 try:
327 shutil.rmtree(path, ignore_errors=False)
328 except Exception as e:
329 self.module.fail_json(msg=f"rmtree failed: {e}", exception=traceback.format_exc())
330
331 return True
332
333 def create_path(self, path):
334 changed = False
335
336 if not os.path.lexists(path):
337 changed = True
338 if not self.module.check_mode:
339 os.makedirs(path)
340
341 elif not os.path.isdir(path):
342 self.module.fail_json(msg=f"{path} exists but is not a directory")
343
344 changed += self.module.set_directory_attributes_if_different(self._get_file_args(path), changed)
345
346 return changed
347
348 def check_link(self, path):
349 if os.path.lexists(path):
350 if not os.path.islink(path):
351 self.module.fail_json(msg=f"{path} exists but is not a symbolic link")
352
353 def create_link(self, source, link_name):
354 if os.path.islink(link_name):
355 norm_link = os.path.normpath(os.path.realpath(link_name))
356 norm_source = os.path.normpath(os.path.realpath(source))
357 if norm_link == norm_source:
358 changed = False
359 else:
360 changed = True
361 if not self.module.check_mode:
362 if not os.path.lexists(source):
363 self.module.fail_json(msg=f"the symlink target {source} doesn't exists")
364 tmp_link_name = f"{link_name}.{self.unfinished_filename}"
365 if os.path.islink(tmp_link_name):
366 os.unlink(tmp_link_name)
367 os.symlink(source, tmp_link_name)
368 os.rename(tmp_link_name, link_name)
369 else:
370 changed = True
371 if not self.module.check_mode:
372 os.symlink(source, link_name)
373
374 return changed
375
376 def remove_unfinished_file(self, new_release_path):
377 changed = False
378 unfinished_file_path = os.path.join(new_release_path, self.unfinished_filename)
379 if os.path.lexists(unfinished_file_path):
380 changed = True
381 if not self.module.check_mode:
382 os.remove(unfinished_file_path)
383
384 return changed
385
386 def remove_unfinished_builds(self, releases_path):
387 changes = 0
388
389 for release in os.listdir(releases_path):
390 if os.path.isfile(os.path.join(releases_path, release, self.unfinished_filename)):
391 if self.module.check_mode:
392 changes += 1
393 else:
394 changes += self.delete_path(os.path.join(releases_path, release))
395
396 return changes
397
398 def remove_unfinished_link(self, path):
399 changed = False
400
401 if not self.release:
402 return changed
403
404 tmp_link_name = os.path.join(path, f"{self.release}.{self.unfinished_filename}")
405 if not self.module.check_mode and os.path.exists(tmp_link_name):
406 changed = True
407 os.remove(tmp_link_name)
408
409 return changed
410
411 def cleanup(self, releases_path, reserve_version):
412 changes = 0
413
414 if os.path.lexists(releases_path):
415 releases = [f for f in os.listdir(releases_path) if os.path.isdir(os.path.join(releases_path, f))]
416 try:
417 releases.remove(reserve_version)
418 except ValueError:
419 pass
420
421 if not self.module.check_mode:
422 releases.sort(key=lambda x: os.path.getctime(os.path.join(releases_path, x)), reverse=True)
423 for release in releases[self.keep_releases :]:
424 changes += self.delete_path(os.path.join(releases_path, release))
425 elif len(releases) > self.keep_releases:
426 changes += len(releases) - self.keep_releases
427
428 return changes
429
430 def _get_file_args(self, path):
431 file_args = self.file_args.copy()
432 file_args["path"] = path
433 return file_args
434
435 def _get_last_release(self, current_path):
436 previous_release = None
437 previous_release_path = None
438
439 if os.path.lexists(current_path):
440 previous_release_path = os.path.realpath(current_path)
441 previous_release = os.path.basename(previous_release_path)
442
443 return previous_release, previous_release_path
444
445
446 def main():
447 module = AnsibleModule(
448 argument_spec=dict(
449 path=dict(aliases=["dest"], required=True, type="path"),
450 release=dict(type="str"),
451 releases_path=dict(type="str", default="releases"),
452 shared_path=dict(type="path", default="shared"),
453 current_path=dict(type="path", default="current"),
454 keep_releases=dict(type="int", default=5),
455 clean=dict(type="bool", default=True),
456 unfinished_filename=dict(type="str", default="DEPLOY_UNFINISHED"),
457 state=dict(choices=["present", "absent", "clean", "finalize", "query"], default="present"),
458 ),
459 required_if=[
460 ("state", "finalize", ["release"]),
461 ],
462 add_file_common_args=True,
463 supports_check_mode=True,
464 )
465
466 deploy_helper = DeployHelper(module)
467 facts = deploy_helper.gather_facts()
468
469 result = {"state": deploy_helper.state}
470
471 changes = 0
472
473 if deploy_helper.state == "query":
474 result["ansible_facts"] = {"deploy_helper": facts}
475
476 elif deploy_helper.state == "present":
477 deploy_helper.check_link(facts["current_path"])
478 changes += deploy_helper.create_path(facts["project_path"])
479 changes += deploy_helper.create_path(facts["releases_path"])
480 if deploy_helper.shared_path:
481 changes += deploy_helper.create_path(facts["shared_path"])
482
483 result["ansible_facts"] = {"deploy_helper": facts}
484
485 elif deploy_helper.state == "finalize":
486 if deploy_helper.keep_releases <= 0:
487 module.fail_json(msg="'keep_releases' should be at least 1")
488
489 changes += deploy_helper.remove_unfinished_file(facts["new_release_path"])
490 changes += deploy_helper.create_link(facts["new_release_path"], facts["current_path"])
491 if deploy_helper.clean:
492 changes += deploy_helper.remove_unfinished_link(facts["project_path"])
493 changes += deploy_helper.remove_unfinished_builds(facts["releases_path"])
494 changes += deploy_helper.cleanup(facts["releases_path"], facts["new_release"])
495
496 elif deploy_helper.state == "clean":
497 changes += deploy_helper.remove_unfinished_link(facts["project_path"])
498 changes += deploy_helper.remove_unfinished_builds(facts["releases_path"])
499 changes += deploy_helper.cleanup(facts["releases_path"], facts["new_release"])
500
501 elif deploy_helper.state == "absent":
502 # destroy the facts
503 result["ansible_facts"] = {"deploy_helper": []}
504 changes += deploy_helper.delete_path(facts["project_path"])
505
506 if changes > 0:
507 result["changed"] = True
508 else:
509 result["changed"] = False
510
511 module.exit_json(**result)
512
513
514 if __name__ == "__main__":
515 main()