You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform使用自建DigitalOcean CDN作为状态后端报错解决方案咨询

问题:如何将自建DigitalOcean CDN作为Terraform状态后端使用

问题重现

CDN与Spaces创建代码

# Create a new Spaces Bucket
resource "digitalocean_spaces_bucket" "mybucket" {
  name   = "example"
  region = "sfo2"
  acl    = "public-read"
}

# Add a CDN endpoint to the Spaces Bucket
resource "digitalocean_cdn" "mycdn" {
  origin = digitalocean_spaces_bucket.mybucket.bucket_domain_name
}

# Output the endpoint for the CDN resource
output "fqdn" {
  value = digitalocean_cdn.mycdn.endpoint
}

后端配置代码

terraform {
  backend "s3" {
    endpoint                    = digitalocean_cdn.mycdn.endpoint
    bucket                      = "example"
    key                         = "terraform.tfstate"
    region                      = "sfo3"
    access_key                  = "access_key"
    secret_key                  = "secret_key"
    skip_credentials_validation = true
    skip_metadata_api_check     = true
    skip_region_validation      = true
  }
}

执行terraform init后的报错

Initializing the backend...
╷
│ Error: Variables not allowed
│ 
│   on backend.conf line 1:
│    1: endpoint                    = digitalocean_cdn.mycdn.endpoint
│ 
│ Variables may not be used here.
╵

核心原因

  1. Terraform后端初始化是所有资源创建前的第一个步骤,此时digitalocean_cdn.mycdn.endpoint这类资源属性还未生成,无法被引用。
  2. Terraform后端配置不允许使用任何动态引用(变量、资源属性等),只能填入静态值,或通过初始化参数传入。
  3. 额外纠正:DigitalOcean CDN是用于加速Spaces内容访问的分发端点,不提供对象存储的API服务,Terraform的S3兼容后端需要连接到Spaces的API端点(而非CDN端点)才能完成状态文件的读写操作。

解决方案

步骤1:先创建Spaces与CDN(不配置远程后端)

  1. 保留CDN创建代码,移除后端配置块。
  2. 执行以下命令完成资源创建:
    terraform init
    terraform apply
    
  3. 记录输出的Spaces API端点(格式为${region}.digitaloceanspaces.com,比如sfo2.digitaloceanspaces.com),以及CDN端点(若需用于其他场景)。

步骤2:配置Terraform后端使用Spaces API端点

选择以下任意一种方式配置后端:

方式1:直接写入静态值

terraform {
  backend "s3" {
    endpoint                    = "sfo2.digitaloceanspaces.com" # 替换为你的Spaces API端点
    bucket                      = "example"
    key                         = "terraform.tfstate"
    region                      = "sfo2" # 与Spaces区域一致
    access_key                  = "your_access_key" # 替换为你的DO访问密钥
    secret_key                  = "your_secret_key" # 替换为你的DO密钥
    skip_credentials_validation = true
    skip_metadata_api_check     = true
    skip_region_validation      = true
  }
}

方式2:使用独立配置文件

创建backend.conf文件:

endpoint = "sfo2.digitaloceanspaces.com"
bucket = "example"
key = "terraform.tfstate"
region = "sfo2"
access_key = "your_access_key"
secret_key = "your_secret_key"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_region_validation = true

执行初始化命令时指定配置文件:

terraform init -backend-config=backend.conf

步骤3:迁移本地状态到远程后端

执行terraform init时,Terraform会提示是否迁移本地状态到远程后端,输入yes确认即可完成迁移。


内容的提问来源于stack exchange,提问作者Guilherme Nunes da Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:39:56