Kubernetes进阶实战读书笔记:配置容器应用(secret)

一、secret概述

 1、注意事项

secret资源的功能类似于、但它专用于存放敏感数据、例如密码、数字证书、私钥、令牌和SSH key等

需要注意的是、在master节点上、secret对象以非加密的格式存储于etcd中,因此管理员必须加以精心管控以确保敏感数据的机密性、必须确保etcd集群节点间以及API server的安全通信、etcd服务的访问授权、还包括用户访问API server时的授权、因为拥有创建pod资源的用户都可以使用secret资源并能通过pod中的容器访问其数据

2、两种用途

一是作为存储卷注入到pod上由容器应用程序所使用
二是用于kubelet为POD里的容器拉取镜像时向私有仓库提供认证信息
不过后面使用ServiceAccount资源自建的secret对象是一种更安全性的方式

二、创建secret资源(命令式创建)

1、generic标识符创建的secret对象为Opaque类型

1、创建

[root@master chapter8]# kubectl create secret generic mysal-auth --from-literal=username=root --from-literal=password=ikubernetes
secret/mysal-auth created

2、验证

查看新建的资源属性信息、由下面的命令及输出结果可以看出、以generic标识符创建的secret对象为Opaque类型、其键值数据会以base64的编码格式进行保存和打印

[root@master chapter8]# kubectl get secrets mysal-auth -o yaml
apiVersion: v1
data:
  password: aWt1YmVybmV0ZXM=
  username: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: "2020-09-01T07:22:58Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:password: {}
        f:username: {}
      f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-09-01T07:22:58Z"
  name: mysal-auth
  namespace: default
  resourceVersion: "6309979"
  selfLink: /api/v1/namespaces/default/secrets/mysal-auth
  uid: 43573f71-255d-4dc7-acd8-e3e5a42d55ee
type: Opaque

不过kubernetes系统的secrets对象的base64编码的数据并非加密格式、许多相关的工具程序均可轻松完成解码、如下面所示的base64命令

[root@master chapter8]# echo aWt1YmVybmV0ZXM= | base64 -d
ikubernetes[root@master chapter8]# 

2、创建用于ssh认证的secrets对象 

对于本身以存储与文件中的数据、也可以在创建generic格式secrets的对象时使用"--from-file"、选项从文件中直接进行加载、例如创建用于ssh认证的secrets对象时、如果尚且没有认证信息你文件、则需要首先使用命令生成一堆认证文件 

[root@master chapter8]# ssh-keygen -t rsa -P '' -f ${HOME}/.ssh/id_rsa
Generating public/private rsa key pair.
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? Y
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:4TyF9Zx0hBkWcvICRm4OrWPz3Na1YNcSNfa3eCARWPc root@master
The key's randomart image is:
+---[RSA 2048]----+
|       .+ *+BBoo.|
|       + = X=oo.o|
|      . * o.=..Eo|
|       B o .. ooo|
|      = S   o.+o.|
|     . = o o +.o |
|        o o . .  |
|         .       |
|                 |
+----[SHA256]-----+

加载文件内容生成secrets对象

[root@master chapter8]# kubectl create secret generic ssh-key-secret --from-file=ssh-privatekey=${HOME}/.ssh/id_rsa --from-file=ssh-publickey=${home}/.ssh/id_rsa.pub
Error from server (AlreadyExists): secrets "ssh-key-secret" already exists

3、生成基于私钥和数字证书文件创建用于SSL/TLS通信的secrets对象 

生成私钥和自签证书

[root@master chapter8]# umask 077;openssl genrsa -out nginx.key 2048
Generating RSA private key, 2048 bit long modulus
.......................+++
...+++
e is 65537 (0x10001)
[root@master chapter8]# ll nginx.*
-rw------- 1 root root 1679 Sep  1 15:36 nginx.key

生成secrets对象

[root@master chapter8]# openssl req -new -x509 -key nginx.key -out nginx.crt -subj /C=CN/ST=Beijing/L=Beijing/O=DevOps/CN=www.iliunx.io
[root@master chapter8]# ll nginx.*
-rw------- 1 root root 1285 Sep  1 15:38 nginx.crt
-rw------- 1 root root 1679 Sep  1 15:36 nginx.key

注意其类型应该为“kubernetes.io/tls” 例如细面命令结果中显示

[root@master chapter8]# kubectl create secret tls nginx-ssl --key=./nginx.key --cert=./nginx.crt 
secret/nginx-ssl created
[root@master chapter8]# kubectl get secrets nginx-ssl 
NAME        TYPE                DATA   AGE
nginx-ssl   kubernetes.io/tls   2      13s

三、创建secret资源(清单式创建)

1、字段详解

[root@master chapter8]# kubectl explain secret
KIND:     Secret
VERSION:  v1

DESCRIPTION:
     Secret holds secret data of a certain type. The total bytes of the values
     in the Data field must be less than MaxSecretSize bytes.

