Teebs
Teebs

Reputation: 785

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

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?

Upvotes: 5

Views: 8575

Answers (3)

Aragorn Dai
Aragorn Dai

Reputation: 1

This can let you generate YAML file of secret, and then apply it.

kubectl create secret generic my-secret ... -o yaml --dry-run=client |\
kubectl label -f - foo=bar --local -o yaml > my_secret.yaml
kubectl apply -f my_secret.yaml

You can also generate it directly:

kubectl create secret generic my-secret ... -o yaml --dry-run=client |\
kubectl label -f - foo=bar --local -o yaml |\
kubectl apply -f -

Upvotes: 0

blacktide
blacktide

Reputation: 12076

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.

Upvotes: 6

larsks
larsks

Reputation: 311606

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="
  }
}

Upvotes: 6

Related Questions