Created
May 3, 2026 18:20
-
-
Save stivio00/a8d305bb6b145fa0d2ab8ea25c666d7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import subprocess | |
| import argparse | |
| from pathlib import Path | |
| PORT = 2376 | |
| def run(cmd: list, dry_run: bool): | |
| if dry_run: | |
| print(f" [dry-run] {' '.join(cmd)}") | |
| return | |
| result = subprocess.run(cmd, capture_output=True, text=True) | |
| print(f" ✓" if result.returncode == 0 else f" ✗ {result.stderr.strip()}") | |
| def cmd_create(args): | |
| for folder in sorted(Path(args.certs_dir).iterdir()): | |
| if not folder.is_dir(): | |
| continue | |
| name = folder.name | |
| spec = (f"host=tcp://{name}:{PORT}," | |
| f"ca={folder}/ca.pem," | |
| f"cert={folder}/cert.pem," | |
| f"key={folder}/key.pem") | |
| print(f"→ {name}") | |
| run(["docker", "context", "create", name, "--docker", spec], args.dry_run) | |
| def cmd_delete(args): | |
| if not args.yes: | |
| confirm = input("Delete all non-default contexts? [y/N] ") | |
| if confirm.lower() != "y": | |
| print("aborted") | |
| return | |
| contexts = subprocess.run( | |
| ["docker", "context", "ls", "--format", "{{.Name}}"], | |
| capture_output=True, text=True | |
| ).stdout.strip().splitlines() | |
| for ctx in contexts: | |
| if ctx == "default": | |
| continue | |
| print(f"→ deleting {ctx}") | |
| run(["docker", "context", "rm", "-f", ctx], args.dry_run) | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Docker context manager from cert folders") | |
| parser.add_argument("--dry-run", action="store_true", help="Preview without executing") | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| # create | |
| p_create = sub.add_parser("create", help="Create a context for each server folder") | |
| p_create.add_argument("--certs-dir", required=True, help="Folder containing server cert subdirs") | |
| # delete | |
| p_delete = sub.add_parser("delete", help="Delete all contexts except default") | |
| p_delete.add_argument("-y", "--yes", action="store_true", help="Skip confirmation") | |
| args = parser.parse_args() | |
| if args.command == "create": | |
| cmd_create(args) | |
| elif args.command == "delete": | |
| cmd_delete(args) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment