When you turn UFW on, denies any incoming connection. So, you need to disable it for port 22 and then you will be SSH to your machine again. To do so, you should edit your instance and run a Startup Script.
- In the GCP Console, go to the VM Instances page.
- Select the instance and click edit.
- Find Custom metadata option and Click Add item and Type Startup-script as a key and Copy and past the command
sudo ufw allow ssh
as a value. This command will enabled port 22 for SSH. - Click save
- Stop and start the instance. After rebooting the instance you should be able to SSH again.
Or:
- Go to edit your VM.
- Go to section
Automation
- Add Startup script
#!/bin/bash sudo ufw allow ssh
Stop and Start VM.
Link: Google Compute Engine ssh: connect to host <IP> port 22: Operation timed out - Server Fault