ufw enable over SSH stops and asks whether you really want to, since it may cut your connection. That question breaks automated setups, so there is a flag to skip it.
In a provisioning script it looks like this:
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow proto tcp from any to any port 80,443
ufw --force enable
--force answers the prompt for you. The order is the whole point: the SSH rule goes in before the firewall comes up, so the connection your script is running over survives.
I’d also add a safety net when doing this by hand on a remote box you can’t reach otherwise. Schedule a disable before you enable:
echo 'ufw disable' | sudo at now + 5 minutes
sudo ufw --force enable
If you can still log in, remove the job with atq and atrm. If you locked yourself out, the firewall switches itself off in five minutes. This needs the at package installed.
Watch for a custom SSH port. ufw allow OpenSSH opens port 22 only, so if sshd listens on another port, allow that number instead. Since --force removes the last warning, a wrong port in a script means a server you can only reach through a console.
Further reading: ufw(8) manual page, at(1) manual page