This project demonstrates how to run a simple "Hello, World!" web server written in Go and expose it to the internet securely using a Cloudflare Tunnel. The entire Cloudflare infrastructure (tunnel, DNS, etc.) is managed as code using OpenTofu.
Before you begin, ensure you have the following installed and configured:
- Go: To run the web server. (Installation Guide)
- OpenTofu: To manage the Cloudflare infrastructure. (Installation Guide)
- cloudflared: The command-line tool to run the tunnel. (Installation Guide)
- A Cloudflare Account: With a domain you can manage.
You need to provide your Cloudflare credentials and account details for OpenTofu to work.
-
Navigate to the
infradirectory. -
Create a file named
terraform.tfvars. -
Add your Cloudflare Account ID and Zone ID to this file. You can find these on your Cloudflare dashboard.
# infra/terraform.tfvars cloudflare_account_id = "your-account-id-goes-here" cloudflare_zone_id = "your-zone-id-goes-here"
OpenTofu authenticates to Cloudflare using an API token.
-
Create a Custom API Token in your Cloudflare dashboard (My Profile > API Tokens).
-
Grant it the following two permissions:
Account|Cloudflare Tunnel|EditZone|DNS|Edit
-
In your terminal, export the token as an environment variable. This variable must be set in the terminal session where you run OpenTofu.
export CLOUDFLARE_API_TOKEN="<your-copied-api-token>"
Follow these steps to deploy the infrastructure and run the server.
From the infra directory, run this command to download the necessary Cloudflare provider.
cd infra
tofu initApply the OpenTofu configuration to create the Cloudflare Tunnel and DNS record. You will be asked to confirm with yes.
tofu apply- Start the Go Server In a separate terminal, navigate to the project's root directory and start the Go web server.
go run server/main.go- Start the Cloudflare Tunnel
Finally, in your
infraterminal, run the tunnel. This command securely gets the tunnel token from your OpenTofu state and uses it to connect.
cloudflared tunnel run --token $(tofu output -raw tunnel_token)Your server is now live at the hostname you configured in main.tf!