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

Terraform模块中基于列表条件创建SNS邮件订阅资源咨询

解决方案

要实现仅当传入非空邮箱列表时才创建SNS订阅资源,只需调整for_each的表达式,确保空列表场景下返回空集合,Terraform就不会生成该资源的任何实例。

修改后的代码

resource "aws_sns_topic_subscription" "email_target" {
  for_each               = length(var.sns_email_subscriber) > 0 ? toset(var.sns_email_subscriber) : toset([])
  topic_arn              = aws_sns_topic.sns_topic.arn
  protocol               = "email"
  endpoint               = each.value
  endpoint_auto_confirms = true
}

关键说明

  • 通过length(var.sns_email_subscriber) > 0判断邮箱列表是否非空
  • 若列表非空,将其转为集合(自动去重重复邮箱)用于for_each;若为空则返回空集合,此时资源不会被创建
  • 建议给变量设置默认空列表,确保未传入参数时也能触发空集合逻辑:
variable "sns_email_subscriber" {
  type        = list(string)
  description = "List of email addresses to subscribe to the SNS topic"
  default     = []
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 10:42:36