How to add custom http headers when using kubectl tool

11/26/2018

Can not find any issues.

I have to add several custom http headers to access my dedicate api-server proxy, but no clues available right now. Did I miss something?

-- AndyChow
http-headers
kubectl
kubernetes

1 Answer

10/4/2019

This is a dirty hard coded hack to show you how to get the outcome your looking for it's not a fully vetted solution. This method will compile a new version of kubectl that will add your needed headers. Maybe it will at least give you a idea to run with.

The reason I wanted to do this is because I put my k8s api endpoint on the internet and safeguarded it with Cloudflare Access. To allow Cloudflare access to let me get past the steel wall I needed to pass in two headers one for my client id and the other for client secret. This ended up working like a charm and is one case someone may want to add custom headers.

Steps:

  • I assume you have Go installed and setup, if not go do that now.
  • git clone https://github.com/kubernetes/kubernetes.git (could take awhile it's pretty big)
  • cd kubernetes/staging/src/k8s.io/client-go/transport/
  • Open file round_trippers.go in your favorite code editor
  • Search for func (rt userAgentRoundTripper) RoundTrip(req http.Request) (*http.Response, error)
  • Add your needed headers by adding lines like this req.Header.Set("Bob-Is", "cool")
  • cd back to root folder kubernetes/
  • cd cmd/kubectl/
  • go build custom-kubectl
  • now test it with ./custom-kubectl get ns --v=9
  • in that output look for the header you added to the rest calls to K8s api, you should see -H "Bob-Is: cool" in the output
  • To make this not a hack maybe see if there's a way to add a kubectl plugin you create do to this for you or ask the kind folks in the k8s community how you can make this hacky method a bit cleaner or if there's a reason adding customer headers isn't a good idea. Worst case parameterize your custom kubectl build to pull in a new parameter you add --custom-request-headers and make it a bit more clean.
-- Kuberchaun
Source: StackOverflow