Ubuntu: setup user-data ssh

I want to install Ubuntu Server 20.04 on Rpi 4 without monitor, so I have to setup SSH in advance by editing user-data file in system-boot folder.

Is it possible to setup SSH for user: set public key and disable password by default before the first login to my Pi?

I found one manual here but there is no info how to setup SSH properly in uaer-data file:

chpasswd:
  expire: true
  list:
  - ubuntu:ubuntu

I need help as I can't find any comprehensive example for such purpose, unfortunately. But there are some cloud config examples for virtual box (1, 2), so I don't know if it is valid for my case.

users:
  - default
  - name: ubuntu
    ssh-authorized-keys:
      - <your user public key here>
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: sudo
    shell: /bin/bash

Solution 1:

Folks, after several attempts installing Ubuntu w/o monitor (playing with blackbox) the required config was succeeded.

My user-data file:

users:
  - default
  - name: ubuntu
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: sudo, users, admin
    lock_passwd: true
    ssh_pwauth: True
    ssh_import_id: None
    ssh_authorized_keys:
      - <your user public key here>

#chpasswd:
#  expire: true
#  list:
#  - ubuntu:ubuntu

#ssh_pwauth: true

Note that default chpasswd and ssh_pwauth are commented out and ssh_authorized_keys written with underscores unlike many examples.

So, you have to generate SSH key on your machine and add it to ssh_authorized_keys list, that's all. No twitching after first connection is required.

Solution 2:

The accepted answer did not helped me. After some more googling I came across this post:

If you are connected via ethernet this is how user-data file should look like: (change this in the image before connecting to the pi)

#cloud-config

## Set hostname
hostname: raspberry

## Configure default user
system_info:
  default_user:
    name: pi
    ssh_authorized_keys:
      - ssh-rsa ... user@comment
    sudo: ALL=(ALL) NOPASSWD:ALL

And change ssh-rsa ... user@comment to the content of id_rsa.pub of the machine where you are connecting from

Offcourse you can also change the hostname and the default_user name

After successful login you can set the password for this user like this:

sudo -i
passwd pi

You will be prompted like this:

New password: 
Retype new password: 

End after that:

passwd: password updated successfully

End then

exit

If all that does still not work, try this "Move your existing Raspberry Pi 4 Ubuntu install from SD card to USB/SSD"