Terraforming a Cloudflare domain for an ephemeral IP of a GCE instance
TL;DR
We provisioned a Compute Engine VM assigning an ephemeral IP to it. Then, we attached this IP to a record A in a Cloudflare’s handled domain. All managed by Terraform.
Hello there.
This article contains a practical example on how to provision a Compute Engine VM in GCP and attaching a subdomain handled by Cloudflare to the VM’s public IP. All automated and orchestrated by Terraform.
Pre setup
Before begin, you need the following:
- A GCP project with a linked billing account.
- A service account of your project, with the proper permissions to create, modify and delete GCE instances.
- Enable the Compute Engine API on GCP.
- Terraform installed.
- Cloudflare’s API Token and Zone ID.
- Clone the repo
- Want to automate things.
Cloudflare API Token
You can create an API Token in Cloudflare, going to the “API Tokens” section in the “My Profile” page. You need permission to handle the DNS on the zone, at least.
The Zone ID could be found in the “Overview” section of your domain. In the bottom right part of the section.
TF variables
First, rename the terraform.tfvars.copy file to terraform.tfvars. Then fill the variables:
cloud_flare_api_token = "<YOUR_CLOUDFLARE_API_TOKEN>"
cloudflare_zone_id = "<YOUR_CLOUDFLARE_DOMAIN_ZONE_ID>"
project = "<GCP_PROJECT_ID>"
GCP Service Account
Download your Service Account key and place it on the root directory, renaming it to account.json. This key is ignored by Git.
Terraforming the world
Some input variables
We have set up some input variables for Terraform in the input.tf file, just use it, or change in a conveniently way:
We are ready to Terraform!
Let’s begin by provisioning our GCE instance and it associates resources.
GCP Provider
To use GCP on Terraform, we need first to declare the “google” provider:
GCE Resource
That was easy 👌. Now, let’s create a GCE instance.
In a matter of example, I’m thinking of a Debian image-based machine as small as possible, with a test script to start a webserver in the 80 port going through the internet by a public IP. In other words:
Firewall rule
If we are creating a web server in the 80 port, we need to allow the traffic through it.
As you could see, We used the default network interface. Let’s import it with a Terraform Data Source and assign a firewall rule to allow traffic by the 80 port from any source.
Cloudflare provider
Same as GCP provider, we must declare the Cloudflare provider as follow:
Cloudflare record
We are using a subdomain of our main domain, say “www”. But first, we need to gather the ephemeral IP of our GCE instance to assign it to the record.
Run the example
Placed on the root folder of the project, run
terraform init
to download all the needed plugins. Next, run
terraform apply
All is done, review your GCE instance on GCP and the just created record A on Cloudflare.
Thanks:
Terraform & Vault master Stenio Ferreira.