k8s - (|) Configmap configuration, Secret encryption

I Configmap

The ConfigMap function is in kubernetes1 Introduced in version 2, many applications read configuration information from configuration files, command-line parameters, or environment variables. The ConfigMap API provides us with a mechanism to inject configuration information into the container. ConfigMap can be used to save a single attribute, an entire configuration file or a JSON binary large object

Put the configuration information into the configmap object, and then import the configmap object into the object of pod to realize the operation of importing the configuration

Resource list creation

1. Create the resource list of ConfigMap

apiVersion: v1			# Version, which can be viewed through kubectl explain cm
kind: ConfigMap
metadata:
  name: special-config	# ConfigMap name
  namespace: default	# Namespace
data:					# key: value structure, configuration data
  special.how: very
  special.type: charm


kubectl apply -f comfigmap.yaml

2. Create with directory

  1. Create / root / k8s / yaml / configmap / game Properties file:
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30

  1. Create / root / k8s / yaml / configmap / UI Properties file
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

  1. Create configmap, - from file specifies that all files in the directory will be used to create a key value pair in configmap. The name of the key is the file name and the value is the content of the file
kubectl create configmap game-config --from-file=../configmap/

  1. View the created configmap (which can be abbreviated as cm):
$ kubectl get cm
NAME          DATA   AGE
game-config   2      6m40s

# View details
kubectl get cm game-config -o yaml
kubectl describe cm game-config

3. Create with file

You can create a ConfigMap from a single file by specifying the -- from file parameter as a file

The - from file parameter can be used multiple times. You can specify the two configuration files in the previous instance twice. The effect is the same as specifying the entire directory

kubectl create configmap game-config-2 --fromfile=game.properties

kubectl get configmaps game-config-2 -o yaml

4. Create with literal value

Create with text value and transfer configuration information with the -- from literal parameter. This parameter can be used multiple times. The format is as follows

kubectl create configmap special-config --from-literal=special.how=very --fromliteral=special.type=charm

kubectl get configmaps special-config -o yaml

Use ConfigMap in Pod

1. Use ConfigMap to replace environment variables

  1. Create two configmaps (configmap.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  special.how: very
  special.type: charm
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-config
  namespace: default
data:
  log_level: INFO

  1. Create pod
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
  - name: test-container
    image: wangyanglinux/myapp:v1
    command: [ "/bin/sh", "-c", "env" ]			# Print env
    env:										# Select the read key from ConfigMap and alias it
    - name: SPECIAL_LEVEL_KEY					# Key alias, where the value should be very
      valueFrom:
        configMapKeyRef:
          name: special-config					# Name of ComfigMap
          key: special.how						# The previous sentence specifies the key name in ConfigMap
    - name: SPECIAL_TYPE_KEY					# Key alias, where the value should be char
      valueFrom:
        configMapKeyRef:
          name: special-config					# Name of ComfigMap
          key: special.type						# The previous sentence specifies the key name in ConfigMap
    envFrom:									# Read all configurations directly from ConfigMap
    - configMapRef:
        name: env-config						# Name of ComfigMap
  restartPolicy: Never

  1. Viewing the log, you can see that the configuration in ConfigMap has been injected into the container

2. Use ConfigMap to set command line parameters

  1. Create ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  special.how: very
  special.type: charm

  1. Create pod
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
  - name: test-container
    image: wangyanglinux/myapp:v1
    command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]	#You can adjust the command when starting the Pod
    env:										# Select the read key from ConfigMap and alias it
    - name: SPECIAL_LEVEL_KEY					# Key alias, where the value should be very
      valueFrom:
        configMapKeyRef:
          name: special-config					# Name of ComfigMap
          key: special.how						# The previous sentence specifies the key name in ConfigMap
    - name: SPECIAL_TYPE_KEY					# Key alias, where the value should be char
      valueFrom:
        configMapKeyRef:
          name: special-config					# Name of ComfigMap
          key: special.type
  restartPolicy: Never

  1. view log
$ kubectl logs dapi-test-pod
very charm

