Lost the only SSH key to dozens of Yandex Cloud VMs: how I got back in
Published: 2026-07-06
An admin leaves the company. Then it turns out that their key is the only one cloud-init ever wrote onto dozens of production VMs. There is no OS Login, no second key and no password that anyone remembers. There is only a password hash in an old secrets dump, and a hash does not turn back into a password. ssh says Permission denied (publickey). My first idea was to push a new key through instance metadata. It didn't work. My second idea was to attach the disk to another VM and fix it there. That didn't work either, for a different reason. Below is what did work, and how I turned it into automation for many machines, not just one.
Why the obvious fixes don't work
Everyone first tries to add a key with yc compute instance add-metadata --metadata-from-file ssh-keys=.... It works in maybe seventy percent of cases. If the VM was built from an image with a guest agent that keeps polling metadata, the key appears in authorized_keys within a minute. But VMs that were set up by hand with cloud-init user-data usually apply that block once, at first boot, and never read it again. On such a VM, ssh -vvv will happily offer the new key, and the server will reject it, because nothing on the server ever picked it up.
The second idea is to attach the disk to another VM, chroot into it and add a user. The idea is right. The direct way to do it is not:
$ yc compute instance detach-disk --name my-host --disk-id fhmxxxxxxxxxxxxxxxxx
ERROR: rpc error: code = InvalidArgument
desc = Request validation error: Can't detach boot disk
Yandex Cloud does not let you detach a boot disk, even when the instance is stopped. This is a platform rule, not a CLI bug. So the fix has to work on a copy of the disk, not on the disk itself.
What works: a snapshot instead of the live disk
Stop the instance, take a snapshot of its boot disk and create a new disk from that snapshot. The new disk is not a boot disk for anyone yet, so you can attach it anywhere. Attach it as a secondary disk to a rescue VM, mount it, chroot into it and add a recovery user with a key and passwordless sudo. Then detach the disk and delete the old instance. Keep the old disk: it is your rollback. Finally, create the instance again on the fixed disk, with the same name and the same internal IP.
The original disk is never detached from anything. It is only read through a snapshot. The result is a new instance object with the same name and IP. Its disk is the same as the original, plus one new user.
Snapshot and the fixed disk
bashFOLDER_ID=b1xxxxxxxxxxxxxxxxxx
HOST=my-host
DISK_ID=$(yc compute instance get --name $HOST --folder-id $FOLDER_ID --full --format json \
| python3 -c "import json,sys;print(json.load(sys.stdin)['boot_disk']['disk_id'])")
yc compute instance stop --name $HOST --folder-id $FOLDER_ID
SNAP_ID=$(yc compute snapshot create --name ${HOST}-snap-final --disk-id $DISK_ID \
--folder-id $FOLDER_ID --format json | python3 -c "import json,sys;print(json.load(sys.stdin)['id'])")
Don't hardcode the size of the new disk. It must be at least as large as the source disk, and on real machines the disks have different sizes. I learned this the hard way, more on that below.
bashSRC_SIZE_GB=$(yc compute disk get --id $DISK_ID --folder-id $FOLDER_ID --format json \
| python3 -c "import json,sys;print(-(-int(json.load(sys.stdin)['size'])//1073741824))")
NEW_DISK=$(yc compute disk create --name ${HOST}-boot-fixed --source-snapshot-id $SNAP_ID \
--zone ru-central1-a --type network-hdd --size $SRC_SIZE_GB --folder-id $FOLDER_ID --format json \
| python3 -c "import json,sys;print(json.load(sys.stdin)['id'])")
Rescue VM, mount, recovery user
The rescue VM is a small VM in the same zone. It is never a recovery target itself, just a shell you trust:
bashyc compute instance attach-disk --name rescue-vm --disk-id $NEW_DISK --folder-id $FOLDER_ID
On the rescue VM:
bashmkdir -p /mnt/rescue
mount /dev/disk/by-id/virtio-${NEW_DISK}-part2 /mnt/rescue
mkdir -p /mnt/rescue/home/devops/.ssh
chroot /mnt/rescue useradd -m -s /bin/bash -G sudo devops 2>/dev/null || true
echo "ssh-ed25519 AAAA... devops" > /mnt/rescue/home/devops/.ssh/authorized_keys
chmod 700 /mnt/rescue/home/devops/.ssh
chmod 600 /mnt/rescue/home/devops/.ssh/authorized_keys
chroot /mnt/rescue chown -R devops:devops /home/devops
echo "devops ALL=(ALL) NOPASSWD:ALL" > /mnt/rescue/etc/sudoers.d/devops
umount /mnt/rescue
The path /dev/disk/by-id/virtio-${NEW_DISK}-part2 is not random. It protects against the race condition described in a later section.
Moving the instance to the fixed disk
bashADDR=$(yc compute instance get --name $HOST --folder-id $FOLDER_ID --format json \
| python3 -c "import json,sys;print(json.load(sys.stdin)['network_interfaces'][0]['primary_v4_address']['address'])")
SUBNET=$(yc compute instance get --name $HOST --folder-id $FOLDER_ID --format json \
| python3 -c "import json,sys;print(json.load(sys.stdin)['network_interfaces'][0]['subnet_id'])")
yc compute instance detach-disk --name rescue-vm --disk-id $NEW_DISK --folder-id $FOLDER_ID
yc compute instance delete --name $HOST --folder-id $FOLDER_ID
yc compute instance create --name $HOST --zone ru-central1-a \
--network-interface subnet-id=$SUBNET,address=$ADDR \
--use-boot-disk disk-id=$NEW_DISK,auto-delete=false \
--memory 4 --cores 4 --folder-id $FOLDER_ID
address=$ADDR keeps the same internal IP that the instance had before. DNS, configs of other services and firewall rules don't notice anything. Check it:
bashssh devops@$ADDR 'echo ok; sudo whoami'
On one machine this took about fifteen minutes, and most of that time I was waiting for a 100 GB snapshot. Then it turned out that there was more than one machine.
One lost key is rarely on one machine
I checked the other machines the same way I had found the cause of the original alert. I went through the metadata of every instance and looked for the departed admin's key in user-data. Out of 118 instances in the folder, 80 had it. Databases, queues, caches, a bastion host and, worst of all, the VPN gateways and routers, which are the network path to everything else.
Running the same script on all 80 at once is a bad idea, for two reasons. First, some of them are replicated clusters (Cassandra, RabbitMQ, etcd). If you take down more than one node at a time, you can lose quorum. Second, some of them are not Linux at all (router appliances) or are managed databases controlled by the cloud control plane. chroot doesn't apply there, and you should not try it.
I grouped the hosts not by service type, but by what breaks if something goes wrong:
yaml# inventory/hosts.yml
all:
children:
quorum_sensitive: # replicated clusters — strictly one node at a time
hosts:
db-node-01: {}
db-node-02: {}
db-node-03: {}
independent: # no cross-host dependency — safe in parallel
hosts:
cache-node-01: {}
bastion-01: {}
network_path: # this IS the path to everything else — manual, last
hosts:
vpn-gw-01: {}
router-01: {}
yaml- name: Recover access — quorum-sensitive
hosts: quorum_sensitive
serial: 1 # don't touch node N+1 until node N is back in the cluster
tasks:
- include_tasks: tasks/recover_one.yml
- name: wait for cluster health
command: ssh devops@{{ recovered_addr }} "cluster-status-check"
delegate_to: localhost
register: check
until: check.rc == 0
retries: 60
delay: 10
- name: Recover access — independent
hosts: independent
serial: "100%"
tasks:
- include_tasks: tasks/recover_one.yml
# network_path isn't referenced by any play. Those hosts get done one at a time,
# by hand, only after a fallback access path is confirmed working. Breaking your
# own VPN gateway mid-recovery cuts you off from everything else you're fixing.
Each task finds the zone, subnet, disk size and IP from the hostname at runtime, so the inventory only needs the name. This makes the blast radius easy to see: every host in the list will be touched, and the groups show exactly what is safe to run in parallel and what is not.
The race condition when one rescue VM serves a whole zone
When only one extra disk is attached to the rescue VM, you can find it with lsblk and take the last partition. This stops working at scale. I processed several hosts in the same zone together, with one shared rescue VM instead of dozens of new ones. Two attach-disk calls run at the same time, then two scripts both take "the last partition in lsblk", and they both get the same disk. The fix for one host ends up on another host's filesystem.
Yandex Cloud gives every attached disk a stable path based on the disk ID, no matter in which order the disks were attached:
bash$ ls -la /dev/disk/by-id/ | grep virtio
virtio-fhmlrpr6g54rfs0dal0p -> ../../vdb
virtio-fhmlrpr6g54rfs0dal0p-part1 -> ../../vdb1
virtio-fhmlrpr6g54rfs0dal0p-part2 -> ../../vdb2
This is where virtio-${NEW_DISK}-part2 in the mount step comes from. I didn't trust the docs on this: I attached a disk, looked at by-id, and the symlink was exactly where I expected it. The script for many hosts takes the largest partition under that ID (in practice, the root filesystem) and does not guess from lsblk:
bashBASE="/dev/disk/by-id/virtio-${NEW_DISK}"
for i in $(seq 1 15); do compgen -G "${BASE}*" >/dev/null 2>&1 && break; sleep 1; done
BEST=""; BEST_SIZE=0
for p in ${BASE}*; do
[ -e "$p" ] || continue
SZ=$(blockdev --getsize64 "$p" 2>/dev/null || echo 0)
[ "$SZ" -gt "$BEST_SIZE" ] && { BEST_SIZE=$SZ; BEST="$p"; }
done
[ -z "$BEST" ] && { echo "FATAL: by-id device not found, refusing to guess" >&2; exit 1; }
If the symlink doesn't appear within 15 seconds, the script fails with an error instead of guessing. A loud failure is better than a quiet write to the wrong disk.
What broke on the real run
The first host after the test run was a bastion with a 1 TB disk, and it cost me an extra half hour. yc compute disk create failed immediately:
ERROR: rpc error: code = InvalidArgument
desc = Request validation error: Disk size must be greater or equal than 1024.0 GB
The reason was simple and fully my fault. I had hardcoded --size 100, because the first couple of machines had 100 GB disks. This one did not. The SRC_SIZE_GB step above fixes it: always read the size from the source disk, never hardcode it.
The second problem came from the same bastion and the same 1 TB disk, this time during the snapshot:
ERROR: operation (id=...) poll fail: rpc error: code = Unavailable
desc = error reading from server: read tcp ...: read: operation timed out
...14m26s
The CLI gave up after fourteen and a half minutes of polling and reported a failure. By then the instance was already stopped. My first reaction was to run the command again. Luckily, I checked first:
bashyc operation get <operation-id>
done: true, snapshot READY. The operation kept running on the server for almost forty more minutes after the CLI stopped waiting. A retry with the same snapshot name would have failed with "already exists", and the bastion would have stayed down twice as long for nothing. Since then, for any disk over a hundred gigabytes, I check yc operation get first. Only then do I decide whether to retry or continue from the next step by hand.
Summary
- Adding a key through instance metadata only helps if something on the VM still polls metadata. VMs set up by hand often apply
user-dataonce and never again. - You can't detach a boot disk, whether the VM is running or stopped. Work with a copy made from a snapshot.
- The full flow: stop → snapshot → new disk from the snapshot → mount and fix on a rescue VM → delete the old instance, create it again on the fixed disk with the same name and IP.
- Always take the new disk size from the source disk. A size that works on one host will fail on another.
- When several hosts share one rescue VM, find the disk by
/dev/disk/by-id/virtio-<disk-id>, never by the order inlsblk. - With many hosts, group them by what breaks, not by service type. Do the network path (VPN, routers) last and by hand.
- A long CLI operation on a big disk that "failed" may still finish on the server. Check
yc operation getbefore you retry.