kubernetes之使用ConfigMap管理Pod配置文件

简介

ConfigMaps可以使容器镜像与配置文件解耦,实现容器化应用程序的可移植性。此文提供一系列的方法示例讲述如何创建ConfigMaps,使用存储在ConfigMaps中的数据配置Pod。

备注:此文档参考官方文档,并加以自己的理解。如有误导性的内容,请批评指正。

创建一个ConfigMap

我们可以使用kubectl create configmapkustomization.yaml中的ConfigMap生成器创建一个ConfigMap。从Kubernetes 1.14版本开始,kubectl开始支持使用kustomization.yaml创建ConfigMap

使用 kubectl create configmap 创建一个 ConfigMap

使用kubectl create configmap从目录、文件或字面值创建configmaps。

kubectl create configmap <map-name> <data-source>

<map-name>即配置的ConfigMap的名字,<data-source>是从目录、文件或字面值下读取数据的目录。

ConfigMap中的data-source应该是一个键值对:

  • key=文件名称或提供的命令行的key
  • value=提命令行中提供的文件内容或字面值

使用kubectl describekubectl get查看ConfigMap的信息。

从目录中创建 ConfigMaps

可以使用kubectl create configmap从同一个目录下的多个文件创建ConfigMap

# Create the local directory
mkdir -p configure-pod-container/configmap/

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/game.properties -O configure-pod-container/configmap/game.properties
wget https://kubernetes.io/examples/configmap/ui.properties -O configure-pod-container/configmap/ui.properties

# Create the configmap
kubectl create configmap game-config --from-file=configure-pod-container/configmap/

configure-pod-container/configmap/目录下包含连个文件

game.properties
ui.properties

查看配置的ConfigMap内容:

kubectl describe configmaps game-config

从结果可以看出:ConfigMap中的data块中包含了configure-pod-container/configmap/目录下game.propertiesui.properties两个文件中的所有内容。

Name:         game-config
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game-env-file.properties:
----
enemies=aliens
lives=3
allowed="true"

# This comment and the empty line above it are ignored

game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
ui.properties:
----
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

Events:  <none>

yaml格式输出如下:

# kubectl get configmaps game-config -o yaml
apiVersion: v1
data:
  game-env-file.properties: |
    enemies=aliens
    lives=3
    allowed="true"

    # This comment and the empty line above it are ignored
  game.properties: |-
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30
  ui.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:18:08Z"
  name: game-config
  namespace: default
  resourceVersion: "10100181"
  selfLink: /api/v1/namespaces/default/configmaps/game-config
  uid: a447f523-ddf4-48f5-a0eb-6f24c732fee5

从文件中创建 ConfigMaps

使用kubectl create configmap从一个独立的文件或多个文件中创建ConfigMap

例如:

# kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties

查看内容:

# kubectl describe configmaps game-config-2

输出如下所示

Name:         game-config-2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
Events:  <none>

也可以通过多次使用--from-file参数从多个数据源中创建ConfigMap

例如:

# kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties

使用--from-env-file选项从env-file中创建ConfigMap:

例如:

# Env-files contain a list of environment variables.
# These syntax rules apply:
#   Each line in an env file has to be in VAR=VAL format.
#   Lines beginning with # (i.e. comments) are ignored.
#   Blank lines are ignored.
#   There is no special handling of quotation marks (i.e. they will be part of the ConfigMap value)).

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties

# The env-file `game-env-file.properties` looks like below
cat configure-pod-container/configmap/game-env-file.properties
enemies=aliens
lives=3
allowed="true"

# This comment and the empty line above it are ignored

创建ConfigMap

kubectl create configmap game-config-env-file        --from-env-file=configure-pod-container/configmap/game-env-file.properties

查看内容

# kubectl get configmap game-config-env-file -o yaml

输出如下

apiVersion: v1
data:
  allowed: '"true"'
  enemies: aliens
  lives: "3"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:32:05Z"
  name: game-config-env-file
  namespace: default
  resourceVersion: "10103588"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-env-file
  uid: 0ed90509-5577-4225-a1ad-826426069da3

注意:当通过多次使用 --from-env-file 从多个数据源中创建ConfigMap时,只有最后一个 env-file生效。

演示多次使用 --from-env-file的例子
例如:

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://k8s.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties

# Create the configmap
kubectl create configmap config-multi-env-files         --from-env-file=configure-pod-container/configmap/game-env-file.properties         --from-env-file=configure-pod-container/configmap/ui-env-file.properties
# kubectl get configmap config-multi-env-files -o yaml

输出内容如下,从结果可以看出生效的配置为最后一个--from-env-file指定的ui-env-file.properties

