jsonjqkubectlredis-sentinel

format json output jq


I'm deploying redis-commander in Kubernetes. I'm creating a configuration connection file for Redis-Commander. I have a command in my bash script to get the required parameters for the connection file as per the link. Managed to connect locally between redis-commander and 1 redis server via sentinel just fine but have many more in non-prod so I need to configure the command below to get desired json output.

This command

kubectl get svc --selector='app.kubernetes.io/component=sentinel' --all-namespaces -o json |
jq -r '
.items[]
   | {label:"my-label",
   sentinels: [{host: (.metadata.name + "."
   + .metadata.namespace + "."
   + "svc" + "."
   + "cluster" + "."
   + "local"),port: .spec.ports[0].port}],
   sentinelName:"mymaster",
   dbIndex: 0
   }
| {connections: [.]}'

has an output similar to this (I've changed the name part):

{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name1.development.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}
{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name2.development.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}
{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name3.staging.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}

The output I'm trying to achieve is this:

{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name1.development.svc.cluster.local",
          "port": 26379
        },
        {
          "host": "name2.development.svc.cluster.local",
          "port": 26379
        },
        {
          "host": "name3.staging.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}

Not used jq many times so any pointers would be greatly appreciated.


Solution

  • Using map with .items is probably a better way to go, along the lines of:

    .items
    | {
        label: "my-label",
        sentinels: map(
          { host: (.metadata.name + "."
              + .metadata.namespace + "."
              + "svc" + "."
              + "cluster" + "."
              + "local"),
            port: .spec.ports[0].port
          } ),
        sentinelName: "mymaster",
        dbIndex: 0
      }
    | {connections: [.] }