Search code examples
kubernetesjsonpath

Extract information of kubernetes annotations with jsonpath


I have this JSON code:

{
    "apiVersion": "autoscaling/v1",
    "kind": "HorizontalPodAutoscaler",
    "metadata": {
        "annotations": {
            "autoscaling.alpha.kubernetes.io/metrics": "[{\"type\":\"Resource\",\"resource\":{\"name\":\"memory\",\"targetAverageValue\":\"400Mi\"}}]",
            "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"autoscaling/v2beta1\",\"kind\":\"HorizontalPodAutoscaler\",\"metadata\":{\"annotations\":{},\"name\":\"pdn-location-suscriber\",\"namespace\":\"pdn-oms\"},\"spec\":{\"maxReplicas\":3,\"metrics\":[{\"resource\":{\"name\":\"cpu\",\"targetAverageUtilization\":100},\"type\":\"Resource\"},{\"resource\":{\"name\":\"memory\",\"targetAverageValue\":\"400Mi\"},\"type\":\"Resource\"}],\"minReplicas\":1,\"scaleTargetRef\":{\"apiVersion\":\"extensions/v1beta1\",\"kind\":\"Deployment\",\"name\":\"location-suscriber\"}}}\n"
        }
    }
}

I need to obtain the value of targetAverageValue = 400Mi that is in "autoscaling.alpha.kubernetes.io/metrics", so how create a JSONPath expression to extract that.


Solution

  • You can extract the information using jq.
    Just run the following command.

    $ kubectl get hpa <hpa-name> -o=json | jq '.metadata.annotations["autoscaling.alpha.kubernetes.io/metrics"]' | jq -r | jq '.[].resource.targetAverageValue'
    

    Also you can try the following.

    $ kubectl get hpa <hpa-name> -o=jsonpath="{.metadata.annotations.autoscaling\.alpha\.kubernetes\.io\/metrics}" | jq '.[].resource.targetAverageValue'