Create kubernetes secret from .json file

5/9/2019

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 -n staging personalbillett-auth0-login-credentials -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?

-- Mr.Turtle
kubernetes

3 Answers

5/9/2019

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)
-- Vasily Angapov
Source: StackOverflow

5/9/2019

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"
}
-- P Ekambaram
Source: StackOverflow

9/6/2019

create a json file like this:

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

Then pipe it into kubectl create:

echo secrets-file.json | kubectl create -f -
-- toddcscar
Source: StackOverflow