能否将变量用作Terraform块定义名称?AWS WAFv2 Web ACL配置报错求助
解决Terraform中AWS WAF规则动态设置field_to_match块的问题
你碰到的这个报错确实是Terraform的语法限制导致的——它没办法直接把变量值当作块的名称来使用,field_to_match下的子块(比如single_header、uri_path这类)属于静态语法元素,不能用变量直接替换块名。
不过别担心,Terraform提供了dynamic块来解决这种需要动态生成子块的场景,正好适配你的需求。下面是修改后的完整配置代码:
resource "aws_wafv2_web_acl" "static_hosting" { provider = aws.acm_us_region name = "${var.cityName}-static-hosting" description = "WAF for ${var.cityName}-static-hosting" scope = "CLOUDFRONT" default_action { block {} } rule { name = "Check_Domain" priority = 1 action { allow {} } statement { byte_match_statement { text_transformation { priority = 0 type = "NONE" } field_to_match { # 使用dynamic块动态生成对应的子块 dynamic "${var.serviceConfig.static_hosting.conditionalType.type}" { content { name = var.serviceConfig.static_hosting.conditionalType.name } } } positional_constraint = var.serviceConfig.static_hosting.conditionalType.conditional search_string = var.serviceConfig.static_hosting.conditionalType.string } } } }
代码说明:
dynamic "${var.serviceConfig.static_hosting.conditionalType.type}"这一行会根据变量中的type值(比如你的示例里的single_header)动态创建对应的子块。content块里的内容就是该子块需要的参数,这里对应single_header的name参数,刚好匹配你的变量结构。- 这个写法支持
field_to_match支持的所有子块类型(比如query_string、method等),只要你的变量type的值是Terraform认可的块名称就行。
需要注意的是,要确保var.serviceConfig.static_hosting.conditionalType.type的值是AWS WAF允许的field_to_match子块类型,否则Terraform依然会报错。
内容的提问来源于stack exchange,提问作者MrBburn
相关产品推荐
相关产品推荐

