Secret可以把想要访问的加密数据,存放到Etcd中,然后Pod可以通过的Volume的方式,访问到Secret保存的信息 ,每当数据修改的时候,Pod挂载的Secret文件也会被修改,特别适合用来存放账户密码
一、创建Secret对象
1. 通过文件创建
生成两个文件,分别是username.txt和password.txt
echo "chenqionghe" > ./username.txt
echo "111111" > ./password.txt
创建
kubectl create secret generic user --from-file=./username.txt
kubectl create secret generic pass --from-file=./password.txt
2. 通过yaml创建
注意:值必须是base64转码
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
user: Y2hlbnFpb25naGUK
pass: MTExMTExCg==
创建
kubectl apply -f mysecret.yaml
二、获取secret对象
[email protected]:/home/ubuntu/project-volume# kubectl get secrets
NAME TYPE DATA AGE
default-token-gqfrx kubernetes.io/service-account-token 3 20d
mysecret Opaque 2 1m
pass Opaque 1 6m
user Opaque 1 6m
三、通过pod使用secret示例
这里指定了volume是projected类型,引用的是secret的user和pass,挂载路径为/projected-volume
apiVersion: v1
kind: Pod
metadata:
name: test-projected-volume
spec:
containers:
- name: test-secret-volume
image: busybox
args:
- sleep
- "86400"
volumeMounts:
- name: mysql-cred
mountPath: "/projected-volume"
readOnly: true
volumes:
- name: mysql-cred
projected:
sources:
- secret:
name: user
- secret:
name: pass
执行创建
kubectl apply -f test-projected-volume.yaml
查看pod已经创建出来
[email protected]:/home/ubuntu/project-volume# kubectl get pod
NAME READY STATUS RESTARTS AGE
test-projected-volume 1/1 Running 0 5m
再进入pod内查看,看到文件已经存在,并且内容和设置的一样
[email protected]:/home/ubuntu/project-volume# kubectl exec -it test-projected-volume -- /bin/sh
/ # ls /projected-volume/
password.txt username.txt
/ # cat /projected-volume/username.txt
chenqionghe
然后我们修改一下username的secret文件,将chenqionghe修改为cqh(对应的base编码为Y3FoCg==)
kubectl edit secret user
修改内容如下
apiVersion: v1
data:
username.txt: Y3FoCg==
kind: Secret
metadata:
creationTimestamp: 2019-09-27T09:14:00Z
name: user
namespace: default
resourceVersion: "2108808"
selfLink: /api/v1/namespaces/default/secrets/user
uid: 24566f8f-e107-11e9-8c22-f242c645cfec
type: Opaque
再次查看pod中挂载的文件,已经发生变化
[email protected]:/home/ubuntu# kubectl exec -it test-projected-volume -- cat /projected-volume/username.txt
cqh
原文地址:https://www.cnblogs.com/chenqionghe/p/11601049.html
时间: 2024-10-10 19:01:09