Extract LoadBalancer name from kubectl output with go-template

7/30/2018

I'm trying to write a go template that extracts the value of the load balancer. Using --go-template={{status.loadBalancer.ingress}} returns [map[hostname:GUID.us-west-2.elb.amazonaws.com]]% When I add .hostname to the template I get an error saying, "can't evaluate field hostname in type interface {}". I've tried using the range keyword, but I can't seem to get the syntax right.

{
    "apiVersion": "v1",
    "kind": "Service",
    "metadata": {
        "creationTimestamp": "2018-07-30T17:22:12Z",
        "labels": {
            "run": "nginx"
        },
        "name": "nginx-http",
        "namespace": "jx",
        "resourceVersion": "495789",
        "selfLink": "/api/v1/namespaces/jx/services/nginx-http",
        "uid": "18aea6e2-941d-11e8-9c8a-0aae2cf24842"
    },
    "spec": {
        "clusterIP": "10.100.92.49",
        "externalTrafficPolicy": "Cluster",
        "ports": [
            {
                "nodePort": 31032,
                "port": 80,
                "protocol": "TCP",
                "targetPort": 8080
            }
        ],
        "selector": {
            "run": "nginx"
        },
        "sessionAffinity": "None",
        "type": "LoadBalancer"
    },
    "status": {
        "loadBalancer": {
            "ingress": [
                {
                    "hostname": "GUID.us-west-2.elb.amazonaws.com"
                }
            ]
        }
    }
}
-- Jeremy Cowan
go-templates
kubernetes

2 Answers

5/16/2019

try this:

kubectl get svc <name> -o go-template='{{range .items}}{{range .status.loadBalancer.ingress}}{{.hostname}}{{printf "\n"}}{{end}}{{end}}'
-- Amjad Hussain Syed
Source: StackOverflow

7/30/2018

As you can see from the JSON, the ingress element is an array. You can use the template function index to grab this array element.

Try:

kubectl get svc <name> -o=go-template --template='{{(index .status.loadBalancer.ingress 0 ).hostname}}'

This is assuming of course that you're only provisioning a single loadbalancer, if you have multiple, you'll have to use range

-- jaxxstorm
Source: StackOverflow