3. Use ConfigMap through the data volume plug-in

Mount by Volume. The key name in ConfigMap is the file name, and the key value is the file content

Create ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  special.how: very
  special.type: charm

Create pod

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: wangyanglinux/myapp:v1
      command: ["/bin/sh", "-c", "cat /etc/config/special.how"]    # Print the contents of the files in the mount directory
      volumeMounts:                 # volume mount
        - name: config-volume       # Mount the volume specified below
          mountPath: /etc/config    # The directory to which to mount (the path in the container. In this directory, the file name is the key name, and the file content is the key value)
  volumes:
    - name: config-volume           # volume name
      configMap:                    # From ConfigMap
        name: special-config        # ConfigMap name
  restartPolicy: Never

Look at the log

$ kubectl logs dapi-test-pod
very

4. Hot update of configmap

Create a ConfigMap and Deployment:

apiVersion: v1
kind: ConfigMap
metadata:
  name: log-config
  namespace: default
data:
  log_level: INFO
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 1
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      containers:
        - name: my-nginx
          image: wangyanglinux/myapp:v1
          ports:
            - containerPort: 80
          volumeMounts:					# I don't understand the previous section using ConfigMap through data volume plug-in
            - name: config-volume
              mountPath: /etc/config	# There will be logs in this directory in the container_ Level this file, the content is INFO
      volumes:
        - name: config-volume
          configMap:
            name: log-config

View / etc / config / log_ Contents of level file

$ kubectl exec my-nginx-c484b98b4-sbls9 -it -- cat /etc/config/log_level
INFO

Modify ConfigMap

kubectl edit configmap log-config


Check / etc / config / log again_ Level file, you can see that the configuration in Pod has also been changed
Note: after updating ConfigMap:
Env s mounted with this ConfigMap will not be updated synchronously
The data in the Volume mounted with this ConfigMap will take a period of time (measured for about 10 seconds) to update synchronously

Let Pod scroll through updates
After the ConfigMap is updated, the corresponding file will not be overloaded. For example, when Nginx starts, it will load the configuration file once (the configuration file contains the relevant parameters of ConfigMap). After loading, no matter how the configuration file changes, Nginx will not load it again. Therefore, it is necessary to update the Pod after the ConfigMap is updated.

  1. You can force rolling updates to be triggered by modifying pod annotations
  2. Here we are spec.template. metadata. Add version/config in annotations to trigger rolling updates by modifying the time of version/config each time
kubectl patch deployment my-nginx --patch \
'{"spec": {"template": {"metadata": {"annotations":{"version/config": "20211110" }}}}}'

II Secret

reference resources

Secret solves the configuration problem of sensitive data such as password, token and key without exposing these sensitive data to the image or Pod Spec. Secret can be used as Volume or environment variable

Users can create secrets, and the system also creates some secrets.

There are three types of Secret:

  • Service Account: it is used to access Kubernetes API, which is automatically created by Kubernetes and automatically mounted to / run / secrets / Kubernetes.com of Pod IO / serviceaccount directory
  • Opaque: a Secret in base64 encoding format, which is used to store passwords, keys, etc. Low encryption
  • kubernetes.io/dockerconfigjson: used to store the authentication information of the private docker registry

To use secret, pod needs to reference secret. Pod can use secret in two ways:

  1. As a file in volume, it is mounted in one or more containers in the pod,
  2. Used when kubelet pulls the image for pod.

1. Service Account (not commonly used)

The Service Account is used to access the Kubernetes API, which is automatically created by Kubernetes and automatically mounted to / run / secrets / Kubernetes.com of Pod IO / serviceaccount directory

# 1. Find any Pod that needs to access the Kubernetes API
$ kubectl get pod -n kube-system
NAME                                   READY   STATUS    RESTARTS   AGE
kube-proxy-2pqkk                       1/1     Running   6          40d

# 2. View / run / secrets / kubernetes. In this Pod Files in io / serviceaccount directory
$ kubectl exec kube-proxy-2pqkk -n kube-system -it -- ls /run/secrets/kubernetes.io/serviceaccount
ca.crt: visit API Service Certificate at
namespace: Namespace
token: Authenticated key information