FIELDS:
   apiVersion	<string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   data	<map[string]string>
   #"key:value" 格式的数据、通产格式敏感信息、数据格式需要是以Base64格式编码的字符串、因此需要用户实现完成编码
     Data contains the secret data. Each key must consist of alphanumeric
     characters, '-', '_' or '.'. The serialized form of the secret data is a
     base64 encoded string, representing the arbitrary (possibly non-string)
     data value here. Described in https://tools.ietf.org/html/rfc4648#section-4

   immutable	<boolean>
     Immutable, if set to true, ensures that data stored in the Secret cannot be
     updated (only object metadata can be modified). If not set to true, the
     field can be modified at any time. Defaulted to nil. This is an alpha field
     enabled by ImmutableEphemeralVolumes feature gate.

   kind	<string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata	<Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   stringData	<map[string]string>
   #以明文格式(非Base64编码)定义的"key:value" 数据;无须用户实现对数据进行Base64编码,而是在创建为Secret对象时自动进行编码并保存于data字段中stringData字段中的明文不会被API Servers输出,不过若是使用"kubectl apply" 命令进行的创建、那么注解信息中还是可能会直接输出这些信息的
     stringData allows specifying non-binary secret data in string form. It is
     provided as a write-only convenience method. All keys and values are merged
     into the data field on write, overwriting any existing values. It is never
     output when reading from the API.

   type	<string>
   #为了便于配置文件中的资源定义示例、其使用stringData提供了明文格式的键值数据、从而免去了事先进行手动编码的麻烦
     Used to facilitate programmatic handling of secret data.

2、secret-demo.yaml 定义示例

其使用stringData提供了明文格式的键值数据、从而免去了事先进行手动编码的麻烦

[root@master chapter8]# cat secret-demo.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: secret-demo
stringData:
  username: redis
  password: redispass
type: Opaque

secret对象也是kubernetes系统的"一等公民"、因此使用标准资源创建命令即可完成其创建、相比较来说、基于清单文件将保存于文件中的敏感信息创建secret对象时,用户首先需要将敏感信息独处、转为编码Base64编码格式而后再将其创建为清单文件,过程繁琐、反而不如命令式创建来的便捷、不过、如果存在多次创建或重构之需,那么将其保存为配置清单也是形式所需

四、secret存储卷

1、资源清单

[root@master chapter8]# cat secret-demo.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: secret-demo
stringData:
  username: redis
  password: redispass
type: Opaque
[root@master chapter8]# cat secret-volume-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: secret-volume-demo
  namespace: default
spec:
  containers:
  - image: nginx:alpine
    name: web-server
    volumeMounts:
    - name: nginxcert
      mountPath: /etc/nginx/ssl/
      readOnly: true
  volumes:
  - name: nginxcert
    secret:
      secretName: nginx-ssl

2、创建验证

[root@master chapter8]# kubectl apply -f secret-volume-pod.yaml 
pod/secret-volume-demo created
[root@master chapter8]# kubectl exec secret-volume-demo ls /etc/nginx/ssl
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
tls.crt
tls.key

五、imagePullSecret资源对象

1、创建docker-registry类型的对象

[root@master chapter8]# kubectl create secret docker-registry local-registry --docker-username=Ops --docker-password=Opspasil=ops@ilinux.io

2、打印类型信息

[root@master chapter8]# kubectl get secrets local-registry 
NAME             TYPE                             DATA   AGE
local-registry   kubernetes.io/dockerconfigjson   1      13s

3、通过字段使用此secrets 对象  

资源清单

[root@master chapter8]# cat secret-imagepull-pod.yaml.0
apiVersion: v1
kind: Pod
metadata:
  name: secret-imagepull-demo
  namespace: default
spec:
  imagePullSecrets:
  - name: local-registry
  containers:
  - image: registry.ikubernetes.io/dev/myimage
    name: myapp

验证

[root@master chapter8]# kubectl get pods|grep secret-imagepull-demo
secret-imagepull-demo     0/1     ImagePullBackOff   0          23h

[root@master chapter8]# kubectl describe pod secret-imagepull-demo
Name:         secret-imagepull-demo
Namespace:    default
Priority:     0
Node:         node1/192.168.118.19
Start Time:   Tue, 01 Sep 2020 15:47:16 +0800
Labels:       <none>
Annotations:  Status:  Pending
IP:           10.244.1.57
IPs:
  IP:  10.244.1.57
Containers:
  myapp:
    Container ID:   
    Image:          registry.ikubernetes.io/dev/myimage
    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-pwl2t (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-pwl2t:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-pwl2t
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                     From            Message
  ----     ------   ----                    ----            -------
  Warning  Failed   8m59s (x6246 over 23h)  kubelet, node1  Error: ImagePullBackOff
  Normal   BackOff  4m6s (x6268 over 23h)   kubelet, node1  Back-off pulling image "registry.ikubernetes.io/dev/myimage"
posted @ 2020-09-05 23:12  活的潇洒80  阅读(83)  评论(0编辑  收藏