天天看点

k8s资源secret和ConfigMap的相关详解一、secret相关简介

secret

  • 一、secret相关简介
    • 二、secret资源的使用
      • 三、Secret实践k8s连接Harbor
        • 四、ConfigMap相关介绍
          • 五、ConfigMap资源的使用

一、secret相关简介

1.Secret资源的作用

用来保存一些敏感信息,比如MySQL服务的账号和密码,或者一些秘钥、证书等。

2.使用示例

用户名: root

密码:123.com
           

将上述信息保存为secret资源有以下几种方法可供使用。

(1)- -from-literal

[[email protected] ~]# kubectl create secret generic secret1 --from-literal=username=root --from-literal=password=123.com
[[email protected] ~]# kubectl get secrets
           

注意

generic是一种算法;

一个--from-literal语句只能保存一条信息;
           

使用Describe命令查看其详细信息,可以看到对应的key值,却看不到详细values值。因为创建的时候,我们给这个数据做了一个加密动作。

[[email protected] ~]# kubectl describe secrets secret1
Name: secret1
Namespace: default
Labels: <none>
Annotations: <none>

Type: Opaque

Data
====
password: 7 bytes
username: 4 bytes
           

(2)- -from-file

[[email protected] secret]# echo root > username
[[email protected] secret]# echo 123.com > password
[[email protected] secret]# kubectl create secret generic secret2 --from-file=username --from-file=password
[[email protected] secret]# kubectl get secrets
           

注意

--from-file的方式中的每个文件中也是只能够保存一条信息
           

(3)- -from-env-file

[[email protected] secret]# vim env.txt
username=root
password=123.com
[[email protected] secret]# kubectl create secret generic secret3 --from-env-file=env.txt
           

注意

这种保存数据的方式比第二种要方便的多。不过文件中每一行只能记录一条数据(key=value);
           

(4)通过yaml文件创建

在创建yaml文件的时候,为了避免能直接看到我们保存的数据,所以我们通常会为保存的数据进行加密。

[[email protected] secret]# echo root | base64
cm9vdAo=
[[email protected] secret]# echo 123.com | base64
MTIzLmNvbQo=
[[email protected] secret]# vim secret4.yaml
apiVersion: v1
kind: Secret
metadata:
  name: secret4
data:
  username: cm9vdAo=
  password: MTIzLmNvbQo=
[[email protected] secret]# kubectl apply -f secret4.yaml
           

注意:即使在保存数据前对要保存的数据做了加密处理,但base64这种方法也不是绝对的安全。比如上边我们用base64这种方法得到的乱码字符串,就可以使用–decode解码。

[[email protected] secret]# echo -n cm9vdAo= | base64 --decode
root
           

二、secret资源的使用

1.通过volume的方式

示例:创建一个Pod资源,用volume的方式使用之前创建的secret1。

[[email protected] secret]# vim mypod.yaml
kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    volumeMounts:
    - name: test-volume
      mountPath: "/etc/volume"
      readOnly: true
  volumes:
  - name: test-volume
    secret:
      secretName: secret1
           

通过yalm文件运行此Pod资源,然后进入Pod对应的挂载目录验证是否有secret资源保存的数据。

[[email protected] secret]# kubectl apply -f mypod.yaml
[[email protected] secret]# kubectl get pod
[[email protected] secret]# kubectl exec mypod cat /etc/volume/username
root
[[email protected] secret]# kubectl exec mypod cat /etc/volume/password
123.com
           

注意:以volume的挂载方式去使用secret资源,它会随着secret资源对象数据的改变而改变。所以通常用volume挂载的时候,为了保证secret资源的安全,在挂载的使用都是只读挂载(readOnly)。

我们也可以自定义存放数据的文件名。比如上述Pod资源可以更改为

[[email protected] secret]# vim mypod.yaml
kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    volumeMounts:
    - name: test-volume
      mountPath: "/etc/volume"
      readOnly: true
  volumes:
  - name: test-volume
    secret:
      secretName: secret1
      items:
      - key: username
        path: mygroup/my-username
      - key: password
        path: mygroup/my-passwd
[[email protected] secret]# kubectl apply -f mypod.yaml
           

在对应的位置仍然可以查看到我们更改过后的数据,数据会实时同步更新。

[[email protected] secret]# kubectl exec -it mypod sh
/etc/volume # ls mygroup/
my-passwd my-username
/etc/volume # pwd
/etc/volume
           

2.用环境变量的方式

同样我们更改一下上述的Pod,将它引用secret资源对象的方式更改为环境变量的方式。

[[email protected] secret]# vim mypod.yaml
kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    env:
    - name: SECRET_USERNAME
      valueFrom:
        secretKeyRef:
          name: secret1
          key: username
    - name: SECRET_PASSWORD
      valueFrom:
        secretKeyRef:
          name: secret1
          key: password
           

运行此yaml文件并进入Pod去验证一下变量的值是否正确。

[[email protected] secret]# kubectl apply -f mypod.yaml
[[email protected] secret]# kubectl get pod
[[email protected] secret]# kubectl exec -it mypod sh
/ # echo $SECRET_USERNAME -n
root
/ # echo $SECRET_PASSWORD -n
123.com
           