2. Opaque Secret

The data of Opaque type is a map type, and the value is required to be base64 encoding format:

(1) Create an opera secret

  1. The user name and password are encrypted with base64
$ echo -n admin | base64
YWRtaW4=
$ echo -n 123 | base64
MTIz

base64 encoding

$ echo -n YWRtaW4= | base64 -d
 admin 
  1. Create a Secret using an encrypted user name and password
apiVersion: v1			# kubectl explain secret view
kind: Secret
metadata:
  name: mysecret		# Secret name
type: Opaque			# Type of Secret
data:
  password: MTIz		# password
  username: YWRtaW4=	# user name

  1. View Secret
    Default token xxxxx: k8s by default, one will be created under each namespace for Pod mounting
$ kubectl get secret
NAME                  TYPE                                  DATA   AGE
default-token-fm46c   kubernetes.io/service-account-token   3      40d
mysecret              Opaque                                2      12s

(2) Mount Secret to Volume

Create Pod

apiVersion: v1
kind: Pod
metadata:
  labels:
    name: secret-test
  name: secret-test
spec:
  volumes:			# Create a volume
    - name: secrets		# Volume name
      secret:			# Scheme used by volume
        secretName: mysecret	# From mysecret created in the previous section
  containers:
    - image: wangyanglinux/myapp:v1
      name: db
      volumeMounts:		# Volume mount
        - name: secrets		# The above declared secrets are mounted
          mountPath: "/etc/secrets"		# Mounted directory (in container directory)
          readOnly: true	# Read only

see

# The user name and password in opera secret have been attached
$ kubectl exec secret-test -it -- ls /etc/secrets
password  username

# View the content and find that the content has been decrypted automatically
$ kubectl exec secret-test -it -- cat /etc/secrets/password
123
$ kubectl exec secret-test -it -- cat /etc/secrets/username
admin

(3) Export Secret to environment variable

Create Deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: pod-deployment
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: pod-deployment
    spec:
      containers:
        - name: pod-1
          image: wangyanglinux/myapp:v1
          ports:
            - containerPort: 80
          env:
            - name: TEST_USER			# Environment variable name
              valueFrom:
                secretKeyRef:			# Get from Secret
                  name: mysecret		# Secret's name
                  key: username		# Key name in Secret
            - name: TEST_PASSWORD		# Environment variable name
              valueFrom:
                secretKeyRef:			# Get from Secret
                  name: mysecret		# Secret's name
                  key: password		# Key name in Secret (compared with configmap, Secret does not need to use plaintext here, which is a little safer)

View environment variables

# Enter container
$ kubectl exec pod-deployment-747f78bc67-2w9wk -it -- /bin/sh

# View environment variables
$ echo $TEST_USER
admin
$ echo $TEST_PASSWORD
123

3. kubernetes.io/dockerconfigjson

Create a secret for docker registry authentication using Kuberctl

# kubectl create secret docker-registry \	# Type of Secret created
#    myregistrykey \  						# Name of Secret
#    --docker-server=hub.zyx.com \			# Address of docker server
#    --docker-username=admin \				# docker user name
#    --docker-password=Harbor12345 \		# docker password
#    --docker-email=aa@qq.com 				# docker mailbox
kubectl create secret docker-registry \
    myregistrykey \
    --docker-server=hub.zyx.com \
    --docker-username=admin \
    --docker-password=Harbor12345 \
    --docker-email=aa@qq.com

When creating a Pod, use imagePullSecrets to reference the newly created myregistrykey to pull the image of the private warehouse

apiVersion: v1
kind: Pod
metadata:
  name: foo
spec:
  containers:
    - name: foo
      image: hub.zyx.com/zyx/myapp:v1
  imagePullSecrets:			# Authentication information when pulling from a private warehouse
    - name: myregistrykey	# Authentication information, docker registry created in the previous step

Keywords: Kubernetes

Added by oakld on Thu, 16 Dec 2021 00:28:46 +0200