Not on Ubuntu, but the following works for me:
systemd-inhibit --what sleep --why "Lock screen" --mode delay xdg-screensaver lock & systemctl suspend
Replace xdg-screensaver lock
with the command to lock the screen on your system and systemctl suspend
with systemctl hibernate
if you want to lock the screen before hibernating.
This works by locking the screen in parallel to suspending the machine. However the screen locking command is running as inhibitor that delays the sleep. This way, systemd will wait until the screen is locked before executing.
If you have inhibitors that are blocking the suspend, add the -i
flag at the end.