Apply annotation upon creating an object through `kubectl`

5/17/2019

Pretty much my question is in the title. I would like to know if there is a way to apply an annotation while creating an object in Kubernetes, through kubectl.

I'll put you more in the context. I am creating an internal load balancer on GKE. To make a load balancer internal, on GKE you would add the following annotation to the service: cloud.google.com/load-balancer-type: "Internal".

But when exposing the deployment it gives me the option to make it LoadBalancer type only:

$ kubectl expose deploy nginx --port 80 --type LoadBalancer

Is there a way to apply the annotation as well on the fly, while creating the service?

EDIT

I tried the following command, that seems to be neat:

kubectl expose deploy nginx --port 80 --type LoadBalancer --overrides '{ "metadata": { "annotations": { "cloud.google.com/load-balancer-type": "Internal" } } }'

... but I am getting the follwoing error, that I don't know how to interpret:

error: unable to convert the internal object type *core.Service to Unstructured without providing a preferred version to convert to.

This is where is comes from: source

-- suren
google-kubernetes-engine
kubectl
kubernetes

2 Answers

5/17/2019

"Kubectl expose" as well as other kubectl subcommands does not have necessary options to include annotations. Kubectl has universal subcommand "annotate" but that's not always very applicable. So in most cases YAML manifests are the only viable way.

-- Vasily Angapov
Source: StackOverflow

5/17/2019

I'm not exactly sure if this is what you are looking for but it works and it's one-liner

kubectl expose deploy nginx --port 80 --type LoadBalancer -oyaml --dry-run > file; sed -i 's/creationTimestamp: null/annotations:\n    cloud.google.comload-balancer-type: "Internal"/g' file

I'm aware this is not the nicest and cleanest way.

Edit:

To put a bit more details into the command.

It's exposing a deployment nginx with port and type as you specified. -oyaml is output in yaml format and --dry-run is only printing without executing.

Then sed is replacing creationTimestamp: null with annotations and in new line adding cloud.google.com/load-balancer-type: "Internal".

-- Crou
Source: StackOverflow