Skip to content

Instantly share code, notes, and snippets.

@mattmichal
Created October 7, 2022 11:31
Show Gist options
  • Save mattmichal/6c12a3b6500052052b92e6ce9a173529 to your computer and use it in GitHub Desktop.
Save mattmichal/6c12a3b6500052052b92e6ce9a173529 to your computer and use it in GitHub Desktop.
Sample Terraform code that uses Cloudflare provider version 3.25.0 to perform operations on resources that require API token as well as API user service key. Secrets are passed to Terraform via TF_VAR environment variables. Two providers are configured and then both are passed to a local module.
module "app" {
for_each = local.applications.customers
source = "./modules/app/"
customer_name = each.key
providers = {
cloudflare = cloudflare
cloudflare.user_service_key = cloudflare.user_service_key
}
}
# ./modules/app/main.tf
resource "cloudflare_record" "cname" {
name = var.customer_name
proxied = true
ttl = 1
type = "CNAME"
value = azurerm_app_service.app.default_site_hostname
zone_id = var.cloudflare_zone_id
}
resource "cloudflare_record" "cname_verification" {
name = "asuid.${var.customer_name}"
proxied = false
ttl = 1
type = "TXT"
value = azurerm_app_service.app.custom_domain_verification_id
zone_id = var.cloudflare_zone_id
}
resource "cloudflare_origin_ca_certificate" "app_origin" {
provider = cloudflare.user_service_key
csr = tls_cert_request.app_origin.cert_request_pem
hostnames = [cloudflare_record.cname.hostname, "www.${cloudflare_record.cname.hostname}"]
request_type = "origin-rsa"
requested_validity = 15 * 365
}
# ./modules/app/versions.tf
terraform {
required_version = "~> 1.0"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.74.0"
}
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 3.25"
configuration_aliases = [cloudflare.user_service_key]
}
}
provider "cloudflare" {
api_token = var.cloudflare_api_token
}
provider "cloudflare" {
alias = "user_service_key"
api_user_service_key = var.cloudflare_api_user_service_key
}
# GitHub Actions workflow configuration
jobs:
terraform:
name: terraform
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TF_IN_AUTOMATION: true
TF_VAR_cloudflare_api_token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
TF_VAR_cloudflare_api_user_service_key: ${{ secrets.CLOUDFLARE_API_USER_SERVICE_KEY }}
...
variable "cloudflare_api_token" {
type = string
description = "API token for Cloudflare that has write access to the `auredia.com` zone."
}
variable "cloudflare_api_user_service_key" {
type = string
description = "User Service Key for Cloudflare with access to Origin CA operations."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment