[英]k8s read secert from nodejs application
我有一個 nodejs 應用程序需要讀取 RT 中的秘密
這是秘密
apiVersion: v1
kind: Secret
metadata:
name: secert1
namespace: trail
type: Opaque
data:
TOKEN1: cmVhbGx5X3NlY3JldF92YWx1ZTE=
我使用了一個卷來掛載秘密,因為我需要閱讀許多字段並且我不想使用 var 選項。
我已將卷添加到部署中,如下所示:
volumeMounts:
- name: secret-volume
mountPath: /etc/secret-volume
volumes:
- name: secret-volume
secret:
secretName: secert1
我的問題是我應該如何從 nodejs 應用程序訪問秘密?
我已經嘗試了以下並沒有得到任何數據,知道嗎?
const fs = require('fs');
fs.readFile('/etc/secret-volume', function read(err, data) {
if (err) {
throw err;
}
const content = data;
});
密鑰中的每個data
項都將成為基於密鑰的卷的mountPath
中的一個文件。
要讀取大量令牌,您可以使用readdir
和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)
您可以閱讀如下。 TOKEN1
是來自秘密secert1
的密鑰
var token1_value = fs.readFileSync("/etc/secret-volume/TOKEN1", 'utf8');
我通常以這種方式將秘密設置為 K8s 的環境變量:
env:
-
name: MY_SECRET_VARIABLE
valueFrom:
secretKeyRef:
name: secert1
key: MY_SECRET_VARIABLE
然后在您的代碼中,只需使用process.env.MY_SECRET_VARIABLE
來訪問它。
您可以在此處查看有關如何執行此操作的更多詳細信息: https://medium.com/faun/using-kubernetes-secrets-as-environment-variables-5ea3ef7581ef
我找到了一個非常有用的解決方案,我遇到了同樣的問題,我已經這樣解決了
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.