在初始化 Terraform教程中,您创建并应用了基本的 Cloudflare 配置。现在您将把这个配置存储在版本控制中,以便跟踪、进行同行评审和实现回滚功能。
在提交到版本控制之前,请从您的 Terraform 文件中删除凭据。Cloudflare 提供程序 v5 会自动从环境变量中读取身份验证信息。
更新您的 main.tf 文件以删除硬编码的 API 令牌:
terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 5"
}
}
}
provider "cloudflare" {
# API token will be read from CLOUDFLARE_API_TOKEN environment variable
}
variable "zone_id" {
description = "Cloudflare Zone ID"
type = string
sensitive = true
}
variable "account_id" {
description = "Cloudflare Account ID"
type = string
sensitive = true
}
variable "domain" {
description = "Domain name"
type = string
default = "example.com"
}
resource "cloudflare_dns_record" "www" {
zone_id = var.zone_id
name = "www"
content = "203.0.113.10"
type = "A"
ttl = 1
proxied = true
comment = "Domain verification record"
}更新您的 terraform.tfvars 文件:
zone_id = "your-zone-id-here"
account_id = "your-account-id-here"
domain = "your-domain.com"确保将您的 API 令牌设置为环境变量:
export CLOUDFLARE_API_TOKEN="your-api-token-here"验证身份验证是否工作:
terraform plan在 Terraform 将基于变量的新配置与现有资源进行比较时,您可能会看到检测到的更改。在将硬编码值迁移到变量时,这是正常的:
# cloudflare_dns_record.www will be updated in-place
~ resource "cloudflare_dns_record" "www" {
~ name = "www.your-domain.com" -> "www"
~ zone_id = (sensitive value)
# (other attributes may show changes)
}
Plan: 0 to add, 1 to change, 0 to destroy.使用以下内容创建一个 .gitignore 文件:
.terraform/
*.tfstate*
.terraform.lock.hcl
terraform.tfvars初始化 Git 并提交您的配置:
git init
git add main.tf .gitignore
git commit -m "Step 2 - Initial Terraform v5 configuration"创建一个 GitHub 存储库(通过 Web 界面或 GitHub CLI)并推送:
git branch -M main
git remote add origin https://github.com/YOUR_USERNAME/cf-config.git
git push -u origin main您的 Terraform 配置现在受版本控制,并且已准备好进行团队协作。敏感数据(API 令牌、区域 ID)保持安全且与代码分离。