For automation purpose, you can install your own ssh key to a multipass VM. This is useful as password authentication is disabled on recent ubuntu images. So sshing to the VM without ssh key authentication you will get something like:
[email protected]: Permission denied (publickey).
Here is a oneliner:
cat ~/.ssh/yourssh.pub | multipass exec $vm_instance -- bash -c 'cat >> ~/.ssh/authorized_keys'
Explanations:
cat ~/.ssh/yourssh.pub
get the content of your favorite ssh key (you may need to create one if you don't have one yet) will be piped through stdin in the next command
multipass exec $vm_instance -- bash -c
execute a bash on the vm, the stdout of the previous cat
is attached to the stdin of the bash. -c
will execute the next command inside the vm
cat >> ~/.ssh/authorized_keys
the remote command executed on the vm: it gets the content of stdin (the piped ssh public key) and append >>
to the local ~/.ssh/authorized_keys
which is the file that stores the keys authorized to connect. As sshd is already installed, the file exists and already has the correct permission and ownership required by sshd.
Test it:
ssh ubuntu@$ip_of_the_vm
And (if your ssh-agent
or ssh related config is well oiled) you're in, on your fresh VM!
Want more automation?
OK, let's go! cloud-init trick here, instead of piping the ssh pub key after the VM has been created, you can ask multipass
to take care of it at creation time. And it's reusable.
I won't detail all extra knowledge here, as yaml syntax and related stuff, but you get the start:
EDIT: the original posted sample was using /home/ubuntu/sshkey.pub
to store the key as a local file.
Which has the nasty side effect to change parent folder ownership to
root:root
which is pretty wrong.
multipass exec vm -- bash -c 'ls -ld $HOME'
drwxr-xr-x 3 root root 4096 Jul 15 12:50 /home/ubuntu
create a YAML file cloud-init.yaml
:
#cloud-config
# ^^ this is not a comment above, but a shebang like parser hint, keep it!
write_files:
# the content here is the verbatim one line full content of your yourssh.pub
# here a small fresh generated with:
# ssh-keygen -t ed25519 -C mykey@laptop -f ~/.ssh/yourssh
- content: |
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDsDOXWBOFIEoIctYaXxHAtTtfS3JHAijxHwkOb3IgoW mykey@laptop
# may you should keep an empty line above ^^
# the filename sshkey.pub will be created as root:root owner
path: /tmp/sshkey.pub
# yes, cloud-init has an ssh key management code too :-)
# here a simple append will also do the trick...
runcmd:
- cat /tmp/sshkey.pub >> /home/ubuntu/.ssh/authorized_keys
Then create your VM:
multipass launch -n vm --cloud-init ./cloud-init.yaml
Test it... and have fun with automation 😁
ssh -i ~/.ssh/mykey [email protected]