apiVersion: v1
data:
  color: purple
  how: fairlyNice
  textmode: "true"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:45:01Z"
  name: config-multi-env-files
  namespace: default
  resourceVersion: "10106742"
  selfLink: /api/v1/namespaces/default/configmaps/config-multi-env-files
  uid: 583873dd-12e6-408a-9373-b9cfeb092d5a

定义从文件创建ConfigMap时要使用的Key

使用--from-file参数给某个数据源的文件的数据定一个key,在ConfigMapdata块下可以看到这个key。

kubectl create configmap game-config-3 --from-file=<my-key-name>=<path-to-file>

这里的<my-key-name>即想要在COnfigMap中使用的key的名称,<path-to-file>是本地数据源中key要表达的数据内容。
例如:

# kubectl create configmap game-config-3 --from-file=game-special-key=configure-pod-container/configmap/game.properties

查看内容

# kubectl get configmaps game-config-3 -o yaml

输出结果如下,在data块下有一个名称为game-special-keykeykey的值即为--from-file=game-special-key=configure-pod-container/configmap/game.properties文件中的内容。

apiVersion: v1
data:
  game-special-key: |-
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:59:47Z"
  name: game-config-3
  namespace: default
  resourceVersion: "10110353"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-3
  uid: e1569842-1438-46c3-91da-30cd989c17da

从字面值中创建ConfigMap

使用带有--from-literal参数的kubectl create configmap从命令行的字面量中创建一个ConfigMap。

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

可以用多个key-value的键值对。每一个命令行中提供的键值对在ConfigMapdata块下都是独立的。

查看内容

# kubectl get configmaps special-config -o yaml

输出如下

apiVersion: v1
data:
  special.how: very
  special.type: charm
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T08:09:09Z"
  name: special-config
  namespace: default
  resourceVersion: "10112639"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: 57306de5-bd39-4d98-84fe-12357312551b

从生成器创建ConfigMap

kubelet从1.14版开始支持使用kustomization.yaml。可以从生成器创建ConfigMap,然后将其应用于在Apiserver上创建对象。

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-4
  files:
  - configure-pod-container/configmap/game.properties
EOF

应用Kustomization目录创建ConfigMap对象。

kubectl apply -k .

查看是否创建成功

# kubectl get configmap
NAME                       DATA   AGE
...
game-config-4-m9dm2f92bt   1      48s
...
# kubectl describe configmaps/game-config-4-m9dm2f92bt
Name:         game-config-4-m9dm2f92bt
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"game.properties":"enemies=aliens\nlives=3\nenemies.cheat=true\nenemies.cheat.level=noGoodRotten\nsecret.code.p...

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
Events:  <none>

注意,生成的ConfigMap名称具有通过对内容进行哈希后而附加的后缀。 这样可以确保每次修改内容时都会生成一个新的ConfigMap。

定义从文件生成ConfigMap时使用的Key

可以定义一个Key,而不是要在ConfigMap生成器中使用的文件名。 例如,要使用game-special-key从文件configure-pod-container/configmap/game.properties生成ConfigMap

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-5
  files:
  - game-special-key=configure-pod-container/configmap/game.properties
EOF

应用Kustomization目录创建ConfigMap对象。

kubectl apply -k .

从字面量生成ConfigMap

为了从自定义的type=charmspecial.how=very字面量创建ConfigMap,在kustomization.yaml中定义的生成器如下:

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: special-config-2
  literals:
  - special.how=very
  - special.type=charm
EOF

创建

kubectl apply -k .

使用 ConfigMap 中的数据定义容器的环境变量

从单一的 ConfigMap中的数据定义容器的环境变量:

1、在ConfigMap中以key-value的键值对定义环境变量

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

2、将ConfigMap中定义的special.how值分配给Pod的spec中的SPECIAL_LEVEL_KEY环境变量。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        # Define the environment variable
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: special-config
              # Specify the key associated with the value
              key: special.how
  restartPolicy: Never

创建Pod

kubectl create -f /root/k8s-example/pods/pod-single-configmap-env-variable.yaml

Pod的输出包含环境变量SPECIAL_LEVEL_KEY=very

从多个ConfigMaps数据中定义容器变量

创建ConfigMaps:

kubectl create -f /root/k8s-example/configmap/configmaps.yaml

在Pod的spec中定义环境变量

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: special.how
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: env-config
              key: log_level
  restartPolicy: Never

创建Pod:

kubectl create -f /root/k8s-example/pods/pod-multiple-configmap-env-variable.yaml

Pod的输出的环境变量包含两个SPECIAL_LEVEL_KEY=veryLOG_LEVEL=INFO

在ConfigMap中配置所有 key-value 键值对作为容器环境变量

