Helm技术问题:如何渲染toYaml插入块中的变量?
如何在KEDA触发器配置中渲染模板变量?
我有一段KEDA伸缩对象的触发器配置变量块:
# [...] autoscaling: enabled: true triggers: - type: prometheus metadata: serverAddress: http://prometheus-server.prometheus.svc.cluster.local metricName: prometheus_redis_message_count query: avg(redis_queue_job_states_total{state=~"waiting|active", namespace="{{ $.Release.Namespace }}", queue="reports"}) without (instance, pod, pod_template_hash, state) threshold: '1' activationThreshold: '1' # [...]
可以看到autoscaling.triggers[0].metadata.query中包含{{ $.Release.Namespace }}变量,但使用toYaml函数渲染时,这个变量无法被解析。我需要找到一种方法,把所有触发器项渲染到最终模板里的同时,解析其中包含的变量。
目前我用了一种临时方案,虽然能推进开发,但灵活性很差,无法支持多个触发器或其他类型的触发器:
# [...] - type: prometheus metadata: serverAddress: http://prometheus-server.prometheus.svc.cluster.local metricName: prometheus_redis_message_count {{- with index .autoscaling.triggers 0 }} query: {{ tpl .metadata.query $ }} {{- end }} threshold: '1' activationThreshold: '1' # [...]
优化后的解决方案
通过遍历所有触发器并使用tpl函数逐一渲染字段,即可实现灵活支持多触发器、同时解析变量的需求:
triggers: {{- range .autoscaling.triggers }} - type: {{ .type }} metadata: query: {{ tpl .metadata.query $ }} serverAddress: {{ tpl .metadata.serverAddress $ }} threshold: {{ tpl .metadata.threshold $ | quote }} activationThreshold: {{ tpl .metadata.activationThreshold $ | quote}} metricName: {{ tpl .metadata.metricName $ }} {{- end }}
这种写法既会生成合法的YAML数组,又能正确渲染所有字段中的模板变量。
内容的提问来源于stack exchange,提问作者Michael Niemand
相关产品推荐
相关产品推荐

