基于enabled状态的Helm3 JSON Schema字段验证需求
解决Helm values.yaml中CPU/Memory自动扩缩容的JSON Schema验证问题
以下是符合你需求的JSON Schema配置,能正确实现enabled为true时必填目标利用率百分比、enabled为false时无需指定的验证逻辑:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "autoscaling": { "type": "object", "properties": { "minReplicas": { "type": "integer", "minimum": 1 }, "maxReplicas": { "type": "integer", "minimum": 1 }, "cpu": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "targetCPUUtilizationPercentage": { "type": "integer", "minimum": 1, "maximum": 100 } }, "required": ["enabled"], "allOf": [ { "if": { "properties": { "enabled": { "const": true } } }, "then": { "required": ["targetCPUUtilizationPercentage"] }, "else": { "not": { "required": ["targetCPUUtilizationPercentage"] } } } ] }, "memory": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "targetMemoryUtilizationPercentage": { "type": "integer", "minimum": 1, "maximum": 100 } }, "required": ["enabled"], "allOf": [ { "if": { "properties": { "enabled": { "const": true } } }, "then": { "required": ["targetMemoryUtilizationPercentage"] }, "else": { "not": { "required": ["targetMemoryUtilizationPercentage"] } } } ] } }, "required": ["minReplicas", "maxReplicas"] } } }
关键说明(针对你之前if-else失效的问题)
- 相对路径引用:在
cpu/memory的子Schema中,if条件直接引用当前对象的enabled字段,而非绝对路径,避免路径匹配错误。 - allOf包裹条件:将条件逻辑放在
allOf数组中,确保基础属性规则(比如enabled必填)和条件验证规则同时生效。 - 精准的条件控制:
- 当
enabled: true时,then块强制要求目标利用率字段为必填项,同时字段本身被定义为1-100的整数,保证有效性。 - 当
enabled: false时,else块通过not规则解除目标利用率字段的必填要求(允许填写但不强制,符合你“无需指定”的需求)。
- 当
可选调整:禁止enabled为false时填写目标字段
如果需要实现enabled: false时不允许填写目标利用率字段,可将else块修改为:
"else": { "properties": { "targetMemoryUtilizationPercentage": { "not": { "type": "integer" } } } }
Helm使用方式
将上述Schema保存为values.schema.json,放在Helm Chart的根目录下,Helm会自动使用该Schema对values.yaml进行验证。
内容的提问来源于stack exchange,提问作者Arpan Solanki
相关产品推荐
相关产品推荐

