Kubernetes Secret
Kubernetes Secret
官方文档:https://kubernetes.io/docs/concepts/configuration/secret/
- 加密数据并存放Etcd中,让Pod的容器以挂载Volume方式访问。
- 应用场景:凭据
通过文本文件创建用户密码
- 创建用户名密码文件
echo -n 'admin' > ./username.txt
echo -n '1f2d1e2e67df' > ./password.txt
- 通过文件创建用户名密码
kubectl create secret generic db-user-pass --from-file=./username.txt --from-file=./password.txt
- 查看创建用户名密码
kubectl get secret
NAME TYPE DATA AGE
db-user-pass Opaque 2 37s
- 查看详情
kubectl describe secret db-user-pass
Name: db-user-pass
Namespace: default
Labels: <none>
Annotations: <none>
Type: Opaque
Data
====
password.txt: 12 bytes
username.txt: 5 bytes
通过yaml文件创建用户名密码
- 编码用户名密码
echo -n 'admin' | base64
echo -n '1f2d1e2e67df' | base64
- 创建yaml文件 vim user.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
- 创建用户名密码
kubectl create -f user.yaml
- 查看创建用户
kubectl get secret
NAME TYPE DATA AGE
db-user-pass Opaque 2 5m42s
mysecret Opaque 2 18s
通过环境变量导入到容器中
- 创建yaml文件
vim secret-var.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: nginx
image: nginx
env:
# 环境变量名称:用户
- name: SECRET_USERNAME
valueFrom:
# 选择输入secret用户
secretKeyRef:
name: mysecret
key: username
# 环境变量名称:密码
- name: SECRET_PASSWORD
valueFrom:
# 选择输入secret密码
secretKeyRef:
name: mysecret
key: password
- 创建Pod
kubectl create -f secret-var.yaml
- 查看创建Pod
kubectl get pods
NAME READY STATUS RESTARTS AGE
mypod 1/1 Running 0 23s
- 进入Pod查看变量
kubectl exec -it mypod bash
root@mypod:/# echo $SECRET_USERNAME
admin
root@mypod:/# echo $SECRET_PASSWORD
1f2d1e2e67df
通过volume挂载用户名密码
- 创建yaml文件
cat secret-vol.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: foo
mountPath: "/etc/foo"
readOnly: true
volumes:
- name: foo
secret:
# 创建的secret
secretName: mysecret
- 创建Pod
kubectl create -f secret-vol.yaml
- 查看Pod
kubectl get pod
NAME READY STATUS RESTARTS AGE
mypod 1/1 Running 0 46s
- 进入Pod查看
kubectl exec -it mypod bash
root@mypod:/# ls /etc/foo/
password username
root@mypod:/# cat /etc/foo/password
1f2d1e2e67dfroot@mypod:/# cat /etc/foo/username
adminroot@mypod:/#