首页 > 其他分享 >k8s secret 创建与使用

k8s secret 创建与使用

时间:2024-12-18 15:59:24浏览次数:5  
标签:kubectl default 创建 nginx secret master k8s root

secret (加密存放的配置文件)

描述:

secret 存放敏感数据 比如:私钥与证书
docker 认证:用于在私有仓库拖镜像时使用的账号密码

查看secret几种类型

app                    default-token-mknnt                      kubernetes.io/service-account-token   3      20d
app                    user-registry                            kubernetes.io/dockerconfigjson        1      28h
default                basic-auth                               Opaque                                1      27hdefault                ingressclass-ingress-nginx-admission     Opaque                                3      23d
default                ingressclass-ingress-nginx-token-fz4hg   kubernetes.io/service-account-token   3      23d
default                prometheus-tls-secret                    kubernetes.io/tls                     2      17h
default                sh.helm.release.v1.ingressclass.v1       helm.sh/release.v1                    1      23d

 创建方式

[root@master-1 ~]# kubectl create secret
Create a secret using specified subcommand.

Available Commands:
  docker-registry 创建一个给 Docker registry 使用的 secret
  generic         从本地 file, directory 或者 literal value 创建一个 secret
  tls             创建一个 TLS secret

1. 创建imagePullSecrets

镜像拉取secret 分为两种方式

    1. 使用账号密码方式创建

    2. 使用/root/.docker/config.json制作

1.1 账号密码方式

[root@master-1 ~]# kubectl create secret docker-registry user-registry --docker-server=xxx:10006 --docker-username=admin --docker-password=Diaonigehai123..
secret/user-registry created

 3.1.1 查看secret

[root@master-1 ~]# kubectl get secret
NAME                                     TYPE                                  DATA   AGE
default-token-4zqth                      kubernetes.io/service-account-token   3      21d
ingressclass-ingress-nginx-admission     Opaque                                3      21d
ingressclass-ingress-nginx-token-fz4hg   kubernetes.io/service-account-token   3      21d
nfs-client-provisioner-token-s4n6n       kubernetes.io/service-account-token   3      21d
sh.helm.release.v1.ingressclass.v1       helm.sh/release.v1                    1      21d
user-registry                            kubernetes.io/dockerconfigjson        1      6s
[root@master-1 ~]# kubectl describe secret user-registry Name: user-registry Namespace: default Labels: <none> Annotations: <none> Type: kubernetes.io/dockerconfigjson Data ==== .dockerconfigjson: 127 bytes [root@master-1 ~]# kubectl get secret user-registry -oyaml apiVersion: v1 data: .dockerconfigjson: eyJhdXRoxbmlnZWhhaTEyMy4uIiwiYXV0aCxxTXVMZz09In19fQ== kind: Secret metadata: creationTimestamp: "2024-12-16T07:37:55Z" managedFields: - apiVersion: v1 fieldsType: FieldsV1 fieldsV1: f:data: .: {} f:.dockerconfigjson: {} f:type: {} manager: kubectl-create operation: Update time: "2024-12-16T07:37:55Z" name: user-registry namespace: default resourceVersion: "1109902" uid: 4e54c04d-1387-4e2a-9539-04d9b297c420 type: kubernetes.io/dockerconfigjson

 1.1.2 解密secret

[root@master-1 busybox]# echo 'eyJhdXRocyIxxixyMy4uIiwiYXxxz09In19fQ==' |base64 --decode
{"auths":{"xxx:10006":{"username":"admin","password":"xx..","auth":"xxxxx=="}}}

 1.1.3 配置到yml清单中

[root@master-1 busybox]#  cat busybox-secret-pull.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-secret
spec:
  containers:
  - name: nginx-secret
    image: xxx:10006/k8s/nginx:latest
    imagePullPolicy: Always
    #command: ["sleep", "3600"]
  imagePullSecrets:- name: user-registry

1.1.4 测试拉取镜像发布

Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  32s   default-scheduler  Successfully assigned default/nginx-secret to node-1
  Normal  Pulling    32s   kubelet            Pulling image "xxx:10006/k8s/nginx:latest"
  Normal  Pulled     31s   kubelet            Successfully pulled image "xxx:10006/k8s/nginx:latest" in 452.059332ms
  Normal  Created    31s   kubelet            Created container nginx-secret
  Normal  Started    31s   kubelet            Started container nginx-secret

