You can SSH into the machine soon after creating it. There isn't any time delay or waiting period for this.
Have you tried SSH into the machine using the
browser? If not, try it and check for any errors.
Usually "
port 22: connection refused" errors occur when there is a port block in the local firewall or the
appropriate service (sshd) is not running. But in your case, you are able to SSH after a certain period of time (30 seconds). So your local firewall will be fine. Also in your bash script, I see a line "sleep 30". Disable this line and run the script again. This might lift you from 30 seconds waiting period.
Let me know if that helps you.