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

使用Terraform创建AWS Redis重复执行apply重建问题咨询

Terraform AWS ElastiCache Redis 重复销毁重建问题解决

你碰到的这个销毁重建绝对不是Redis集群的预期行为,完全是配置里的两个小细节踩坑了,咱们直接看问题根源:

问题1:cluster_mode字段类型不匹配

看你的terraform plan输出里有一行非常关键的提示:

replicas_per_node_group = 1 # forces replacement

这说明这个字段的变更触发了资源强制替换。回头看你的代码:

cluster_mode {
  num_node_groups          = "1"
  replicas_per_node_group = "1"
}

这里你把num_node_groups和replicas_per_node_group写成了带引号的字符串,但实际上这两个参数的类型要求是number(数字)。第一次创建时AWS会自动做类型转换,但后续Terraform对比配置和状态时,会认为字符串"1"和数字1是不同值,所以判定需要销毁重建。

问题2:node_type末尾多了空格

你的代码里node_type = "cache.t2.medium "(注意末尾有个空格),而实际创建后AWS存储的是无空格的cache.t2.medium。每次terraform plan时,这个空格都会被判定为配置和状态不一致,同样会触发替换操作。

修正后的配置代码

把这两个问题修复后,配置应该是这样的:

resource "aws_elasticache_replication_group" "cng_redis" {
  replication_group_description = "Cluster"
  replication_group_id         = "dev-af-redis"
  engine                       = "redis"
  engine_version               = "5.0.4"
  node_type                    = "cache.t2.medium" # 移除末尾多余空格
  port                         = 6379
  subnet_group_name            = "dev-subnet-group-airflow"
  security_group_ids           = [aws_security_group.airflow_sg.id] # Terraform 0.12+支持直接引用,无需${}
  parameter_group_name         = "default.redis5.0"
  at_rest_encryption_enabled   = true
  transit_encryption_enabled   = true
  maintenance_window           = "sun:06:00-sun:07:00"
  auto_minor_version_upgrade   = false
  apply_immediately            = true
  automatic_failover_enabled   = true
  cluster_mode {
    num_node_groups          = 1 # 改为数字类型,去掉引号
    replicas_per_node_group = 1 # 改为数字类型,去掉引号
  }
  tags = merge(
    var.common_tags,
    {
      Classification = "private",
      Name           = "airflow-redis"
    } # 用更简洁的对象写法替代旧的map()函数
  )
}

验证修复效果

修改后执行terraform plan,应该会输出No changes. Your infrastructure matches the configuration.,说明Terraform已经识别到现有资源和配置一致,不会再触发销毁重建了。

另外补充一句:apply_immediately = true只是控制变更是否立即生效,和这次的销毁重建问题无关,你可以根据自己的需求保留或修改这个配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:46:51