1.2 使用 config.json 创建 Secret

 1.2.1 使用config.json制作secret

当用户成功docker login server:port后,会在家目录下生成一个.docker/config.json文件

[root@master-1 ~]# cat .docker/config.json
{
        "auths": {
                "xxx:10006": {
                        "auth": "YWxx"
                }
        }

创建secret

[root@master-1 ~]# kubectl create secret generic  docker-cfg-impull --from-file=.dockerconfigjson=/root/.docker/config.json --type=kubernetes.io/dockerconfigjson
secret/docker-cfg-impull created
[root@master-1 ~]# kubectl  get secret
NAME                                     TYPE                                  DATA   AGE
default-token-4zqth                      kubernetes.io/service-account-token   3      21d
docker-cfg-impull                        kubernetes.io/dockerconfigjson        1      9s
ingressclass-ingress-nginx-admission     Opaque                                3      21d
ingressclass-ingress-nginx-token-fz4hg   kubernetes.io/service-account-token   3      21d
nfs-client-provisioner-token-s4n6n       kubernetes.io/service-account-token   3      21d
sh.helm.release.v1.ingressclass.v1       helm.sh/release.v1                    1      21d
user-registry                            kubernetes.io/dockerconfigjson        1      3m47s
[root@master-1 ~]# kubectl  get secret docker-cfg-impull -oyaml
apiVersion: v1
data:
  .dockerconfigjson: ewoJImF1dGhzIxxVm9ZV2t4TWpNdUxnPT0iCgkJfQoJfQp9
kind: Secret
metadata:
  creationTimestamp: "2024-12-16T07:41:33Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:.dockerconfigjson: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-12-16T07:41:33Z"
  name: docker-cfg-impull
  namespace: default
  resourceVersion: "1110342"
  uid: e50cfc09-bd08-47c2-a466-2fdea4de5cdc
type: kubernetes.io/dockerconfigjson
[root@master-1 ~]# kubectl describe secret docker-cfg-impull Name: docker-cfg-impull Namespace: default Labels: <none> Annotations: <none> Type: kubernetes.io/dockerconfigjson Data ==== .dockerconfigjson: 96 bytes

 测试拉取镜像

[root@master-1 busybox]# cat busybox-secret-pull.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-secret
spec:
  containers:
  - name: nginx-secret
    image: xxx:10006/k8s/nginx:latest
    imagePullPolicy: Always
    #command: ["sleep", "3600"]
  imagePullSecrets:
  - name: docker-cfg-impull

 查看pod创建过程

Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  32s   default-scheduler  Successfully assigned default/nginx-secret to node-1
  Normal  Pulling    32s   kubelet            Pulling image "xxx:10006/k8s/nginx:latest"
  Normal  Pulled     31s   kubelet            Successfully pulled image "xxx:10006/k8s/nginx:latest" in 452.059332ms
  Normal  Created    31s   kubelet            Created container nginx-secret
  Normal  Started    31s   kubelet            Started container nginx-secret

 至此,创建拉取镜像的secret已经创建完成,并且可以成功拉取。

1.3 跨namespace的secret引用问题

但是,secret属于namespace资源,也就是说默认创建的secret在default命名空间,当创建的pod不在default命名空间,则会拉取失败

[root@master-1 busybox]# cat busybox-secret-pull.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-secret
  namespace: app
spec:
  containers:
  - name: nginx-secret
    image: xxx:10006/k8s/nginx:latest
    imagePullPolicy: Always
    #command: ["sleep", "3600"]
  imagePullSecrets:
  #- name: docker-cfg-impull
  - name: user-registry

 1.3.1 创建pod并查看详情

[root@master-1 busybox]# kubectl  get pod -w -owide -n app
NAME           READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED NODE   READINESS GATES
nginx-secret   0/1     Pending   0          0s    <none>   <none>   <none>           <none>
nginx-secret   0/1     Pending   0          0s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ContainerCreating   0          0s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ContainerCreating   0          1s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ErrImagePull        0          2s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ErrImagePull        0          2s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ErrImagePull        0          2s    <none>   node-1   <none>           <none>
nginx-secret   0/1     ImagePullBackOff    0          3s    10.244.84.189   node-1   <none>           <none>

[root@master-1 busybox]# kubectl describe pod nginx-secret -n app
Name:         nginx-secret
Namespace:    app
Priority:     0
Node:         node-1/192.168.43.130
Start Time:   Mon, 16 Dec 2024 16:07:07 +0800
Labels:       <none>
Annotations:  cni.projectcalico.org/containerID: ba0edfe518142569f4b4d87fe4b1c8386b7678a98e2f5af7796e0c52c99867b6
              cni.projectcalico.org/podIP: 10.244.84.189/32
              cni.projectcalico.org/podIPs: 10.244.84.189/32
Status:       Pending
IP:           10.244.84.189
IPs:
  IP:  10.244.84.189
Containers:
  nginx-secret:
    Container ID:
    Image:          xxx:10006/k8s/nginx:latest
    Image ID:
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       ErrImagePull
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-mknnt (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-mknnt:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-mknnt
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason          Age                From               Message
  ----     ------          ----               ----               -------
  Normal   Scheduled       31s                default-scheduler  Successfully assigned app/nginx-secret to node-1
  Normal   SandboxChanged  29s                kubelet            Pod sandbox changed, it will be killed and re-created.
  Normal   Pulling         16s (x2 over 30s)  kubelet            Pulling image "xxx:10006/k8s/nginx:latest"
  Warning  Failed          16s (x2 over 30s)  kubelet            Failed to pull image "xxx:10006/k8s/nginx:latest": rpc error: code = Unknown desc = Error response from daemon: unauthorized: unauthorized to access repository: k8s/nginx, action: pull: unauthorized to access repository: k8s/nginx, action: pull
  Warning  Failed          16s (x2 over 30s)  kubelet            Error: ErrImagePull
  Normal   BackOff         4s (x4 over 29s)   kubelet            Back-off pulling image "xxx:10006/k8s/nginx:latest"
  Warning  Failed          4s (x4 over 29s)   kubelet            Error: ImagePullBackOff

 解决:

 方法 1:在每个 Namespace 中重新创建 Secret

kubectl create secret docker-registry my-registry-secret \
  --docker-server=<server> \
  --docker-username=<username> \
  --docker-password=<password> \
  --namespace=other-namespace

 方法2. 通过 kubectl get 和 kubectl apply 复制 Secret

kubectl get secret my-registry-secret -n my-namespace -o yaml > secret.yaml
# 修改namespace
metadata:
  namespace: other-namespace
# 部署
kubectl apply -f secret.yaml

 方法 3:使用 ServiceAccount 引用 Secret

kubectl patch serviceaccount default \
  -n my-namespace \
  -p '{"imagePullSecrets": [{"name": "existing-secret"}, {"name": "new-registry-secret"}]}'

即使使用sa与secret绑定,也需要在当前的namespace创建imagePullSecrets,这其实与在每个namespace创建一个secret一样,只不过这种是加载到默认的default中,如果pod没有指定sa,则默认加载default的sa。

 查看默认的sa
Namespace:           app
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   default-token-mknnt
Tokens:              default-token-mknnt
Events:              <none>
创建Image pull secrets
kubectl get secret user-registry -oyaml >user-registry.yaml

# 修改命名空间
apiVersion: v1
data:
  .dockerconfigjson: eyJeE1qTXVMZz09In19fQ==
kind: Secret
metadata:
  creationTimestamp: "2024-12-16T07:37:55Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:.dockerconfigjson: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-12-16T07:37:55Z"
  name: user-registry
  namespace: app
  resourceVersion: "1109902"
  uid: 4e54c04d-1387-4e2a-9539-04d9b297c420
type: kubernetes.io/dockerconfigjson
 将secret配置到sa
kubectl patch serviceaccount default \
  -n app \
  -p '{"imagePullSecrets": [{"name": "user-registry"}]}'
 再次查看sa
[root@master-1 busybox]# kubectl describe sa -n app  default
Name:                default
Namespace:           app
Labels:              <none>
Annotations:         <none>
Image pull secrets:  user-registry
Mountable secrets:   default-token-mknnt
Tokens:              default-token-mknnt
Events:              <none>
 将sa配置到pod清单
apiVersion: v1
kind: Pod
metadata:
  name: nginx-secret
  namespace: app
spec:
  serviceAccountName: default
  containers:
  - name: nginx-secret
    image: xx:10006/k8s/nginx:latest
    imagePullPolicy: Always
    #command: ["sleep", "3600"]
  #imagePullSecrets:
  #- name: docker-cfg-impull
  #- name: user-registry
 查看pod已经创建成功
[root@master-1 ~]# kubectl get pod -n app -w
nginx-secret   0/1     ContainerCreating   0          0s
nginx-secret   0/1     ContainerCreating   0          1s
nginx-secret   1/1     Running             0          2s


Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  23s   default-scheduler  Successfully assigned app/nginx-secret to node-1
  Normal  Pulling    23s   kubelet            Pulling image "xxx:10006/k8s/nginx:latest"
  Normal  Pulled     23s   kubelet            Successfully pulled image "xxx:10006/k8s/nginx:latest" in 618.903779ms
  Normal  Created    23s   kubelet            Created container nginx-secret
  Normal  Started    23s   kubelet            Started container nginx-secret

2. 创建Opaque 类型secret

 帮助文档

Examples:
  # Create a new secret named my-secret with keys for each file in folder bar
  kubectl create secret generic my-secret --from-file=path/to/bar

  # Create a new secret named my-secret with specified keys instead of names on disk
  kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-file=ssh-publickey=path/to/id_rsa.pub

  # Create a new secret named my-secret with key1=supersecret and key2=topsecret
  kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret

  # Create a new secret named my-secret using a combination of a file and a literal
  kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-literal=passphrase=topsecret

  # Create a new secret named my-secret from an env file
  kubectl create secret generic my-secret --from-env-file=path/to/bar.env

实际操作:

从目录创建secret

[root@master-1 bar]# ll /opt/secret/bar/
总用量 8
-rw-r--r-- 1 root root 24 12月 18 14:28 password.txt
-rw-r--r-- 1 root root 29 12月 18 14:27 username.txt
[root@master-1 bar]# cat username.txt
zhangsan
lisi
wangwu
zhaoliu
[root@master-1 bar]# cat password.txt
xxxxx
zzzzz
ccccc
vvvvv

创建

[root@master-1 bar]# kubectl create secret generic my-secret --from-file=/opt/secret/bar
secret/my-secret created

[root@master-1 bar]# kubectl get secret
NAME                                     TYPE                                  DATA   AGE
basic-auth                               Opaque                                1      28h
default-token-4zqth                      kubernetes.io/service-account-token   3      23d
docker-cfg-impull                        kubernetes.io/dockerconfigjson        1      46h
ingressclass-ingress-nginx-admission     Opaque                                3      23d
ingressclass-ingress-nginx-token-fz4hg   kubernetes.io/service-account-token   3      23d
my-secret                                Opaque                                2      11s
nfs-client-provisioner-token-s4n6n       kubernetes.io/service-account-token   3      23d
prometheus-tls-secret                    kubernetes.io/tls                     2      17h
sh.helm.release.v1.ingressclass.v1       helm.sh/release.v1                    1      23d
user-registry                            kubernetes.io/dockerconfigjson        1      46h

[root@master-1 bar]# kubectl get secret my-secret -oyaml
apiVersion: v1
data:
  password.txt: eHh4eHgKenp6enoKY2NjY2MKdnZ2dnYK    # 可以看到key是文件名
  username.txt: emhhbmdzYW4KbGlzaQp3YW5nd3UKemhhb2xpdQo=
kind: Secret
metadata:
  creationTimestamp: "2024-12-18T06:29:06Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:password.txt: {}
        f:username.txt: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-12-18T06:29:06Z"
  name: my-secret
  namespace: default
  resourceVersion: "1294805"
  uid: 27ef10db-a41b-4b69-980a-27aaceaa4114
type: Opaque

# 解析 [root@master-1 bar]# echo eHh4eHgKenp6enoKY2NjY2MKdnZ2dnYK |base64 --decode xxxxx zzzzz ccccc vvvvv [root@master-1 bar]# echo emhhbmdzYW4KbGlzaQp3YW5nd3UKemhhb2xpdQo |base64 --decode zhangsan lisi wangwu zhaoliu

从文件创建secret

 解决key是文件名问题,自定义key

[root@master-1 bar]# kubectl create secret generic my-secret -n default --from-file=username=username.txt --from-file=password=password.txt
secret/my-secret created

[root@master-1 bar]# kubectl describe secret "my-secret"
Name:         my-secret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
password:  24 bytes
username:  29 bytes
[root@master-1 bar]# kubectl get secret "my-secret" -oyaml apiVersion: v1 data: password: eHh4eHgKenp6enoKY2NjY2MKdnZ2dnYK username: emhhbmdzYW4KbGlzaQp3YW5nd3UKemhhb2xpdQo= kind: Secret metadata: creationTimestamp: "2024-12-18T06:40:02Z" managedFields: - apiVersion: v1 fieldsType: FieldsV1 fieldsV1: f:data: .: {} f:password: {} f:username: {} f:type: {} manager: kubectl-create operation: Update time: "2024-12-18T06:40:02Z" name: my-secret namespace: default resourceVersion: "1296147" uid: 263cbea3-05e3-4109-b789-24eee920c89f type: Opaque

根据键值对创建secret

[root@master-1 bar]# kubectl create secret generic my-secret-k-v --from-literal=key1=supersecret --from-literal=key2=topsecret
secret/my-secret-k-v created

[root@master-1 bar]# kubectl describe secret my-secret-k-v
Name:         my-secret-k-v
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
key1:  11 bytes
key2:  9 bytes
[root@master-1 bar]# kubectl get secret my-secret-k-v -oyaml apiVersion: v1 data: key1: c3VwZXJzZWNyZXQ= key2: dG9wc2VjcmV0 kind: Secret metadata: creationTimestamp: "2024-12-18T07:21:15Z" managedFields: - apiVersion: v1 fieldsType: FieldsV1 fieldsV1: f:data: .: {} f:key1: {} f:key2: {} f:type: {} manager: kubectl-create operation: Update time: "2024-12-18T07:21:15Z" name: my-secret-k-v namespace: default resourceVersion: "1301146" uid: 07777af1-ef58-4476-837b-4e49fb8bd919 type: Opaque

使用文件和文字的组合创建secret

[root@master-1 bar]# ll /root/.ssh/
id_rsa       id_rsa.pub   known_hosts
[root@master-1 bar]# ll /root/.ssh/id_rsa.pub
-rw-r--r--. 1 root root 395 10月 31 10:47 /root/.ssh/id_rsa.pub

[root@master-1 bar]#  kubectl create secret generic my-secret-file-kv  --from-file=ssh-privatekey=/root/.ssh/id_rsa.pub --from-literal=passphrase=topsecret
secret/my-secret-file-kv created
[root@master-1 bar]# kubectl get secret my-secret-file-kv -oyaml apiVersion: v1 data: passphrase: dG9wc2VjcmV0 ssh-privatekey: c3NoLXJzYU1dLVRNOWN...dEBtYXN0ZXItMQo= # 将整个文件内容加密作为key kind: Secret metadata: creationTimestamp: "2024-12-18T07:26:20Z" managedFields: - apiVersion: v1 fieldsType: FieldsV1 fieldsV1: f:data: .: {} f:passphrase: {} f:ssh-privatekey: {} f:type: {} manager: kubectl-create operation: Update time: "2024-12-18T07:26:20Z" name: my-secret-file-kv namespace: default resourceVersion: "1301764" uid: e4c54a58-2452-4b3e-add4-4afd5a8fc148 type: Opaque
[root@master-1 bar]# cat /root/.ssh/id_rsa.pub ssh-rsa AAAAB3Nza...ccJRQLfs9Sr78pfm+BHcuF root@master-1
[root@master-1 bar]# echo c3NoLX...9vdEBtYXN0ZXItMQo= |base64 --decode ssh-rsa AAAAB3NzaC1y...Kd4nrHcuF root@master-1 [root@master-1 bar]# kubectl describe secret my-secret-file-kv Name: my-secret-file-kv Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== passphrase: 9 bytes ssh-privatekey: 395 bytes

从环境变量文件创建secret

 准备文件

[root@master-1 secret]# cat userinfo.txt
USERNAME=root
PASSWORD=123456..
SERVER=192.168.43.129
PORT=6443

创建

[root@master-1 secret]# kubectl create secret generic mysql-secret-env  --from-env-file=userinfo.txt
secret/mysql-secret-env created

[root@master-1 secret]# kubectl describe secret mysql-secret-env
Name:         mysql-secret-env
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
PASSWORD:  8 bytes
PORT:      4 bytes
SERVER:    14 bytes
USERNAME:  4 bytes

[root@master-1 secret]# kubectl get secret mysql-secret-env -oyaml
apiVersion: v1
data:
  PASSWORD: MTIzNDU2Li4=
  PORT: NjQ0Mw==
  SERVER: MTkyLjE2OC40My4xMjk=
  USERNAME: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: "2024-12-18T07:40:05Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:PASSWORD: {}
        f:PORT: {}
        f:SERVER: {}
        f:USERNAME: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-12-18T07:40:05Z"
  name: mysql-secret-env
  namespace: default
  resourceVersion: "1303446"
  uid: 66179975-a4a2-4aac-860a-1550b5c06807
type: Opaque

# 解析 [root@master-1 secret]# echo 'MTIzNDU2Li4=' |base64 --decode |xargs echo 123456.. [root@master-1 secret]# echo NjQ0Mw== |base64 --decode |xargs echo 6443 [root@master-1 secret]# echo MTkyLjE2OC40My4xMjk= |base64 --decode |xargs echo 192.168.43.129 [root@master-1 secret]# echo cm9vdA== |base64 --decode |xargs echo root [root@master-1 secret]# kubectl describe secret mysql-secret-env Name: mysql-secret-env Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== PORT: 4 bytes SERVER: 14 bytes USERNAME: 4 bytes PASSWORD: 8 bytes

secret使用

 

 

 

 

 

 

 

3. 创建TLS类型的secret

创建证书请求配置文件

[root@master-1 openssl]# cat openssl.cfg
# 该部分配置如何生成证书请求(CSR)
[ req ]
default_bits        = 2048              # 密钥的默认长度(例如 2048 位 RSA 密钥)
default_md          = sha256            # 证书签名使用的哈希算法
default_keyfile     = server.key        # 默认的私钥输出文件
prompt              = no                # 是否提示用户输入主题信息 (no 表示自动填充)
encrypt_key         = no                # 是否加密私钥(yes 加密,no 不加密)
distinguished_name  = req_distinguished_name # 指定主题信息部分的名称
req_extensions      = v3_req            # 扩展字段的配置部分名称

# 该部分定义证书的 主题信息(Subject),如国家、组织、域名等
[ req_distinguished_name ]
C   = CN                      # 国家代码(例如 CN 为中国)
ST  = SX                   # 省/州名称
L   = ShangHai                    # 城市/地区
O   = KN                      # 组织名称
OU  = KN                      # 组织单位名称
CN  = rentlearn.com                    # 通用名称(Common Name),通常是域名

# 该部分用于定义 扩展字段,如 subjectAltName
[ v3_req ]
subjectAltName = @alt_names   # 使用 [alt_names] 部分的配置

# 该部分定义 subjectAltName 的具体内容,允许证书绑定多个域名或 IP 地址
[ alt_names ]
DNS.1 = rentlearn.com           # 第一个域名
DNS.2 = www.rentlearn.com       # 第二个域名
DNS.3 = sub.rentlearn.com       # 第三个域名
IP.1  = 192.168.43.130        # 第一个 IP 地址

 创建证书

openssl genpkey -algorithm RSA -out server.key -pkeyopt rsa_keygen_bits:4096
openssl req -new -key server.key -out server.csr -config openssl.cfg
openssl x509 -req -days 365  -in server.csr -CA cert.crt -CAkey ca.key -CAcreateserial -out server.crt  -extensions v3_req -extfile openssl.cfg

创建secret

kubectl create secret tls -n monitor prometheus-tls-secret --key=server.key --cert=server.crt

 查看secret

[root@master-1 openssl]# kubectl describe secret -n monitor prometheus-tls-secret
Name:         prometheus-tls-secret
Namespace:    monitor
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/tls

Data
====
tls.crt:  1939 bytes
tls.key:  3268 bytes

[root@master-1 openssl]# kubectl get secret -n monitor prometheus-tls-secret -oyaml
apiVersion: v1
data:
  tls.crt: LS0tLS1CRUdJS8KQm1UdgotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
  tls.key: LS0tLS1CHNEZZcjhhSFNtdgotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==
kind: Secret
metadata:
  creationTimestamp: "2024-12-18T04:25:42Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:tls.crt: {}
        f:tls.key: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2024-12-18T04:25:42Z"
  name: prometheus-tls-secret
  namespace: monitor
  resourceVersion: "1279764"
  uid: 1e435780-706e-495d-9793-34129b0a5bed
type: kubernetes.io/tls

配置secret

[root@master-1 openssl]# cat /opt/prometheus-k8s/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: monitor
  name: prometheus-ingress
spec:
  tls:
    - hosts:
      - www.rentlearn.com
      - sub.rentlearn.com
      - test.rentlearn.com
  ingressClassName: nginx
  rules:
  - host: test.rentlearn.com
    http:
      paths:
        - pathType: Prefix
          backend:
            service:
              name: prometheus
              port:
                number: 9090
          path: /

 

 

标签:kubectl,default,创建,nginx,secret,master,k8s,root
From: https://www.cnblogs.com/rtnb/p/18615157

相关文章

  • k8s service 轮巡方式rr hash
    在Kubernetes(k8s)中,Service对象用于定义如何访问Pod的策略,包括负载均衡算法。轮询(RoundRobin,简称rr)和哈希(Hash)是两种常见的负载均衡策略。1.**轮询(RoundRobin,rr)**:-这是默认的负载均衡策略,按照顺序将请求分配给后端的Pod。-当创建Service后,kube-proxy会为Service......
  • 基于k8s环境pulsar集群之一:pulsar-manager部署
    目录一:pulsar-manager安装说明二:pulsar-manager环境四:pulsar-manager部署步骤1.安装postgres2.创建pulsar-manager库3.验证pulsar-manger创建成功4.执行安装pulsar-manger 4.1.创建pvc  4.2.创建svc,deployment4.3.执行pulsar-manager-pvc4.4.验证pulsar-manage......
  • 鸿蒙Next创建自定义组件总结
    一、引言在鸿蒙Next开发中,自定义组件是构建高效、可维护UI的重要组成部分。它具有可组合、可重用以及数据驱动UI更新等特点,能帮助开发者更好地实现代码复用、业务逻辑与UI分离等目标。本文将详细总结创建自定义组件的相关知识,包括其基本结构、成员函数/变量、参数规定、build()函......
  • vite 创建react hook项目
    create-vite安装create-vite是一个用于快速搭建Vite项目的脚手架工具。你可以通过npm(Node包管理器)来安装它。通常情况下,你不需要单独安装create-vite,因为你可以直接使用npx(Node包运行器)来运行它。npx是npm5.2.0版本及以上版本自带的一个工具,用于执行在本地或远程注册......
  • 使用 Golang 和模板引擎创建网站
    使用Golang和模板引擎创建网站原创 源自开发者 源自开发者 2024年12月17日12:57 广东在过去,人们通常使用HTML、CSS和JavaScript来构建网站,同时在后端使用PHP。如今,已经有许多JavaScript框架可供选择,比如React.js、Next.js、Vue.js、Nuxt、Svelte、SvelteKit......
  • ln -s的创建与删除,重要!
    今天幸亏是自己的文件,没造成什么后果。不然真的很容易误删除!先说删除!一定要看。删除就是删一个链接,所以根本不需要加-r,加-r开始递归,就已经在错误的路上狂奔了!一个链接而已,肯定不用-r。所以就是仅仅删名字,比如,rmdata就行。data是一个链接的目录,但是仅删除这个文件就好:rmdata......
  • 第47节 ArkTS 创建自定义组件
    在ArkTS中创建自定义组件是一个相对简单但功能强大的过程。以下是如何在ArkTS中创建和使用自定义组件的详细步骤:一、定义自定义组件1.使用@Component注解:为了注册一个组件,使其能够在其他文件中被引用,你需要使用@Component注解。例如:@ComponentstructMyComp......
  • SQL Server创建用户一直提示用户已存在的解决办法
    背景:复制的老数据库,创建账号onlyread时,一直提示数据库里有这个用户名。报错如下:“用户、组或角色'onlyread'在当前数据库中已存在。”解决方法:1.查询数据库,是否有这个用户--查询是否存在指定的用户、组或者角色SELECT*FROMsys.database_principalsWHEREname='only......
  • Maven简单使用说明(在IDEA中创建一个基于POI的处理Excel文件的Maven项目)
    目录Maven简介(AI生成的内容)一、环境变量设置二、设置Maven的本地jar仓库位置三、设置maven配置文件settings.xml3.1配置本地仓库3.2配置镜像仓库URL3.3配置JDK版本四、在IDEA中配置maven并创建maven项目4.1设置IDEA的全局配置4.2在IDEA中创建maven项目4.3创建一个使用POI处......
  • 在CodeBolcks+Windows API下的C++面向对象的编程教程——用面向对象的方法改写用向导
    0.前言我想通过编写一个完整的游戏程序方式引导读者体验程序设计的全过程。我将采用多种方式编写具有相同效果的应用程序,并通过不同方式形成的代码和实现方法的对比来理解程序开发更深层的知识。了解我编写教程的思路,请参阅体现我最初想法的那篇文章中的“1.编程计划”:学习编程......