How to use terraform for cloudflare

前置條件

  • terraform
  • cloudflare

建立 Cloudflare token

開啟 Cloudflare Token 設定,建立一個 token,包含以下權限

  • 區域 -> 區域設定 -> 編輯
  • 區域 -> 區域 -> 編輯
  • 區域 -> DNS -> 編輯

撰寫 terraform

在主目錄建立3個 tf 檔案

1
2
3
4
5
6
# main.tf

# 設定 provider,並帶入 api token
provider "cloudflare" {
api_token = var.cf_api_token
}
1
2
3
4
5
# variables.tf

variable "cf_api_token" {
type = string
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# cf.tf

# 設定 cloudflare 的zone
# https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/zone
resource "cloudflare_zone" "seancheng-space" {
zone = "seancheng.space"
}

# 設定 dns records
# https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/record
resource "cloudflare_record" "root-seancheng-space" {
name = "seancheng.space"
type = "A"
zone_id = cloudflare_zone.seancheng-space.id
value = "127.0.0.1"
proxied = true
}

resource "cloudflare_record" "blog-seancheng-space" {
name = "blog"
type = "CNAME"
zone_id = cloudflare_zone.seancheng-space.id
value = "blackhorseya.github.io"
proxied = true
}

最後執行 terraform apply