如何在Terraform模块中条件化配置ordered_cache_behavior?
解决Terraform CloudFront模块条件化添加ordered_cache_behavior的问题
你的问题出在把count放在了ordered_cache_behavior的列表元素内部——count是Terraform用于控制资源/模块实例数量的参数,不能直接嵌套在模块的参数值里。该模块的ordered_cache_behavior参数接受的是一个对象列表,因此需要通过条件表达式动态生成这个列表,来实现仅当each.value.main_website为true时添加配置的效果。
正确配置示例
module "cloudfront" { source = "terraform-aws-modules/cloudfront/aws" version = "~>3.2" # 用条件表达式判断:为true时返回带配置的列表,否则返回空列表 ordered_cache_behavior = each.value.main_website ? [ { path_pattern = "/*" # 注意:该参数为模块必填项,需根据实际需求调整 use_forwarded_values = false target_origin_id = "s3_one" # 可根据需求添加其他ordered_cache_behavior支持的参数,比如viewer_protocol_policy等 } ] : [] }
关键说明
- 当
each.value.main_website为true时,ordered_cache_behavior会被设置为包含指定配置的列表;为false时则是空列表,模块会忽略该配置。 - 注意补充
path_pattern这类必填参数,否则模块会抛出参数缺失的错误,具体必填项可参考该模块3.2版本的定义。
内容的提问来源于stack exchange,提问作者Neekoy
相关产品推荐
相关产品推荐

