Terraform验证传入字符串列表与本地列表匹配的实现方法
Terraform变量验证:确保传入的事件类型在允许列表内
我正在创建Azure Event Grid的Terraform模块,要求仅使用指定的事件类型列表,同时会部署Azure Policy作为ClickOps视角的二次过滤。相关代码如下:
locals.tf
local { event_types = [ "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted", "Microsoft.Storage.BlobRenamed", "Microsoft.Web.AppUpdated" ] }
variables.tf(默认值为客户输入示例)
variable "included_event_types" { type = list(string) default = ["Microsoft.Storage.BlobDeleted", "Microsoft.Storage.BlobRenamed", "Microsoft.Storage.DirectoryRenamed" ] }
问题
如何编写验证规则,检查传入变量列表中的每个元素是否都存在于本地列表中?我最初的解决方案在for关键字处出现“missing item separator”错误:
variable "included_event_types" { type = list(string) default = [] validation { condition = all([contains(lower(local.event_types), lower(s)) for s in var.included_event_types]) error_message = "Error" } }
解决方案
原代码存在两个问题:一是lower(local.event_types)直接对列表使用lower()函数,而lower()仅支持字符串类型;二是语法结构导致Terraform解析出错。修正后的验证规则如下:
variable "included_event_types" { type = list(string) default = [] validation { condition = all([ contains( [for t in local.event_types : lower(t)], lower(s) ) for s in var.included_event_types ]) error_message = "传入的事件类型必须是以下允许值之一:${join(", ", local.event_types)}。" } }
说明
- 用列表推导式
[for t in local.event_types : lower(t)]将本地允许的所有事件类型转换为小写,实现大小写不敏感的匹配 - 对
var.included_event_types中的每个元素s,转成小写后检查是否存在于转换后的允许列表中 all()函数确保所有传入的事件类型都符合要求,只要有一个不在允许列表内就会触发错误提示,同时错误消息明确列出了所有允许的事件类型,方便排查
内容的提问来源于stack exchange,提问作者Maabat
相关产品推荐
相关产品推荐