创建包含多个键值对的ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
kubectl create -f /root/k8s-example/configmap/configmap-multikeys.yaml

使用envFrom定义ConfigMap中的所有数据作为容器的环境变量。ConfigMap中的Key变成了Pod中的环境变量。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: special-config
  restartPolicy: Never

创建Pod

kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-envFrom.yaml

Pod输出包含环境变量SPECIAL_LEVEL=verySPECIAL_TYPE=charm

在Pod命令中使用ConfigMap中定义的变量

在Pod的spec中的command块可以使用$(VAR_NAME)的方式,导入ConfigMap中定义的环境变量

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_LEVEL
        - name: SPECIAL_TYPE_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_TYPE
  restartPolicy: Never

test-container容器输出如下:

very charm

Volumes 中添加 ConfigMap 数据

创建ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
# kubectl create -f /root/k8s-example/configmap/configmap-multikeys.yaml

在Pod的spec规格的volume块下添加ConfigMap的名称。此配置会添加ConfigMap中的数据到指定的volumeMounts.mountPath的目录中,即如下容器的/etc/config目录。command块列出volumeMounts.mountPath目录下的所有文件。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never

创建Pod:

# kubectl apply -f pod-configmap-volume.yaml

查看容器日志输出

# kubectl logs dapi-test-pod

输出内容如下:

SPECIAL_LEVEL
SPECIAL_TYPE

注意:如果 /etc/config 目录下有文件,将会被删除掉。

添加 ConfigMap数据到指定 Volume 路径下

使用 path 字段配置ConfigMap中的特定项到指定的路径下。例如SPECIAL_LEVEL项的内容将会挂载在config-volume指定的/etc/config/keys卷上。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh","-c","cat /etc/config/keys" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        - key: SPECIAL_LEVEL
          path: keys
  restartPolicy: Never

创建Pod

# kubectl apply -f /root/k8s-example/pods/pod-configmap-volume-specific-key.yaml

查看日志输出

# kubectl logs dapi-test-pod
very

注意:所有以前在 /etc/config/ 目录下的文件将会被删除

删除资源

# kubectl delete configmaps game-config
# kubectl delete configmaps game-config-2
# kubectl delete configmaps config-multi-env-files
# kubectl delete configmaps game-config-3
...

理解 ConfigMap 和 Pod

ConfigMap 的 API 资源以键值对的形式存储配置数据。数据可以在Pod中使用,也可以提供系统组件的配置。例如 controllers。ConfigMap与Secrets类似,但是提供了一种处理不包含敏感信息的字符串的方法。 用户和系统组件都可以将配置数据存储在ConfigMap中。

注意:ConfigMap应该引用属性文件,而不是替换它们。 可以将ConfigMap表示为类似于Linux / etc目录及其内容的东西。 例如,如果从ConfigMap创建Kubernetes卷,则ConfigMap中的每个数据项都由该卷中的单个文件表示。

ConfigMap的data字段包含配置数据。 如下例所示,它可以很简单,例如使用--from-literal定义的单个属性例,也可以很复杂,如使用--from-file定义的配置文件

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2016-02-18T19:14:38Z
  name: example-config
  namespace: default
data:
  # example of a simple property defined using --from-literal
  example.property.1: hello
  example.property.2: world
  # example of a complex property defined using --from-file
  example.property.file: |-
    property.1=value-1
    property.2=value-2
    property.3=value-3

