I've a nodejs application which needs to read secret in RT
This is the secret
apiVersion: v1
kind: Secret
metadata:
name: secert1
namespace: trail
type: Opaque
data:
TOKEN1: cmVhbGx5X3NlY3JldF92YWx1ZTE=
I have used a volume to mount the secret as I've many fields that I need to read and I don't want to use the var option.
I've added volume to the deployment as following:
volumeMounts:
- name: secret-volume
mountPath: /etc/secret-volume
volumes:
- name: secret-volume
secret:
secretName: secert1
My question is how should I access the secret from the nodejs app?
I've tried with the following and didnt get any data, any idea?
const fs = require('fs');
fs.readFile('/etc/secret-volume', function read(err, data) {
if (err) {
throw err;
}
const content = data;
});
I usually set the secrets as environment variables from K8s this way:
env:
-
name: MY_SECRET_VARIABLE
valueFrom:
secretKeyRef:
name: secert1
key: MY_SECRET_VARIABLE
And then in your code, simply use process.env.MY_SECRET_VARIABLE
to access it.
You can see more details on how to do this here: https://medium.com/faun/using-kubernetes-secrets-as-environment-variables-5ea3ef7581ef
I have found a very useful solution, I had the same problem and I have solved it like this
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: insertmendoza
name: sarys-authentications
spec:
replicas: 1
selector:
matchLabels:
app: sarys-authentications
template:
metadata:
labels:
app: sarys-authentications
spec:
containers:
- name: sarys-authentications
image: 192.168.88.246:32000/sarys:authentications
imagePullPolicy: Always
resources:
limits:
memory: "500Mi"
cpu: "50m"
ports:
- containerPort: 8000
envFrom:
- configMapRef:
name: authentications-config
- secretRef: <<-- add
name: authentications-sercret <<-- add
volumeMounts:
- name: config-volumen
mountPath: /etc/config/
readOnly: true
- name: secret-volumen
mountPath: /etc/secret/
readOnly: true
volumes:
- name: config-volumen
configMap:
name: authentications-config
- name: secret-volumen
secret:
secretName: authentications-sercret
Each data
item in a secret will become a file in the mountPath
of the secret based volume.
To read lots of tokens you can trawl the directory with readdir
and readFile
const fsp = require('fs').promises
const path = require('path')
async function readTokens(token_path) {
const tokens = {}
const entries = await fsp.readdir(token_path, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isFile()) continue
const buf = await fsp.readFile(path.join(token_path, entry.name), 'utf8')
tokens[file] = buf.toString()
}
return tokens
}
readTokens('/etc/secret-volume').then(console.log).catch(console.err)
You can read as below.TOKEN1
is the key from the secret secert1
var token1_value = fs.readFileSync("/etc/secret-volume/TOKEN1", 'utf8');