使用jq查找JSON指定字段并为对应K8s Redis实例插入sentinel密码
正确实现方案
方案1:流式一步生成(推荐)
不需要存储中间JSON变量,直接在管道中完成配置生成和密码填充,避免转义错误:
# 先拉取对应sentinel的密码,请替换<>中的实际secret名称和密码字段名 password=$(kubectl get secret -n development <你的secret名称> -o jsonpath='{.data.<密码对应的key名>}' | base64 -d) # 直接生成最终配置文件 kubectl get svc --selector='app.kubernetes.io/component=sentinel' --all-namespaces -o json | jq -r --arg target_host "Redis2.development.svc.cluster.local" --arg sentinel_pwd "$password" ' .items | map( { label:.metadata.name, sentinels: [{ host:(.metadata.name + "." + .metadata.namespace + ".svc.cluster.local"), port: .spec.ports[0].port }], sentinelName:"mymaster", sentinelPassword: "", dbIndex: 0 }) | {connections: . } # 匹配目标host填充密码 | .connections[] |= if .sentinels[0].host == $target_host then .sentinelPassword = $sentinel_pwd else . end ' > /local.json
方案2:保留中间变量的写法
如果你需要先存储初始JSON再修改,使用以下正确语法:
# 存储初始生成的JSON JSON=$(kubectl get svc --selector='app.kubernetes.io/component=sentinel' --all-namespaces -o json | jq -r ' .items | map( { label:.metadata.name, sentinels: [{host:(.metadata.name + "." + .metadata.namespace + ".svc.cluster.local"),port: .spec.ports[0].port}], sentinelName:"mymaster", sentinelPassword: "", dbIndex: 0 }) | {connections: . }') # 拉取sentinel密码 password=$(kubectl get secret -n development <你的secret名称> -o jsonpath='{.data.<密码对应的key名>}' | base64 -d) # 匹配修改后写入文件 echo "$JSON" | jq -r --arg target_host "Redis2.development.svc.cluster.local" --arg sentinel_pwd "$password" ' .connections[] |= if .sentinels[0].host == $target_host then .sentinelPassword = $sentinel_pwd else . end ' > /local.json
关键语法说明
- 使用jq的
--arg参数将shell变量传入jq内部,避免嵌套引号转义错误 - 用
|=运算符遍历connections数组的每个元素,匹配到目标host后直接修改对应sentinelPassword字段值
内容的提问来源于stack exchange,提问作者Alan
相关产品推荐
相关产品推荐