注意:用环境变量的方式也可以正确引用secret资源,但是它并不会像Volume的方式一样,它引用数据不会进行动态的更新。

资源在创建的过程中可以直接使用命令的方式,也可以使用yaml文件的方式。虽然yaml文件的方式创建相对比较麻烦,但是它会将我们在创建对应资源的时候的基本状态做一个保存。

我们可以先使用命令的方式创建出来对应的资源,然后将此资源另存为一个yaml文件。比如我们之前创建的secret2

[[email protected] secret]# kubectl get secrets secret2 -o yaml > secret2.yaml
[[email protected] secret]# cat secret2.yaml
apiVersion: v1
data:
  password: MTIzLmNvbQo=
  username: cm9vdAo=
kind: Secret
metadata:
  creationTimestamp: "2020-04-27T06:39:47Z"
  name: secret2
  namespace: default
  resourceVersion: "12904"
  selfLink: /api/v1/namespaces/default/secrets/secret2
  uid: 23b294ab-0ef8-411f-825b-b3c69f14115e
type: Opaque
           

三、Secret实践k8s连接Harbor

假设此时有一个deployment需要用到私有镜像,已知Harbor地址为:192.168.229.214,首先应该确认各节点都修改了/usr/lib/systemd/system/docker.service文件,或者在/etc/docker/daemon.json文件中添加过私有仓库地址。因为登录Harbor需要用户名和密码,所以我们可以先创建一个Secret文件,将Harbor的信息保存到k8s集群中。

1.先登录harbor仓库

[[email protected] ~]# vim /usr/lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd --insecure-registry 192.168.229.214
[[email protected] ~]# systemctl daemon-reload
[[email protected] ~]# systemctl restart docker
[[email protected] ~]# vim /usr/lib/systemd/system/docker.service
[[email protected] ~]# systemctl daemon-reload
[[email protected] ~]# systemctl restart docker.service
[[email protected] ~]# vim /usr/lib/systemd/system/docker.service
[[email protected] ~]# systemctl daemon-reload
[[email protected] ~]# systemctl restart docker
[[email protected] harbor]# docker-compose restart
Restarting nginx              ... done
Restarting harbor-portal      ... done
Restarting harbor-jobservice  ... done
Restarting harbor-core        ... done
Restarting harbor-adminserver ... done
Restarting registryctl        ... done
Restarting registry           ... done
Restarting harbor-db          ... done
Restarting redis              ... done
Restarting harbor-log         ... done
[[email protected] ~]# docker login -u admin -p Harbor12345 192.168.229.214
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
           

2.查看秘钥登录数据

[[email protected] ~]# cat .docker/config.json
{
	"auths": {
		"192.168.229.214": {
			"auth": "YWRtaW46SGFyYm9yMTIzNDU="
		}
	},
	"HttpHeaders": {
		"User-Agent": "Docker-Client/18.09.0 (linux)"
	}
}
           

3.进行加密

[[email protected] ~]# cat .docker/config.json | base64
ewoJImF1dGhzIjogewoJCSIxOTIuMTY4LjIyOS4yMTQiOiB7CgkJCSJhdXRoIjogIllXUnRhVzQ2U0dGeVltOXlNVEl6TkRVPSIKCQl9Cgl9LAoJIkh0dHBIZWFkZXJzIjogewoJCSJVc2VyLUFnZW50IjogIkRvY2tlci1DbGllbnQvMTguMDkuMCAobGludXgpIgoJfQp9
           

4.创建secret资源

[[email protected] ~]# mkdir secret
[[email protected] ~]# cd secret/
[[email protected] secret]# vim secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: harbor-secret
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: ewoJImF1dGhzIjogewoJCSIxOTIuMTY4LjIyOS4yMTQiOiB7CgkJCSJhdXRoIjogIllXUnRhVzQ2U0dGeVltOXlNVEl6TkRVPSIKCQl9Cgl9LAoJIkh0dHBIZWFkZXJzIjogewoJCSJVc2VyLUFnZW50IjogIkRvY2tlci1DbGllbnQvMTguMDkuMCAobGludXgpIgoJfQp9
[[email protected] secret]# kubectl apply -f secret.yaml
           

5.创建Deployment资源引用secret资源

[[email protected] secret]# vim deploy.yaml
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: test
spec:
  replicas: 2
  template:
    metadata:
      labels:
        test: registry
    spec:
      containers:
      - name: test
        image: 192.168.229.214/test/httpd:v1
        imagePullPolicy: Always
      imagePullSecrets:
      - name: harbor-secret
[[email protected] secret]# kubectl apply -f deploy.yaml
[[email protected] secret]# kubectl get pod
NAME                    READY   STATUS    RESTARTS   AGE
test-6d9c69c9f8-7nvlv   1/1     Running   0          42s
test-6d9c69c9f8-sc7w4   1/1     Running   0          42s
           

四、ConfigMap相关介绍

