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

如何在Terraform中动态配置CloudFront缓存行为?

Terraform 根据变量切换CloudFront缓存行为配置

核心思路

通过条件数据源加载和dynamic块结合,实现根据is_cache_disabled变量切换两种缓存配置逻辑:

  • 缓存禁用时:使用AWS托管的Managed-CachingDisabled缓存策略
  • 缓存启用时:使用自定义TTL配置和forwarded_values块

完整配置示例

1. 变量定义

variable "is_cache_disabled" {
  type = bool
}

2. 条件加载缓存策略数据源

仅当缓存禁用时,才加载AWS托管的禁用缓存策略:

data "aws_cloudfront_cache_policy" "cache_disabled" {
  count = var.is_cache_disabled ? 1 : 0
  name  = "Managed-CachingDisabled"
}

3. CloudFront分发资源配置

在default_cache_behavior中通过条件表达式和dynamic块实现配置切换:

resource "aws_cloudfront_distribution" "cloudfront_distribution" {
  # 此处保留你的其他固定配置(如origin、viewer_protocol_policy等)

  default_cache_behavior {
    some_parameter_1 = some_value1
    some_parameter_2 = some_value2

    # 缓存禁用时设置托管策略ID,启用时忽略该参数
    cache_policy_id = var.is_cache_disabled ? data.aws_cloudfront_cache_policy.cache_disabled[0].id : null

    # 动态生成TTL配置(仅缓存启用时生效)
    dynamic "default_ttl" {
      for_each = var.is_cache_disabled ? [] : [1]
      content {
        default_ttl = 86400
      }
    }

    dynamic "max_ttl" {
      for_each = var.is_cache_disabled ? [] : [1]
      content {
        max_ttl = 86400
      }
    }

    dynamic "min_ttl" {
      for_each = var.is_cache_disabled ? [] : [1]
      content {
        min_ttl = 3600
      }
    }

    # 动态生成forwarded_values块(仅缓存启用时生效)
    dynamic "forwarded_values" {
      for_each = var.is_cache_disabled ? [] : [1]
      content {
        cookies {
          forward = "none"
        }
        query_string = true
      }
    }
  }
}

关键逻辑说明

  • 条件数据源:通过count参数控制数据源是否创建,避免缓存启用时加载无用资源
  • cache_policy_id条件赋值:使用Terraform条件表达式,缓存禁用时取托管策略ID,启用时设为null(Terraform会自动忽略null参数)
  • dynamic块控制:利用for_each的空数组/单元素数组特性,决定是否生成TTL参数和forwarded_values块——空数组表示不生成,单元素数组表示生成一次

内容的提问来源于stack exchange,提问作者rzlvmp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:10:05