ConfigMap的限制条件

  • 在Pod的被创建之前必须先创建 ConfigMap(除非设置了 ConfigMap为可选项。如果引用的ConfigMap不存在,则Pod不会启动。 同样,对ConfigMap中不存在的key的引用也会阻止Pod启动。
  • 如果使用envFrom从ConfigMap中定义环境变量,则将忽略被认为无效的键。 可以启动Pod,但无效名称将记录在事件日志(InvalidVariableNames)中。 日志消息列出了每个跳过的键,可使用如下命令查看
kubectl get events

类似输出如下:

LASTSEEN FIRSTSEEN COUNT NAME          KIND  SUBOBJECT  TYPE      REASON                            SOURCE                MESSAGE
   0s       0s        1     dapi-test-pod Pod              Warning   InvalidEnvironmentVariableNames   {kubelet, 127.0.0.1}  Keys [1badkey, 2alsobad] from the EnvFrom configMap default/myconfig were skipped since they are considered invalid environment variable names.
  • ConfigMap驻留在特定的命名空间中。 ConfigMap只能由位于相同名称空间中的Pod引用
  • 不能给静态Pod配置ConfigMaps,Kubelet不支持。

原文地址:https://www.cnblogs.com/mcsiberiawolf/p/12227855.html

时间: 2024-07-31 07:46:06

kubernetes之使用ConfigMap管理Pod配置文件的相关文章

[转帖] Kubernetes如何使用ReplicationController、Replica Set、Deployment管理Pod ----文章很好 但是还没具体操作实践 也还没记住.

Kubernetes如何使用ReplicationController.Replica Set.Deployment管理Pod https://blog.csdn.net/yjk13703623757/article/details/53746273 Pod直译是豆荚,我们可以把容器想像成豆荚里的豆子,把一个或多个关系紧密的豆子包在一起就是豆荚(一个Pod).在k8s中我们不会直接操作容器,而是把容器包装成Pod,而对于Pod,我们该如何管理?先看下面这个场景: 1. 应用场景 假设有一个Pod

Docker Kubernetes 创建管理 Pod

Docker Kubernetes 容器扩容与缩容 环境: 系统:Centos 7.4 x64 Docker版本:18.09.0 Kubernetes版本:v1.8 管理节点:192.168.1.79 工作节点:192.168.1.78 工作节点:192.168.1.77 管理节点:创建pod yaml文件 vim pod.yaml apiVersion: v1 kind: Pod metadata: name: pod-test labels: os: centos spec: contain

kubernetes云平台管理实战:deployment通过标签管理pod(十)

一.kubectl run命令拓展 1.RC创建 [root@k8s-master ~]# kubectl run web --generator=run/v1 --image=10.0.128.0:5000/nginx:1.13 --replicas=3 replicationcontroller "web" created 2.deployment创建 [root@k8s-master ~]# kubectl run web --image=10.0.128.0:5000/ngin

k8s之安全信息(secret)及配置信息(configmap)管理

应用启动过程中可能需要一些敏感信息,比如访问数据库的用户名密码或者秘钥.将这些信息直接保存在容器镜像中显然不妥,Kubernetes 提供的解决方案是 Secret. Secret 会以密文的方式存储数据,避免了直接在配置文件中保存敏感信息.Secret 会以 Volume 的形式被 mount 到 Pod,容器可通过文件的方式使用 Secret 中的敏感数据:此外,容器也可以环境变量的方式使用这些数据. Secret 可通过命令行或 YAML 创建.比如希望 Secret 中包含如下信息: 用

Kubernetes有状态应用管理——PetSet

1.介绍 在Kubernetes中,大多数的Pod管理都是基于无状态.一次性的理念.例如Replication Controller,它只是简单的保证可提供服务的Pod数量.如果一个Pod被认定为不健康的,Kubernetes就会以对待牲畜的态度对待这个Pod--删掉.重建.相比于牲畜应用,PetSet(宠物应用),是由一组有状态的Pod组成,每个Pod有自己特殊且不可改变的ID,且每个Pod中都有自己独一无二.不能删除的数据. 众所周知,相比于无状态应用的管理,有状态应用的管理是非常困难的.有

Kubernetes 里,怎么让 Pod 有 DNS 记录?

在专栏"深入剖析Kubernetes"的第20章,我们学到很容易让一个 StatefulSet 中的 Pod 拥有 DNS 记录.如果一个 StatefulSet 的名字是 memcached, 而它指定了关联的 serviceName 叫 memcached-cluster,那 kube-dns 就会为它的每个 pod 解析如下的 DNS A 记录: memcached-0.memcached-cluster.svc.cluster.local memcached-1.memcach

kubernetes概述之深入理解pod对象

一.深入理解Pod对象 1.Pod容器的分类 Pod的概念: 最小部署单元 一组容器的集合 一个Pod中的容器共享网络命名空间 Pod是短暂的 Pod的容器分类: Infrastructure Container:基础容器 -- 维护整个Pod的网络空间 一般这里的pause镜像的作用就是维护pod的网络空间 InitContainers:初始化容器 -- 先与业务容器开始执行 Containers:业务容器 -- 并行启动 2.镜像拉取策略 IfNotPresent:默认值,镜像在宿主机上不存

ansible管理nginx配置文件

#生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下.下面我们来写个管理nginx配置文件的playbook 一.创建相关目录 mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks} #其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令. #关于回滚,需要在执行playb

linux系统-用户管理-相关配置文件

linux系统-用户管理-相关配置文件 一 配置文件 1 用户信息文件:/etc/passwd 2 密码文件:/etc/shadow 3 用户组信息文件:/etc/group 4 用户组密码文件:/etc/gshadow 5 用户配置文件:/etc/login.defs     /etc/default/useradd 6 新用户的信息文件:/etc/skel 7 登陆信息文件:/etc/motd和/etc/issue 二 my_qq 872785786 及相应的网盘资料链接:http://pa