Skip to content

LucaGelmini/tofu-tunnel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

Go Server with Cloudflare Tunnel and OpenTofu

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.


Prerequisites

Before you begin, ensure you have the following installed and configured:


Configuration

You need to provide your Cloudflare credentials and account details for OpenTofu to work.

1. Configure OpenTofu Variables

  1. Navigate to the infra directory.

  2. Create a file named terraform.tfvars.

  3. 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"

2. Set Cloudflare API Token

OpenTofu authenticates to Cloudflare using an API token.

  1. Create a Custom API Token in your Cloudflare dashboard (My Profile > API Tokens).

  2. Grant it the following two permissions:

    • Account | Cloudflare Tunnel | Edit
    • Zone | DNS | Edit
  3. 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>"

How to Run

Follow these steps to deploy the infrastructure and run the server.

1. Initialize OpenTofu

From the infra directory, run this command to download the necessary Cloudflare provider.

cd infra
tofu init

2. Deploy the Infrastructure

Apply the OpenTofu configuration to create the Cloudflare Tunnel and DNS record. You will be asked to confirm with yes.

tofu apply
  1. 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
  1. Start the Cloudflare Tunnel Finally, in your infra terminal, 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!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors