Mr.Turtle
Mr.Turtle

Reputation: 3090

Create kubernetes secret from .json file

I have a json file with some keys like this:

{
  "a":"someval"
  "b":"someval"
  .. more keys
}

How do I add these keys to a secret in kubernetes?

When I try $ kubectl create secret generic mysecret --from-file=file.json it returns a secret containing the file, but I want to map the contents of the file to the secret, not add the file as a secret.

Output:

$ kubectl get secret mysecret -o yaml

apiVersion: v1
data:
  file.json: #base64 encoded stuff here.
kind: Secret

Wanted output:

$ kubectl get secret mysecret -o yaml

apiVersion: v1
data:
  a: someval
  b: someval
kind: Secret

What am I doing wrong?

Upvotes: 17

Views: 36658

Answers (4)

toddcscar
toddcscar

Reputation: 1225

Create a json file like this (note that secret values must be base64-encoded):

{ 
  "metadata": {
    "annotations": {},
    "name": "mytest",
    "namespace": "default"
  },
  "apiVersion": "v1",
  "kind": "Secret",
  "data": {
    "a": "dGVzdA==",
    "b": "dGVzdA=="
  }
}

Then pass it into kubectl create:

kubectl create -f secrets-file.json

Upvotes: 6

ton
ton

Reputation: 4607

You can use --from-literal:

kubectl create secret generic secretname --from-literal "someJsonKey=$(cat somejsonfile.json)"

Then you can recover the data with

kubectl get secret secretname -o 'go-template={{ .data.someJsonKey | base64decode }}'

Upvotes: -1

P Ekambaram
P Ekambaram

Reputation: 17689

Try these steps

kubectl proxy --port 8000 &  
curl localhost:8000/api/v1/namespaces/default/secrets 

curl localhost:8000/api/v1/namespaces/default/secrets \
  -X POST -H "Content-Type: application/json" \
  --data '{"metadata":{"name":"mytest"},"stringData":{"a":"test","b":"test","c":"test"}}'

master $ curl localhost:8000/api/v1/namespaces/default/secrets/mytest{
  "kind": "Secret",
  "apiVersion": "v1",
  "metadata": {
    "name": "mytest",
    "namespace": "default",
    "selfLink": "/api/v1/namespaces/default/secrets/mytest",
    "uid": "55736602-725e-11e9-b3a2-0242ac110034",
    "resourceVersion": "2948",
    "creationTimestamp": "2019-05-09T13:28:29Z"
  },
  "data": {
    "a": "dGVzdA==",
    "b": "dGVzdA==",
    "c": "dGVzdA=="
  },
  "type": "Opaque"
}

Upvotes: 7

Vasilii Angapov
Vasilii Angapov

Reputation: 9042

If you have flat (not nested) JSON then try this (assuming you have jq tool installed):

kubectl create secret generic test --from-env-file <(jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" YOUR_FILE.json)

Upvotes: 12

Related Questions