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

如何仅当证书将过期时触发Terraform MongoDB证书资源替换?

解决MongoDB Atlas X.509证书仅在即将过期时触发Terraform资源替换的问题

问题场景

需要实现仅当MongoDB Atlas的X.509认证数据库用户证书将在一个月内过期时,才触发该资源的替换(生成新证书)。现有配置会在terraform_data.replacement的值变化时(无论是否为证书即将过期的状态)均触发替换,不符合需求。

现有配置代码:

locals {
  expire_in_less_than_month =     timecmp(mongodbatlas_x509_authentication_database_user.backend.current_certificate.not_after, timeadd(timestamp(), "768h")) == -1
}

resource "terraform_data" "replacement" {
  input = local.expire_in_less_than_month
}


resource "mongodbatlas_x509_authentication_database_user" "backend" {
  project_id              = mongodbatlas_database_user.backend.project_id
  username                = mongodbatlas_database_user.backend.username
  months_until_expiration = 6
  lifecycle {
    replace_triggered_by = [
      terraform_data.replacement 
# this will always trigger replaces when this value change but I  want to trigger replace only when replacement has value 1, when it is 0 I do not want to recreate this resource
    ]
}

解决方案

核心思路是让触发替换的标记仅在证书即将过期时才发生变化,其他状态下保持固定值。具体修改如下:

locals {
  # 判断证书是否在一个月(768小时)内过期
  expire_in_less_than_month = timecmp(
    mongodbatlas_x509_authentication_database_user.backend.current_certificate.not_after,
    timeadd(timestamp(), "768h")
  ) == -1

  # 仅当证书即将过期时,生成动态变化的触发值;否则使用证书当前的过期时间(固定值)
  replacement_trigger = local.expire_in_less_than_month ? timestamp() : mongodbatlas_x509_authentication_database_user.backend.current_certificate.not_after
}

resource "terraform_data" "replacement" {
  input = local.replacement_trigger
}

resource "mongodbatlas_x509_authentication_database_user" "backend" {
  project_id              = mongodbatlas_database_user.backend.project_id
  username                = mongodbatlas_database_user.backend.username
  months_until_expiration = 6

  lifecycle {
    replace_triggered_by = [terraform_data.replacement.input]
  }
}

原理说明

  • 当证书未进入过期预警期时,replacement_trigger使用证书的not_after值(该值在证书未被替换前保持固定),因此terraform_data.replacement不会发生状态变更,不会触发资源替换。
  • 当证书进入一个月内过期的预警期时,replacement_trigger切换为当前时间戳(每次执行terraform plan/apply时都会生成新值),此时terraform_data.replacement的状态更新,触发mongodbatlas_x509_authentication_database_user资源的替换,生成新的证书。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:13:24