:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devbox): clone command (#66138)
Raúl Negrón-Otero49831c9e8271
diff --git a/hogli.yaml b/hogli.yamlindex 32963d34108a..e40d7b356d55 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -144,6 +144,9 @@ devbox:devbox:start:click: hogli_commands.devbox.cli:devbox_startdescription: Start or create your remote devbox+ devbox:clone:+ click: hogli_commands.devbox.cli:devbox_clone+ description: Clone a running devbox into a new one (carries full disk state)devbox:stop:click: hogli_commands.devbox.cli:devbox_stopdescription: Stop your devbox (preserves disk, stops billing)diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex e2d076f28cfa..531852292432 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -35,10 +35,12 @@ from .coder import (_diagnose_unreachable_coder,_fail,_start_app_param,+ clone_workspace,coder_authenticated,coder_installed,coder_reachable,coder_ssh_alias_configured,+ create_clone_image,create_task,create_workspace,delete_user_secret,@@ -56,6 +58,7 @@ from .coder import (get_default_git_identity,get_shared_users,get_sharing_status,+ get_username,get_workspace,get_workspace_name,get_workspace_region,@@ -1394,6 +1397,75 @@ def devbox_start(_print_connection_info(name)+ name="devbox:clone",+ help="Clone a running devbox into a new one, carrying its full disk state",+)+@workspace_argument+ "--as",+ "new_label",+ default="clone",+ show_default=True,+ help="Label for the new devbox (becomes devbox-<you>-<label>)",+)[email protected]("-y", "--yes", is_flag=True, help="Skip the confirmation prompt")[email protected]("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")+def devbox_clone(workspace: str | None, new_label: str, yes: bool, verbose: bool) -> None:+ """Duplicate a running devbox, disk and all.++ Captures the source box's root volume into a private, short-lived AMI and+ boots a new devbox from it, so the clone comes up with the source's full+ disk state -- uncommitted work, local databases, installed tooling -- not+ just the settings that dotfiles and user secrets already carry. The source+ must be running; quiesce its dev stack first for an application-consistent+ copy. The capture image is private to you and auto-expires.+ """+ ensure_runtime_ready()+ source_name, workspaces = resolve_workspace_name(workspace)+ ws = _get_workspace_or_fail(source_name, workspaces)++ owner = get_username()+ if str(ws.get("owner_name") or "").lower() not in ("", owner):+ _fail("You can only clone your own devbox.")++ template = ws.get("template_name") or DEFAULT_TEMPLATE+ if template != DEFAULT_TEMPLATE:+ _fail(f"Clone supports the '{DEFAULT_TEMPLATE}' template only (this devbox uses '{template}').")++ region = region_from_workspace_name(source_name)+ if region != DEFAULT_REGION:+ _fail("Clone is us-east-1 only for now (an AMI is region-scoped). EU clone is not wired yet.")++ status = get_workspace_status(ws)+ if status != "running":+ suffix = _workspace_arg_suffix(source_name)+ _fail(+ f"The source devbox must be running to clone it (status: {status}). Start it: `hogli devbox:start{suffix}`."+ )++ target_name = get_workspace_name(new_label, region=region)+ if get_workspace(target_name, workspaces) is not None:+ _fail(f"A devbox named '{target_name}' already exists. Pass `--as <label>` to pick another name.")++ if not yes:+ click.echo(f"Clone '{source_name}' -> '{target_name}'.")+ click.echo(+ "This images the source box's entire disk (including any on-disk secrets) into a\n"+ "private AMI and boots the new box from it. The image auto-expires after a few days."+ )+ if not click.confirm("Proceed?"):+ click.echo("Cancelled.")+ return++ click.echo("Capturing a clone image from the source devbox (this takes a few minutes)...")+ ami = create_clone_image(source_name, owner=owner, source_label=source_name)+ click.echo(f"Captured {ami}. Creating '{target_name}'...")+ clone_workspace(source_name, target_name, base_ami=ami, template=template, verbose=verbose)+ click.echo("Cloned.")+ _print_connection_info(target_name)++@click.command(name="devbox:stop", help="Stop your devbox (preserves disk, stops billing)")@workspace_argument@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.pyindex ffcefd5b5d3c..489e4e8d0cf8 100644--- a/tools/hogli-commands/hogli_commands/devbox/coder.py+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py@@ -12,6 +12,7 @@ import csvimport sysimport jsonimport shlex+import base64import shutilimport socketimport functools@@ -69,6 +70,12 @@ AUTO_START_APP_PARAMETER = "auto_start_app"WORKSPACE_REGION_PARAMETER = "workspace_region"REGIONS = ("us-east-1", "eu-central-1")DEFAULT_REGION = REGIONS[0]++# Immutable, create-time AMI override consumed by `devbox:clone`. A clone boots+# the new box from a per-clone image captured off the source box's root volume,+# so the duplicate comes up with that box's full disk state instead of a blank+# golden AMI. Empty everywhere else.+BASE_AMI_PARAMETER = "base_ami"# Key of the workspace metadata item the template publishes the region back as.REGION_METADATA_KEY = "region"# Workspace-name suffix per region. us-east-1 is the historical default and@@ -1233,6 +1240,159 @@ def create_workspace(raise SystemExit(result.returncode)+# Imaging a tens-of-GiB root volume to an AMI takes a few minutes; allow ample+# headroom (includes a possible one-time AWS CLI install on older golden AMIs).+CLONE_IMAGE_TIMEOUT = 1800++# Tag values ride into the AWS CLI tag shorthand; keep them to a safe charset so+# neither the shorthand parser nor the IAM tag conditions can be subverted.+_CLONE_TAG_VALUE_RE = re.compile(r"^[A-Za-z0-9._-]+$")+_CLONE_READY_RE = re.compile(r"^CLONE_READY=(ami-[0-9a-f]+)$", re.MULTILINE)++# Runs ON the source devbox (over its ssh alias) and images the box's own root+# volume into a private, tagged AMI the clone boots from. The box authenticates+# with its instance profile, so no human AWS credentials are involved. The AWS+# CLI is installed on demand for golden AMIs that predate it. --no-reboot keeps+# this box running (the clone is driven from a live ssh session) at the cost of+# a crash-consistent (not application-consistent) image -- quiesce the dev stack+# first for the latter. __OWNER__/__SOURCE__ are substituted with shell-quoted,+# validated values before transport.+_CLONE_IMAGE_SCRIPT = """#!/usr/bin/env bash+set -euo pipefail++OWNER=__OWNER__+SOURCE=__SOURCE__++if ! command -v aws >/dev/null 2>&1; then+ echo "clone: installing AWS CLI on the devbox (one-time)..." >&2+ sudo apt-get update -qq >/dev/null 2>&1 || true+ sudo apt-get install -y -qq unzip >/dev/null 2>&1 || true+ curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o /tmp/awscliv2.zip+ (cd /tmp && unzip -q -o awscliv2.zip && sudo ./aws/install --update)+ rm -rf /tmp/awscliv2.zip /tmp/aws+fi++TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 120")+IID=$(curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)+REGION=$(curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/region)++CREATED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)+NAME="posthog-devbox-clone-${OWNER}-$(date +%s)"+TAGS="{Key=Coder_CloneArtifact,Value=true},{Key=Coder_CloneOwner,Value=${OWNER}},{Key=Coder_CloneSource,Value=${SOURCE}},{Key=Coder_CloneCreatedAt,Value=${CREATED_AT}}"++# Flush dirty pages so the crash-consistent snapshot is as clean as possible.+sync++AMI=$(aws ec2 create-image --region "$REGION" --instance-id "$IID" --no-reboot --name "$NAME" --description "devbox clone of ${SOURCE} for ${OWNER}" --tag-specifications "ResourceType=image,Tags=[${TAGS},{Key=Name,Value=${NAME}}]" "ResourceType=snapshot,Tags=[${TAGS}]" --query ImageId --output text)++echo "CLONE_AMI=${AMI}"+echo "clone: baking ${AMI}; waiting for it to become available..." >&2+aws ec2 wait image-available --region "$REGION" --image-ids "$AMI"+echo "CLONE_READY=${AMI}"+"""+++def _parse_clone_ami(output: str) -> str | None:+ """Pull the AMI id out of the remote clone script's CLONE_READY line."""+ match = _CLONE_READY_RE.search(output)+ return match.group(1) if match else None+++def create_clone_image(+ workspace_name: str,+ *,+ owner: str,+ source_label: str,+ timeout: int = CLONE_IMAGE_TIMEOUT,+) -> str:+ """Capture the source devbox's root volume into a tagged AMI; return its id.++ Runs on the box itself over the ssh alias so the capture uses the+ instance's own profile -- no human AWS credentials. Blocks until the image+ is ``available`` (a fresh root-volume snapshot of tens of GiB takes a few+ minutes), then returns the AMI id for :func:`clone_workspace` to boot from.+ The image is private and reaped by the cloud-infra clone reaper.+ """+ if not coder_ssh_alias_configured(workspace_name):+ _fail(f"ssh alias for '{workspace_name}' is not configured. {RUNTIME_SETUP_HINT}")+ for value, what in ((owner, "owner"), (source_label, "source")):+ if not _CLONE_TAG_VALUE_RE.match(value):+ _fail(f"Refusing to clone: {what} '{value}' has characters unsafe for an AWS tag.")++ script = _CLONE_IMAGE_SCRIPT.replace("__OWNER__", shlex.quote(owner)).replace(+ "__SOURCE__", shlex.quote(source_label)+ )+ encoded = base64.b64encode(script.encode()).decode()+ try:+ result = subprocess.run(+ ["ssh", _ssh_host_alias(workspace_name), f"echo {encoded} | base64 -d | bash"],+ capture_output=True,+ text=True,+ timeout=timeout,+ )+ except subprocess.TimeoutExpired:+ _fail(f"Timed out after {timeout}s waiting for the clone image to build.")++ if result.returncode != 0:+ sys.stderr.write(result.stderr)+ _fail("Failed to capture a clone image from the source devbox.")++ ami = _parse_clone_ami(result.stdout)+ if ami is None:+ sys.stderr.write(result.stdout)+ sys.stderr.write(result.stderr)+ _fail("Clone image build did not report an AMI id.")+ return ami+++def clone_workspace(+ source: str,+ target: str,+ *,+ base_ami: str,+ template: str = DEFAULT_TEMPLATE,+ verbose: bool = False,+) -> None:+ """Create ``target`` as a copy of ``source``, booting from the clone AMI.++ ``--copy-parameters-from`` carries the source's parameter values (disk+ size, region, git identity, ...) so the duplicate matches it; the explicit+ ``base_ami`` override points the new box at the captured image.++ Unlike create/update, this does NOT go through the param-retry shim: that+ path silently drops a parameter the template does not declare, which for a+ clone would boot the golden AMI and present a blank box as a successful+ clone. If ``base_ami`` is rejected, the template predates the clone change+ and we fail loudly instead.+ """+ # --preset none is required: newer Coder shows an interactive preset picker+ # that --yes does not bypass, which would hang clone_workspace. The source's+ # own parameters arrive via --copy-parameters-from, so no preset is wanted.+ args = _append_parameter_flags(+ [+ "coder",+ "create",+ target,+ "--template",+ template,+ "--preset",+ NO_PRESET,+ "--copy-parameters-from",+ source,+ "--yes",+ ],+ {BASE_AMI_PARAMETER: base_ami},+ )+ result = _run_build(args, verbose=verbose)+ if result.returncode != 0:+ if _PARAM_NOT_PRESENT_RE.search(result.stdout or ""):+ _fail(+ f"This Coder template does not accept '{BASE_AMI_PARAMETER}', so it cannot be "+ "cloned. Deploy the cloud-infra devbox-clone template change first."+ )+ raise SystemExit(result.returncode)++def start_workspace(name: str, *, verbose: bool = False) -> None:"""Start a stopped workspace."""result = _run_build(["coder", "start", name, "--yes"], verbose=verbose)