You could use the following simplest way (user-data) to turn off the ufw then access the instance and edit your firewall.
- stop the instance
- Edit the user data to disable the ufw once and let you access the instance
- start the instance
Following is the user data:
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, once]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
sudo ufw disable
--//
See my answer here enable firewall port 22 on ec2 server after disable it