edd-tool 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
edd_tool/__init__.py ADDED
File without changes
edd_tool/cli.py ADDED
@@ -0,0 +1,302 @@
1
+ import argparse
2
+ import subprocess
3
+ import sys
4
+ import tempfile
5
+ import shutil
6
+ import json
7
+ import logging
8
+ import os
9
+ import pprint
10
+ from contextlib import contextmanager
11
+ from pathlib import Path
12
+
13
+ from ansible.parsing.dataloader import DataLoader
14
+ from ansible.inventory.manager import InventoryManager
15
+ from ansible.vars.manager import VariableManager
16
+ from ansible.template import Templar
17
+ from ansible.parsing.vault import VaultSecret, VaultSecretsContext
18
+
19
+ logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
20
+ logger = logging.getLogger("edd-installer")
21
+
22
+
23
+ @contextmanager
24
+ def working_directory(path):
25
+ """Temporarily change the working directory inside the context."""
26
+ original_dir = os.getcwd()
27
+ try:
28
+ os.chdir(path)
29
+ yield
30
+ finally:
31
+ os.chdir(original_dir)
32
+
33
+
34
+ def run_cmd(cmd, cwd=None, check=True, env=None):
35
+ """
36
+ Run a subprocess command.
37
+
38
+ Args:
39
+ cmd (list[str]): Command and arguments
40
+ cwd (str|Path, optional): Directory to run command in
41
+ check (bool): Exit on non-zero return code
42
+
43
+ Returns:
44
+ str: stdout of the command
45
+ """
46
+ logger.debug(f"Running command: {' '.join(cmd)}")
47
+ result = subprocess.run(cmd, cwd=cwd, capture_output=False, text=True, check=False, env=env)
48
+ if result.returncode != 0 and check:
49
+ logger.error(f"Command failed: {' '.join(cmd)}")
50
+ sys.exit(result.returncode)
51
+
52
+
53
+ def default_deployment_dir(args):
54
+ """
55
+ Compute the default deployment directory for a project/version/inventory combination.
56
+
57
+ Args:
58
+ args (Namespace): Parsed argparse arguments with project, version, inventory
59
+
60
+ Returns:
61
+ Path: Absolute path for deployment directory
62
+ """
63
+ project = args.project.split("/")[-1].replace(".git", "")
64
+ path = Path.home() / ".edd" / "deployments" / project / str(args.version) / args.inventory
65
+ return path
66
+
67
+
68
+ def create_deployment_dir(path, force=False):
69
+ """
70
+ Create a deployment directory, optionally clearing it if it exists and is not empty.
71
+
72
+ Args:
73
+ path (str|Path): Path to create
74
+ force (bool): If True, remove contents if directory exists
75
+
76
+ Returns:
77
+ Path: Absolute path of the deployment directory
78
+ """
79
+ path = Path(path).absolute()
80
+ if path.exists():
81
+ if any(path.iterdir()):
82
+ if not force:
83
+ raise RuntimeError(f"Deployment directory {path} already exists and is not empty. Use --force to override.")
84
+ logger.warning(f"Deployment directory {path} exists and is not empty. Force enabled, clearing contents.")
85
+ for item in path.iterdir():
86
+ if item.is_dir():
87
+ shutil.rmtree(item)
88
+ else:
89
+ item.unlink()
90
+ else:
91
+ path.mkdir(parents=True, exist_ok=True)
92
+ logger.info(f"Deployment directory ready: {path}")
93
+ return path
94
+
95
+
96
+ def clone_or_copy_project(project_path, deploy_dir, branch=None):
97
+ """
98
+ Clone a git repository into the deployment directory.
99
+
100
+ Args:
101
+ project_path (str): Git URL of the project
102
+ deploy_dir (str|Path): Deployment directory
103
+ branch (str, optional): Branch or tag to checkout
104
+ """
105
+ logger.info(f"Cloning repository from {project_path} into {deploy_dir}")
106
+ if branch:
107
+ run_cmd(["git", "clone", "--single-branch", "--depth", "1", "--branch",
108
+ branch, project_path, str(deploy_dir)])
109
+ else:
110
+ run_cmd(["git", "clone", "--single-branch", "--depth", "1", project_path, str(deploy_dir)])
111
+
112
+
113
+ def parse_inventory(inventory_source, vault_pass_file=None):
114
+ """
115
+ Parse the Ansible inventory and extract variables and EDD_PLUGINS,
116
+ resolving Jinja2 templates and decrypting vault-encrypted variables.
117
+
118
+ Args:
119
+ inventory_source (str): Path to inventory (file, directory, or script)
120
+ vault_pass_file (str, optional): Path to Ansible vault password file
121
+
122
+ Returns:
123
+ tuple: (all_vars: dict of merged variables, plugins: list of plugin dicts)
124
+ """
125
+ loader = DataLoader()
126
+
127
+ vault_secret = None
128
+ if vault_pass_file:
129
+ with open(vault_pass_file, "rb") as f:
130
+ vault_secret = VaultSecret(f.read().strip())
131
+
132
+ if vault_secret:
133
+ VaultSecretsContext.initialize(VaultSecretsContext([("default", vault_secret)]))
134
+
135
+ inventory = InventoryManager(loader=loader, sources=[inventory_source])
136
+ variable_manager = VariableManager(loader=loader, inventory=inventory)
137
+
138
+ all_vars = {}
139
+ all_plugins = []
140
+
141
+ for host in inventory.get_hosts():
142
+ host_vars = variable_manager.get_vars(host=host)
143
+ templar = Templar(loader=loader, variables=host_vars)
144
+
145
+ resolved_vars = {k: templar.template(v) if isinstance(v, str) else v
146
+ for k, v in host_vars.items()}
147
+ all_vars.update(resolved_vars)
148
+
149
+ if "EDD_PLUGINS" in resolved_vars:
150
+ rendered_plugins = []
151
+ for plugin in resolved_vars["EDD_PLUGINS"]:
152
+ rendered_plugins.append({k: templar.template(v) if isinstance(v, str) else v
153
+ for k, v in plugin.items()})
154
+ all_plugins.extend(rendered_plugins)
155
+
156
+ # Deduplicate plugins by JSON-serialized content
157
+ deduped_plugins = list({json.dumps(p, sort_keys=True): p for p in all_plugins}.values())
158
+ logger.info(f"Found {len(deduped_plugins)} plugins after templating and decryption")
159
+ return all_vars, deduped_plugins
160
+
161
+
162
+ def display_vars(vars_dict):
163
+ """
164
+ Pretty-print a dictionary of variables.
165
+
166
+ Args:
167
+ vars_dict (dict): Dictionary of variables
168
+ """
169
+ logger.info(pprint.pformat(vars_dict, indent=2))
170
+
171
+
172
+ def install_plugins(plugins, method="galaxy"):
173
+ """
174
+ Install plugins using the specified method.
175
+
176
+ Args:
177
+ plugins (list[dict]): List of plugin dictionaries
178
+ method (str): "galaxy" or "git"
179
+ """
180
+ if not plugins:
181
+ logger.info("No plugins to install.")
182
+ return
183
+
184
+ if method == "galaxy":
185
+ req_file = tempfile.NamedTemporaryFile(delete=False, mode="w", suffix=".yml")
186
+ req_file.write("collections:\n")
187
+ for p in plugins:
188
+ req_file.write(f" - type: git\n source: {p['source']}\n version: \"{p['version']}\"\n")
189
+ req_file.close()
190
+ run_cmd(["ansible-galaxy", "collection", "install", "-r", req_file.name, "-p", "./ansible_collections/"])
191
+ elif method == "git-submodule":
192
+ run_cmd(["git", "submodule", "update", "--init", "--recursive"])
193
+ run_cmd(["git", "submodule", "update", "--remote", "--recursive"])
194
+ else:
195
+ raise NotImplementedError(f"Plugin install method '{method}' is unsupported")
196
+
197
+
198
+ def run_playbook(inventory, vault_pass_file, site_config, tags=None, dry_run=False):
199
+ """
200
+ Run an Ansible playbook.
201
+
202
+ Args:
203
+ inventory (str): Inventory path
204
+ vault_pass_file (str): Vault password file
205
+ site_config (str): Playbook YAML file
206
+ tags (str, optional): Tags to limit execution
207
+ dry_run (bool): If True, log the command instead of running
208
+ """
209
+ collections = (Path().cwd() / "ansible_collections").absolute()
210
+ env = os.environ.copy()
211
+ env['ANSIBLE_COLLECTIONS_PATH'] = str(collections)
212
+ cmd = ["ansible-playbook", "-i", inventory, "--vault-password-file", vault_pass_file, site_config]
213
+ if tags:
214
+ cmd.extend(["--tags", tags])
215
+ if dry_run:
216
+ logger.info("Would run: %s", " ".join(cmd))
217
+ else:
218
+ run_cmd(cmd, env=env)
219
+
220
+
221
+ def cmd_install(args):
222
+ """
223
+ Main install/deploy command handler.
224
+
225
+ Args:
226
+ args (Namespace): Parsed command-line arguments
227
+ """
228
+ deploy_dir = args.deploy_dir or default_deployment_dir(args)
229
+ logger.info("Creating deployment directory: %s", deploy_dir)
230
+ deploy_dir = create_deployment_dir(deploy_dir, force=args.force)
231
+ vault_pass_file = str(Path(args.vault_pass_file).absolute())
232
+
233
+ with working_directory(deploy_dir):
234
+ logger.info("Cloning site repository: %s (version: %s)", args.project, args.version)
235
+ clone_or_copy_project(args.project, "./", branch=args.version)
236
+ logger.info("Parsing ansible inventory")
237
+ vars_dict, plugins = parse_inventory(args.inventory, vault_pass_file)
238
+ display_vars(vars_dict)
239
+
240
+ if not args.dry_run:
241
+ logger.info("Installing plugins")
242
+ install_plugins(plugins, method=args.plugin_install_method)
243
+ else:
244
+ for plugin in plugins:
245
+ logger.info("Would install plugin: %s", plugin)
246
+
247
+ if not args.no_pullremote:
248
+ logger.info("Pulling docker images")
249
+ run_playbook(args.inventory, vault_pass_file, args.site_config,
250
+ tags="pullremote", dry_run=args.dry_run)
251
+ logger.info("Running deployment")
252
+ run_playbook(args.inventory, vault_pass_file, args.site_config, dry_run=args.dry_run)
253
+ logger.info("Deployment finished")
254
+
255
+
256
+ def main():
257
+ """Command-line entry point for the EDD installer."""
258
+ # Create a parent parser for global arguments
259
+ parent_parser = argparse.ArgumentParser(add_help=False)
260
+ parent_parser.add_argument(
261
+ "--log-level",
262
+ default="INFO",
263
+ choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
264
+ help="Set the logging level (default: INFO)"
265
+ )
266
+
267
+ parser = argparse.ArgumentParser(prog="edd-tool", description="EDD Installer Tool")
268
+ subparsers = parser.add_subparsers(dest="command", required=True)
269
+
270
+ # Attach the parent parser to all subparsers
271
+ sp_install = subparsers.add_parser(
272
+ "deploy",
273
+ help="Install and deploy project",
274
+ parents=[parent_parser]
275
+ )
276
+ sp_install.add_argument("project", help="Git URL of the EDD site repository")
277
+ sp_install.add_argument("--version", default=None, help="Branch or tag for the site repository")
278
+ sp_install.add_argument("--deploy-dir", default=None, help="Deployment directory")
279
+ sp_install.add_argument("--inventory", required=True, help="Ansible inventory path (file, dir, or script)")
280
+ sp_install.add_argument("--vault-pass-file", required=True, help="Path to vault password file")
281
+ sp_install.add_argument("--site-config", required=True, help="Path to site configuration YAML")
282
+ sp_install.add_argument("--plugin-install-method", choices=["galaxy", "git-submodule"], default="galaxy")
283
+ sp_install.add_argument("--no-pullremote", action="store_true", help="Skip pullremote tag")
284
+ sp_install.add_argument("--force", action="store_true", help="Force overwrite of deployment directory")
285
+ sp_install.add_argument("--dry-run", action="store_true", help="Dry run the deployment")
286
+ sp_install.set_defaults(func=cmd_install)
287
+
288
+ args = parser.parse_args()
289
+
290
+ # Set log level after parsing
291
+ numeric_level = getattr(logging, args.log_level.upper(), logging.INFO)
292
+ logger.setLevel(numeric_level)
293
+ logging.getLogger().setLevel(numeric_level)
294
+ logger.debug("Log level set to %s", args.log_level)
295
+
296
+ args.func(args)
297
+
298
+
299
+
300
+
301
+ if __name__ == "__main__":
302
+ main()
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: edd-tool
3
+ Version: 0.1.0
4
+ Summary: EDD deployment and plugin management tool
5
+ Author-email: Ewan Barr <ebarr@mpifr-bonn.mpg.de>
6
+ License: Copyright 2025 Ewan Barr
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13
+
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: ansible-core<2.20,>=2.14
18
+ Dynamic: license-file
@@ -0,0 +1,8 @@
1
+ edd_tool/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ edd_tool/cli.py,sha256=1eb0wBVbKIZ05kjLUN1ZB3SOFsUXbZJU-C7G-n2MmGU,11047
3
+ edd_tool-0.1.0.dist-info/licenses/LICENSE,sha256=cmmlTITnsaoRWAVgsvzj5r2hvIafltab2AGeyb4_mK0,1057
4
+ edd_tool-0.1.0.dist-info/METADATA,sha256=Vo3siuw-SVgNl3bTz08NL5DiL9WWcbNRqMkw7_K0mFg,1423
5
+ edd_tool-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ edd_tool-0.1.0.dist-info/entry_points.txt,sha256=TXV2JiMOb_bstG2wV_cHfMCkqb8rIjF6MsmY2nloS8o,47
7
+ edd_tool-0.1.0.dist-info/top_level.txt,sha256=faIgh5poOJJJW8uGTlqckI0FXNz4T8q1Mr_hFB6fYKk,9
8
+ edd_tool-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ edd-tool = edd_tool.cli:main
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Ewan Barr
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ edd_tool