与secret资源一样,configMap也可以保存一些数据信息。不同的是,secret资源保存的是相对敏感的信息或者是秘钥等,而configMap保存的是一些明文的数据。

1.使用示例

user1=admin

user2=root
           

(1)- -from-literal

[[email protected] ~]# mkdir configmap
[[email protected] ~]# cd configmap/
[[email protected] configMap]# kubectl create configmap myconfigmap1 --from-literal=user1=admin --from-literal=user2=root
[[email protected] configmap]# kubectl describe configmaps myconfigmap1
Name:         myconfigmap1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
user1:
----
admin
user2:
----
root
Events:  <none>
           

(2)- -from-file

[[email protected] configMap]# echo admin > user1
[[email protected] configMap]# echo root > user2
[[email protected] configMap]# kubectl create configmap myconfigmap2 --from-file=user1 --from-file=user2
[[email protected] configMap]# kubectl describe configmaps myconfigmap2
Name: myconfigmap2
Namespace: default
Labels: <none>
Annotations: <none>

Data
====
user2:
----
root

user1:
----
admin

Events: <none>
           

(3)- -from-env-file

[[email protected] configMap]# cat > user.txt <<EOF
> user1=admin
> user2=root
> EOF
[[email protected] configMap]# kubectl create configmap myconfigmap3 --from-env-file=user.txt
[[email protected] configMap]# kubectl describe configmaps myconfigmap3
Name: myconfigmap3
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
user2:
----
root
user1:
----
admin
Events: <none>
           

(4)通过yaml文件的方式

[[email protected] configmap]# vim myconfigmap4.yaml
kind: ConfigMap
apiVersion: v1
metadata:
  name: myconfigmap4
data:
  user1: admin
  user2: root
[[email protected] configmap]# kubectl apply -f myconfigmap4.yaml
           
五、ConfigMap资源的使用

示例:创建一个Pod资源,引用上述myconfigmap1资源。

1.以volume的方式引用

[[email protected] configmap]# vim pod1.yaml
kind: Pod
apiVersion: v1
metadata:
  name: pod1
spec:
  containers:
  - name: pod1
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    volumeMounts:
    - name: volume1
      mountPath: "/tmp/volume"
      readOnly: true
  volumes:
  - name: volume1
    configMap:
      name: myconfigmap1
[[email protected] configmap]# kubectl apply -f pod1.yaml
[[email protected] configmap]# kubectl get pod
NAME                    READY   STATUS    RESTARTS   AGE
pod1                    1/1     Running   0          14s
[[email protected] configmap]# kubectl exec -it pod1 sh
/ # cat /tmp/volume/user1 -n
     1	admin
/ # cat /tmp/volume/user2 -n
     1	root
           

这里假如我们将myconfigmap1对应的user1的值进行更改,会看到Pod内对应的值也会进行动态的更新。

[[email protected] configmap]# kubectl edit configmaps myconfigmap1
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  user1: snow
  user2: root
kind: ConfigMap
metadata:
  creationTimestamp: "2020-11-10T08:02:43Z"
  name: myconfigmap1
  namespace: default
  resourceVersion: "9180"
  selfLink: /api/v1/namespaces/default/configmaps/myconfigmap1
  uid: 88719cef-fd57-4bfd-905f-c807d404ca3a
  [[email protected] configmap]# kubectl edit configmaps myconfigmap1
configmap/myconfigmap1 edited
[[email protected] configmap]# kubectl exec -it pod1 sh
/ # cat /tmp/volume/user1 -n
     1	snow
           

2.环境变量的方式引用

[[email protected] configmap]# vim pod2.yaml
kind: Pod
apiVersion: v1
metadata:
  name: pod2
spec:
  containers:
  - name: pod2
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    env:
    - name: USER_1
      valueFrom:
        configMapKeyRef:
          name: myconfigmap1
          key: user1
    - name: USER_2
      valueFrom:
        configMapKeyRef:
          name: myconfigmap1
          key: user2
[[email protected] configmap]# kubectl apply -f pod2.yaml
[[email protected] configmap]# kubectl get pod
NAME                    READY   STATUS    RESTARTS   AGE
pod1                    1/1     Running   0          12m
pod2                    1/1     Running   0          36s
[[email protected] configmap]# kubectl exec -it pod2 sh
/ # echo $USER_1
snow
/ # echo $USER_2
root
           

这里再把user1对应的更改为admin,再次验证Pod内的变量值仍然不会变,说明环境变量的方式不论引用的什么资源,都不会动态的更新。

[[email protected] configmap]# kubectl edit configmaps myconfigmap1
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  user1: admin
  user2: root
kind: ConfigMap
metadata:
  creationTimestamp: "2020-11-10T08:02:43Z"
  name: myconfigmap1
  namespace: default
  resourceVersion: "14597"
  selfLink: /api/v1/namespaces/default/configmaps/myconfigmap1
  uid: 88719cef-fd57-4bfd-905f-c807d404ca3a
[[email protected] configmap]# kubectl exec -it pod2 sh
/ # echo $USER_1
snow
           

继续阅读