Skip to content

Instantly share code, notes, and snippets.

@stivio00
Created September 18, 2025 16:24
Show Gist options
  • Select an option

  • Save stivio00/96fe6383b89639fa54bbda2ac2884fd9 to your computer and use it in GitHub Desktop.

Select an option

Save stivio00/96fe6383b89639fa54bbda2ac2884fd9 to your computer and use it in GitHub Desktop.
Docker context import script
from pathlib import Path
import subprocess
import click
import os
import sys
REQUIRED_FILES = ["cert.pem", "ca.pem", "key.pem"]
def get_user_data_dir(app_name: str) -> Path:
"""
Return a cross-platform directory for storing user-specific application data.
"""
if sys.platform == "win32":
base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
elif sys.platform == "darwin":
base = Path.home() / "Library" / "Application Support"
else:
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
return base / app_name
@click.command()
@click.argument(
"root_dir",
type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path)
)
def main(root_dir: Path):
"""
Create Docker contexts for hosts under ROOT_DIR using TLS certificates.
Copies certificates into a user-data directory for safe reference.
"""
click.echo(f"Scanning root directory: {root_dir}")
local_base_dir = get_user_data_dir("docker_contexts")
local_base_dir.mkdir(parents=True, exist_ok=True)
for host_path in root_dir.iterdir():
if not host_path.is_dir():
continue # skip files
host_name = host_path.name
# Validate required files
missing = [f for f in REQUIRED_FILES if not (host_path / f).is_file()]
if missing:
click.secho(f"Skipping {host_name}, missing files: {', '.join(missing)}", fg="red")
continue
# Copy certificates to user-data directory
local_host_dir = local_base_dir / host_name
local_host_dir.mkdir(parents=True, exist_ok=True)
for f in REQUIRED_FILES:
src_file = host_path / f
dst_file = local_host_dir / f
dst_file.write_bytes(src_file.read_bytes())
# Build docker context create command
ca = local_host_dir / "ca.pem"
cert = local_host_dir / "cert.pem"
key = local_host_dir / "key.pem"
cmd = [
"docker", "context", "create", host_name,
"--docker",
f"host=tcp://{host_name}:2376,ca={ca},cert={cert},key={key}"
]
click.secho(f"Creating Docker context for host: {host_name}", fg="green")
try:
subprocess.run(cmd, check=True)
click.secho(f"Context {host_name} created successfully ✅", fg="green")
except subprocess.CalledProcessError as e:
click.secho(f"Failed to create context for {host_name}: {e}", fg="red")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment