Home > database >  Kubernetes - create secret with a label using cli in a single line
Kubernetes - create secret with a label using cli in a single line

Time:06-02

I can create a secret using a single line command like so:

kubectl -n myns create secret generic my-secret --from-literal=type=super --from-literal=url=example.com --from-file=samples=sample.txt

But it's missing a label when this is created. I want to keep it as a single line command.

Can I pass in a label parameter or do i need to do a second call to modify the created secret?

CodePudding user response:

It all depends on your definition of "in a single line". Here's a single line:

$ kubectl -n myns create secret generic my-secret \
    --from-literal=type=super \
    --from-literal=url=example.com \
    --from-file=samples=sample.txt -o json --dry-run=client |
 jq '.metadata.labels |= {"foo":"bar"}' |
 kubectl apply -f-

We create the secret, send it as JSON to stdout, modify the JSON using jq, and then pipe the result into kubectl apply -f-.

The output of the first two commands is:

{
  "kind": "Secret",
  "apiVersion": "v1",
  "metadata": {
    "name": "my-secret",
    "namespace": "myns",
    "creationTimestamp": null,
    "labels": {
      "foo": "bar"
    }
  },
  "data": {
    "samples": "dGhpcyBpcyBhIHRlc3QK",
    "type": "c3VwZXI=",
    "url": "ZXhhbXBsZS5jb20="
  }
}

CodePudding user response:

There isn't an option in the kubectl create secret command to add a label.

You will need to run a second command to add the label:

kubectl label secret my-secret -n myns "foo=bar"

But you could technically do it on one line like:

kubectl create secret generic my-secret ... && kubectl label secret my-secret "foo=bar"

Or do as @larsks suggests which is much better for job security.

  • Related