Terraform配置CloudFront动态块报错:参数定义需以换行结尾
Terraform CloudFront动态块语法错误排查
我在AWS CloudFront Distribution资源中编写了如下ordered_cache_behavior动态块:
dynamic "ordered_cache_behavior" { for_each = var.ordered_cache_behaviors content { path_pattern = ordered_cache_behavior.value.path_pattern allowed_methods = ordered_cache_behavior.value.allowed_methods cached_methods = ordered_cache_behavior.value.cached_methods target_origin_id = var.origin_id cache_policy_id = var.cache_policy_ids["${var.policy_prefix}${ordered_cache_behavior.value.cache_policy_name}"] origin_request_policy_id = ordered_cache_behavior.value.path_pattern = "/" ? var.origin_request_policy_ids["whitelist_policy"] : null dynamic "lambda_function_association" { for_each = var.enable_auth ? var.default_cache_behavior.lambda_function_association : ordered_cache_behavior.value.lambda_function_association content { event_type = lambda_function_association.value.event_type include_body = lambda_function_association.value.include_body lambda_arn = lambda_function_association.value.lambda_arn != "" ? lambda_function_association.value.lambda_arn : local.lambda_mapping[lambda_function_association.value.event_type] } } compress = ordered_cache_behavior.value.compress viewer_protocol_policy = ordered_cache_behavior.value.viewer_protocol_policy } }
运行后触发如下错误:
│ Error: Missing newline after argument │ │ on main.tf line 111, in resource "aws_cloudfront_distribution" "web_distribution": │ 111: origin_request_policy_id = ordered_cache_behavior.value.path_pattern = "/" ? var.origin_request_policy_ids["origin_1H_1D_plp_pdp_whitelist_whitelist_none"] : null │ │ An argument definition must end with a newline.
我的需求是根据path_pattern是否为"/"来设置origin_request_policy_id,但不清楚错误原因,请问问题出在哪?
问题根源
错误提示看似是换行问题,但实际是三元表达式的判断符号用错了:你用了单个等号=,这是Terraform里的赋值操作符,而判断值相等需要用双等号==。
当你写ordered_cache_behavior.value.path_pattern = "/"时,Terraform会把它理解为赋值操作,后面跟着的? ... : ...就成了无效语法,导致解析混乱,才抛出了“缺少换行”的错误提示。
修正方案
把判断符号改成==即可,修正后的origin_request_policy_id行代码如下:
origin_request_policy_id = ordered_cache_behavior.value.path_pattern == "/" ? var.origin_request_policy_ids["whitelist_policy"] : null
替换后重新执行Terraform命令,语法错误就能解决,同时也能实现根据path_pattern是否为"/"来设置对应策略ID的需求。
内容的提问来源于stack exchange,提问作者MBA
相关产品推荐
相关产品推荐

