0

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.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52

2 Answers2

3

You can actually use this expression to get your desired value.

kubectl get hpa pdn-location-suscriber(your_hpa_name) -n pdn-oms -o jsonpath="{.spec.metrics[1].resource.targetAverageValue}"

which means jsonpath expression:

jsonpath="{.spec.metrics[1].resource.targetAverageValue}"

as you have metrics under spec which is a list you have to use index number which is 1 in this case.

Taybur Rahman
  • 1,347
  • 8
  • 20
2

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'
Masudur Rahman
  • 1,585
  • 8
  • 16