14.kubernetes笔记 Volume存储卷(五) Secret、downwardAPI

Secret简介

ConfigMap的配置信息基本没有类别之分,但Secret有所不同,根据其用户存在类型的概念;

  1. docker-registry:专用于让kubelet启动Pod时从私有镜像仓库pull镜像时,首先认证到Registry时使用;
  2. TLS:专门用于保存tls/ssl用到的证书和配对的私钥;
  3. generic:余下的为通用类型;在通用型中又存在多个子类型
  4. 子类型中系统默认的几个常用类型 都是用于系统组件通信时用到的认证

    --type="kubernetes.io/basic-auth"
    --type="kubernetes.io/rbd"
    --type="kubernetes.io/ssh-auth"
  5. 另外,保存有专用于ServiceAccount的相关的token信息的Secret资源会使用资源注解annotations来保存其使用场景。

    kind: Secret
    metadata:
      annotations:
      kubernetes.io/service-account.name: node-controller
      kubernetes.io/service-account.uid: 5c7b00cc-8fae-48f7-9069-8efce3681f4d
  6. 资源的元数据:除了name,namespace之外,常用的还有labels, annotations;
  7. annotation的名称遵循类似于labels的名称命名格式,但其数据长度不受限制;
  8. 它不能用于被标签选择器作为筛选条件;但常用于为那些仍处于Beta阶段的应用程序提供临时的配置接口;
  9. 管理命令:kubectl annotate TYPE/NANE KEY=VALUE,kubectl annotate TYPE/NAME KEY-

  • 还有一种由kubeadm的bootstrap所使用的token专用的类型,它通常保存于kube-system名称空间,以bootstrap-token-为前缀.

    --type="bootstrap. kubernetes.io/token"

TLS类型Secret

TLS类型是一种独特的类型,在创建secret的命令行中,除了类型标识的不同之外,它还需要使用专用的选项--cert和--key
无论证书和私钥文件名是什么,它们会统一为:
tls.crt
tls.key

Docker Registry类型Secret

[root@k8s-master ~]# kubectl create secret docker-registry --help   #查看帮助 提示提供的信息
......
Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --append-hash=false: Append a hash of the secret to its name.
      --docker-email='': Email for Docker registry
      --docker-password='': Password for Docker registry authentication
      --docker-server='https://index.docker.io/v1/': Server location for Docker registry
      --docker-username='': Username 为 Docker registry authentication
  • 也能够从docker的认证文件中加载信息,这时使用--from-file选项;

    $HOME/.dockercfg, ~/.docker/config.json
  • 何时引用,以及如何引用 通过以下字段在Pod中引用

    pod.spec.imagePullSecrets

    Secret资源,使用环境变量引用格式

  • name: ...
    image: ...
    env:

    • name: #变量名,其值来自于某Secret对象上的指定键的值;
      valueFrom: #键值引用;
      secretkeyRef:

      name:  #引用的Secret对象的名称,需要与该Pod位于同一名称空间;
      key:  #引用的Secret对象上的键,其值将传递给环境变量;
      optional:   #是否为可选引用;

      envFrom: #整体引用指定的Secret对象的全部键名和键值;

    • prefix: #将所有键名引用为环境变量时统一添加的前缀;
      secretRef:
      name: #引用的Secret对象名称;
      optional: #是否为可选引用;

示例1: 创建通用型Secret、MySQL引用Secret

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

Available Commands:  #3种类型Secret说明
  docker-registry Create a secret for use with a Docker registry
  generic         Create a secret from a local file, directory or literal value
  tls             Create a TLS secret

#创造generi类型 Secret  用户:root 密码:userpassword
[root@k8s-master secret]# kubectl create secret generic mysql-root-authn --from-literal=username=root --from-literal=password=userpassword
secret/mysql-root-authn created

[root@k8s-master secret]# kubectl get secret  
NAME                               TYPE                                  DATA   AGE
default-token-fsshk                kubernetes.io/service-account-token   3      39d
my-grafana                         Opaque                                3      36d
my-grafana-test-token-87856        kubernetes.io/service-account-token   3      36d
my-grafana-token-gh765             kubernetes.io/service-account-token   3      36d
mysql-root-authn                   Opaque(模糊类型)                    2      25s
sh.helm.release.v1.my-grafana.v1   helm.sh/release.v1                    1      36d

#详细描述信息
[root@k8s-master secret]# kubectl describe secret mysql-root-authn  
Name:         mysql-root-authn
Namespace:    default
Labels:       
Annotations:  

Type:  Opaque

Data
====
password:  12 bytes
username:  4 bytes
[root@k8s-master secret]# kubectl get secret mysql-root-authn
NAME               TYPE     DATA   AGE
mysql-root-authn   Opaque   2      64s
[root@k8s-master secret]# kubectl get secret mysql-root-authn -o yaml
apiVersion: v1
data:
  password: dXNlcnBhc3N3b3Jk #通过base64格式加密
  username: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: "2021-08-07T07:03:31Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:password: {}
        f:username: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2021-08-07T07:03:31Z"
  name: mysql-root-authn
  namespace: default
  resourceVersion: "7454439"
  selfLink: /api/v1/namespaces/default/secrets/mysql-root-authn
  uid: 5743f6a0-1f02-445c-87e5-ae9819d77811
type: Opaque

[root@k8s-master secret]# echo dXNlcnBhc3N3b3Jk|base64 -d  #通过base64格式解密
userpassword[root@k8s-master secret]# 

#创建basic-authn认证
[root@k8s-master secret]# kubectl create secret generic web-basic-authn --from-literal=username=devopser --from-literal=password=userpassword --type="kubenetes.io/basic-auth"
secret/web-basic-authn created
[root@k8s-master secret]# kubectl get secret
NAME                               TYPE                                  DATA   AGE
default-token-fsshk                kubernetes.io/service-account-token   3      39d
my-grafana                         Opaque                                3      36d
my-grafana-test-token-87856        kubernetes.io/service-account-token   3      36d
my-grafana-token-gh765             kubernetes.io/service-account-token   3      36d
mysql-root-authn                   Opaque                                2      8m2s
sh.helm.release.v1.my-grafana.v1   helm.sh/release.v1                    1      36d
web-basic-authn                    kubenetes.io/basic-auth(认证类型)   2      21s

[root@k8s-master secret]# kubectl get secret -n kube-system   #kube-system名称空间下常用的secret类型
NAME                                             TYPE                                  DATA   AGE
attachdetach-controller-token-bpprw              kubernetes.io/service-account-token   3      39d
bootstrap-signer-token-69hd8                     kubernetes.io/service-account-token   3      39d
bootstrap-token-hbjzpz                           bootstrap.kubernetes.io/token         5      3d
certificate-controller-token-26sn8               kubernetes.io/service-account-token   3      39d
clusterrole-aggregation-controller-token-hlb6c   kubernetes.io/service-account-token   3      39d
coredns-token-k6swp                              kubernetes.io/service-account-token   3      39d
cronjob-controller-token-449ng                   kubernetes.io/service-account-token   3      39d
daemon-set-controller-token-qb22n                kubernetes.io/service-account-token   3      39d
default-token-xjfpp                              kubernetes.io/service-account-token   3      39d
deployment-controller-token-tb84w                kubernetes.io/service-account-token   3      39d
disruption-controller-token-cqzdt                kubernetes.io/service-account-token   3      39d
endpoint-controller-token-ptsp4                  kubernetes.io/service-account-token   3      39d

[root@k8s-master secret]# kubectl get secret node-controller-token-rv7zt -n kube-system -o yaml
  • MySQL 引用Secret

    [root@k8s-master secret]# cat secrets-env-demo.yaml 
    apiVersion: v1
    kind: Pod
    metadata:
    name: secrets-env-demo
    namespace: default
    spec:
    containers:
    - name: mariadb
      image: mariadb
      imagePullPolicy: IfNotPresent
      env: #使用环境变量,容器在启动时加载 无法实时加载更新
      - name: MYSQL_ROOT_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysql-root-authn  #引用之前的secret
            key: password
    [root@k8s-master secret]# kubectl apply -f secrets-env-demo.yaml
    
    [root@k8s-master secret]# kubectl get pod
    NAME                                 READY   STATUS    RESTARTS   AGE
    centos-deployment-66d8cd5f8b-95brg   1/1     Running   0          2d22h
    configmap-volume-demo3               1/1     Running   0          4h36m
    configmaps-env-demo                  1/1     Running   0          24h
    configmaps-volume-demo               1/1     Running   0          24h
    configmaps-volume-demo2              2/2     Running   0          17h
    my-grafana-7d788c5479-bpztz          1/1     Running   3          2d22h
    secrets-env-demo                     1/1     Running   0          6m38s
    volumes-pvc-longhorn-demo            1/1     Running   0          2d4h
    
    #使用Secret帐号密码登录
    [root@k8s-master secret]# kubectl exec secrets-env-demo -it -- /bin/bash
    root@secrets-env-demo:/# mysql -uroot -puserpassword   
    Welcome to the MariaDB monitor.  Commands end with ; or \g.
    Your MariaDB connection id is 3
    Server version: 10.6.3-MariaDB-1:10.6.3+maria~focal mariadb.org binary distribution
    
    Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    MariaDB [(none)]> exit
    Bye
    
    root@secrets-env-demo:/# exit
    exit
    

    示例2: 创TLS类型Secret HTTPS引用自签证书

    #创建TLS证书
    [root@k8s-master secret]# (umask 007; openssl genrsa -out nginx.key 2048)   #创建Key
    Generating RSA private key, 2048 bit long modulus
    ................................................................................................+++
    .................+++
    e is 65537 (0x10001)
    [root@k8s-master secret]# ls
    nginx.key
    #创建自签证书
    [root@k8s-master secret]# openssl req -new -x509 -key nginx.key -out nginx.crt -subj /C=CN/ST=Hz/O=DevOps/CN=www.test.com 
    [root@k8s-master secret]# ls
    nginx.crt  nginx.key
    #创建Secret
    [root@k8s-master secret]# kubectl create secret tls nginx-ssl-secret --key=./nginx.key --cert=./nginx.crt  
    secret/nginx-ssl-secret created
    
    [root@k8s-master secret]# kubectl get secret
    NAME                               TYPE                                  DATA   AGE
    default-token-fsshk                kubernetes.io/service-account-token   3      39d
    my-grafana                         Opaque                                3      36d
    my-grafana-test-token-87856        kubernetes.io/service-account-token   3      36d
    my-grafana-token-gh765             kubernetes.io/service-account-token   3      36d
    mysql-root-authn                   Opaque                                2      32m
    nginx-ssl-secret                   kubernetes.io/tls                     2      15s
    sh.helm.release.v1.my-grafana.v1   helm.sh/release.v1                    1      36d
    web-basic-authn                    kubenetes.io/basic-auth               2      24m
    [root@k8s-master secret]# kubectl describe secret nginx-ssl-secret
    Name:         nginx-ssl-secret
    Namespace:    default
    Labels:       
    Annotations:  
    
    Type:  kubernetes.io/tls
    
    Data
    ====
    tls.crt:  1220 bytes
    tls.key:  1675 bytes
    [root@k8s-master secret]# kubectl get  secret nginx-ssl-secret -o yaml
    apiVersion: v1
    data:
    tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURWekNDQWorZ0F3SUJBZ0lKQUpsZGlNMGIvTTRFTUEwR0NTcUdTSWIzRFFFQkN3VUFNRUl4Q3pBSkJnTlYKQkFZVEFrTk9NUXN3Q1FZRFZRUUlEQUpJ1ekhVSkNyc3AxQjkyZGhuCktEZGt0ZWFGVWw5eXFiYzFHeHVwRG15b0lUUjJQUnZzTkREeUl5OGtnOHB6NVl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1hhNll5Vzc0b3JWemtoTElhUXMzcDVqWUM5M2UzeUE1QklubVNaZ29iOEFNMU10c3dsYjJnZVpsMzRSNUtmCms3a1Q4UUtCZ0Z3RkxudHlmR2x5VW9pRVllZTFGSTQvZVB4VU9TZXJUQzRvMnRkakwwQmJKbGllVStXYWlOcEEKeXZ1eHE4VEhuVDBRLytyTHp1ZzkvdlhWQ01ycmliZk92bHZMMjBDclpkNVd0a205TXdYQklQR1B3cHpQZXJldwp3RFV2VG9hb21sQnVXRVpFc1V3eGYyK3hzc042MFp6OThRSVRTU2R3TmFSSm55ZzJHUk5mCi0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0tCg==
    kind: Secret
    metadata:
    creationTimestamp: "2021-08-07T07:35:35Z"
    managedFields:
    - apiVersion: v1
      fieldsType: FieldsV1
      fieldsV1:
        f:data:
          .: {}
          f:tls.crt: {}
          f:tls.key: {}
        f:type: {}
      manager: kubectl-create
      operation: Update
      time: "2021-08-07T07:35:35Z"
    name: nginx-ssl-secret
    namespace: default
    resourceVersion: "7460794"
    selfLink: /api/v1/namespaces/default/secrets/nginx-ssl-secret
    uid: 72bdf764-cd58-4be4-b93c-c9e7bd83713e
    type: kubernetes.io/tls
    
    #解密key
    [root@k8s-master secret]# echo LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFb3dJQkFBS0NBUUVBcUl6Nk9yVFYxWENPYWJiZERDaVdFd0ZOcnlwQ2JHby9kYXlqYmc2eUUvcFJsYzFiCnJ5QWJSOFJhZmh3aCtiWXdUMC9qMG1NQXkyRG4rRStnVXczVXhKTjg1YzFvUjVWeEs3MlBVeTV4dXZkQWRvTUIKOVFKcmpjTS9HMkgzUjY0SUViUkVERTVrMWprbVZNbVRhVGJnYVNLYzZ6Umg3ZUZ0S1VnQVlJdE1GMUtFbXpqQwpiS1owY3ZnUE5vV0J5TnJ3WFBRT1FURXFJVGFoaURWRVFBYlJFL2FIS1VWd2RXK0Y3dklpYzV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eB/fiqlQmM7CrK1McnpaoNKCEG
    oEVzvbMKBKH8hFYBslEdMtffeePeMXIHDqHOIV0jvTAupEJVLVBryka+FcATdeYC
    9SXa6YyW74orVzkhLIaQs3p5jYC93e3yA5BInmSZgob8AM1Mtswlb2geZl34R5Kf
    k7kT8QKBgFwFLntyfGlyUoiEYee1FI4/ePxUOSerTC4o2tdjL0BbJlieU+WaiNpA
    yvuxq8THnT0Q/+rLzug9/vXVCMrribfOvlvL20CrZd5Wtkm9MwXBIPGPwpzPerew
    wDUvToaomlBuWEZEsUwxf2+xssN60Zz98QITSSdwNaRJnyg2GRNf
    -----END RSA PRIVATE KEY-----
    
    [root@k8s-master secret]# 
    
  • HTTPS自签证书引用TLS Secret

    [root@k8s-master secret]# cat secrets-volume-demo.yaml 
    apiVersion: v1
    kind: Pod
    metadata:
    name: secrets-volume-demo
    namespace: default
    spec:
    containers:
    - image: nginx:alpine
      name: ngxserver
      volumeMounts:
      - name: nginxcerts
        mountPath: /etc/nginx/certs/
        readOnly: true
      - name: nginxconfs
        mountPath: /etc/nginx/conf.d/
        readOnly: true
    volumes:
    - name: nginxcerts
      secret:
        secretName: nginx-ssl-secret   #引用之前的secret自签证
    - name: nginxconfs
      configMap:
        name: nginx-sslvhosts-confs  #引用configMap
        optional: false
    
    [root@k8s-master secret]# cat nginx-config.d/myserver
    myserver.conf        myserver-gzip.cfg    myserver-status.cfg  
    [root@k8s-master secret]# cat nginx-config.d/myserver.conf 
    server {
      listen 443 ssl;
      server_name www.test.com;
    
      ssl_certificate /etc/nginx/certs/tls.crt;
      ssl_certificate_key /etc/nginx/certs/tls.key;
      
      ssl_session_timeout 5m;
      
      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    
      ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
      ssl_prefer_server_ciphers on;
    
      include /etc/nginx/conf.d/myserver-*.cfg;
      location / {
        root /usr/share/nginx/html;
      }
    }
    
    server {
      listen 80;
      server_name www.ilinux.io;
      return 301 https://$host$request_uri;
    }
    
    #创建comfigMap
    [root@k8s-master secret]# kubectl create configmap nginx-sslvhosts-confs --fromonfs --from-file=./nginx-config.d
    configmap/nginx-sslvhosts-confs created
    [root@k8s-master secret]# kubectl get cm
    NAME                    DATA   AGE
    demoapp-config          4      47h
    demoapp-confs           4      18h
    nginx-config            2      26h
    nginx-config-files      3      24h
    nginx-sslvhosts-confs   3      12s
    
    [root@k8s-master secret]# kubectl apply -f secrets-volume-demo.yaml pod/secrets-volume-demo created
    
    [root@k8s-master secret]# kubectl get pod
    NAME                          READY   STATUS    RESTARTS   AGE
    secrets-volume-demo           1/1     Running   0          14m
    volumes-pvc-longhorn-demo     1/1     Running   0          2d5h
    
    #查看Pod配置
    [root@k8s-master secret]# kubectl exec secrets-volume-demo -it -- /bin/sh
    / # cd /etc/nginx/conf.d/
    /etc/nginx/conf.d # ls
    myserver-gzip.cfg    myserver-status.cfg  myserver.conf
    /etc/nginx/conf.d # cat myserver.conf 
    server {
      listen 443 ssl;
      server_name www.test.com;
    
      ssl_certificate /etc/nginx/certs/tls.crt;
      ssl_certificate_key /etc/nginx/certs/tls.key;
      
      ssl_session_timeout 5m;
      
      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    
      ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
      ssl_prefer_server_ciphers on;
    
      include /etc/nginx/conf.d/myserver-*.cfg;
      location / {
        root /usr/share/nginx/html;
      }
    }
    
    server {
      listen 80;
      server_name www.ilinux.io;
      return 301 https://$host$request_uri;
    }
    /etc/nginx/conf.d # netstat -nlt
    Active Internet connections (only servers)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       
    tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      
    
    /etc/nginx/conf.d # curl  -H "Host:www.test.com"  https://127.0.0.1:443   #警告自签证书风险
    curl: (60) SSL certificate problem: self signed certificate
    More details here: https://curl.se/docs/sslcerts.html
    
    curl failed to verify the legitimacy of the server and therefore could not
    establish a secure connection to it. To learn more about this situation and
    how to fix it, please visit the web page mentioned above.
    
    /etc/nginx/conf.d # curl -k -H "Host:www.test.com"  https://127.0.0.1:443   # -k忽略风险  访问成功
    
    
    
    Welcome to nginx!
    
    
    
    

    Welcome to nginx!

    If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

    For online documentation and support please refer to nginx.org.
    Commercial support is available at nginx.com.

    Thank you for using nginx.

    /etc/nginx/conf.d # exit [root@k8s-master secret]#

    示例3: 创建docker-registry类型secret用于私有仓库的认证

    [root@k8s-master secret]# kubectl create secret docker-registry harbor-tom --docker-username=tom --docker-password=userpassword [email protected] --docker-server=https://registry.test.com/v2/
    secret/harbor-tom created
    [root@k8s-master secret]# kubectl get secret
    NAME                               TYPE                                  DATA   AGE
    default-token-fsshk                kubernetes.io/service-account-token   3      39d
    harbor-tom                         kubernetes.io/dockerconfigjson        1      50s
    mysql-root-authn                   Opaque                                2      45m
    nginx-ssl-secret                   kubernetes.io/tls                     2      13m
    sh.helm.release.v1.my-grafana.v1   helm.sh/release.v1                    1      36d
    web-basic-authn                    kubenetes.io/basic-auth               2      37m
    [root@k8s-master secret]# kubectl get secret harbor-tom  -o yaml
    apiVersion: v1
    data:
    .dockerconfigjson: eyJhdXRocyI6eyJodHRwczovL3JlZ2lzdHJ5LnRlc3QuY29tL3YyLyI6eyJ1c2VybmFtZSI6InRvbSIsInBhc3N3b3JkIjoidXNlcnBhc3N3b3JkIiwiZW1haWwiOiJ0b21AdGVzdC5jb20iLCJhdXRoIjoiZEc5dE9uVnpaWEp3WVhOemQyOXlaQT09In19fQ==
    kind: Secret
    metadata:
    creationTimestamp: "2021-08-07T07:48:15Z"
    managedFields:
    - apiVersion: v1
      fieldsType: FieldsV1
      fieldsV1:
        f:data:
          .: {}
          f:.dockerconfigjson: {}
        f:type: {}
      manager: kubectl-create
      operation: Update
      time: "2021-08-07T07:48:15Z"
    name: harbor-tom
    namespace: default
    resourceVersion: "7463303"
    selfLink: /api/v1/namespaces/default/secrets/harbor-tom
    uid: 461547f3-4286-4377-9220-130231041908
    type: kubernetes.io/dockerconfigjson
    [root@k8s-master secret]# 
    [root@k8s-master secret]# echo eyJhdXRocyI6eyJodHRwczovL3JlZ2lzdHJ5LnRlc3QuY29tL3YyLyI6eyJ1c2VybmFtZSI6InRvbSIsInBhc3N3b3JkIjoidXNlcnBhc3N3b3JkIiwiZW1haWwiOiJ0b21AdGVzdC5jb20iLCJhdXRoIjoiZEc5dE9uVnpaWEp3WVhOemQyOXlaQT09In19fQ==|base64 -d
    {"auths":{"https://registry.test.com/v2/":{"username":"tom","password":"userpassword","email":"[email protected]","auth":"dG9tOnVzZXJwYXNzd29yZA=="}}}[root@k8s-master secret]# 

downwardAPI

  • downwardAPI存储卷类型,从严格意义上来说,downwardAPI不是存储卷,它自身就存在,原因在于,它引用的是Pod自身的运行环境信息,这些信息在Pod启动手就存在。
  • 类似于ConfigMap或Secret资源,容器能够在环境变量中在valueFrom字段中嵌套fieldRef或resourceFieldRef字段来引用其所属Pod对象的元数据信息。不过,通常只有常量类型的属性才能够通过环境变量,注入到容器中,毕竟,在进程启动完成后无法再向其告知变量值的变动,于是,环境变量也就不支持中途的更新操作。容器规范中可在环境变量配置中的valueFrom通过内嵌字段fieldRef引用的信息包括如下这些

  • metadata.name: Pod对象的名称;
  • metadata.namespace: Pod对象隶属的名称空间;
  • metadata.uid: Pod对象的UID;
  • metadata.labels['']: Pod对象标签中的指定键的值,例如metadata.labels['mylabel'],仅Kubernetes 1.9及之后的版本才支持;
  • metadata.annotations['']: Pod对象注解信息中的指定键的值,仅Kubernetes 1.9及之后的版本才支持。

  • 容器上的计算资源需求和资源限制相关的信息,以及临时存储资源需求和资源限制相关的信息可通过容器规范中的resourceFieldRef字段引用,相关字段包括requests.cpu、limits.cpu、requests.memory和limits.memory等。另外,可通过环境变量引用的信息有如下几个:

  • status.podIP: Pod对象的IP地址
  • spec.serviceAccountName: Pod对象使用的ServiceAccount资源名称
  • spec.nodeName: 节点名称
  • status.hostIP: 节点IP地址

  • 另外,还可以通过resoqurceFieldRef字段引用当前容器的资源请求及资源限额的定义,因此它们包括requests.cpu、requests.memory、requests.ephemeral-storage、limits.cpu、limits.memory和limits.ephemeral storage这6项。

示例4:downwardAPI 通过环境变量env:引用

[root@k8s-master secret]# cat downwardapi-env-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: downwardapi-env-demo
  labels:
    app: demoapp
spec:
  containers:
  - name: demoapp
    image: ikubernetes/demoapp:v1.0
#    command: ["/bin/sh","-c","env"]
    resources:
      requests:
        memory: "32Mi"
        cpu: "250m"
      limits:
        memory: "64Mi"
        cpu: "500m"
    env:
    - name: THIS_POD_NAME  #变量名
      valueFrom:
        fieldRef:
          fieldPath: metadata.name  #获取POD对象名称
    - name: THIS_POD_NAMESPACE
      valueFrom:
        fieldRef :
          fieldPath: metadata.namespace  #所在名称空间
    - name: THIS_APP_LABEL
      valueFrom:
        fieldRef:
          fieldPath: metadata.labels['app']
    - name: THIS_CPU_LIMIT
      valueFrom:
        resourceFieldRef:
          resource: limits.cpu #获取CPU限制 只显示整数1核 2核......
    - name: THIS_MEM_REQUEST
      valueFrom :
        resourceFieldRef:
          resource: requests.memory
          divisor: 1Mi #默认为K 单位换算为M
#restartPolicy: Never

[root@k8s-master secret]# kubectl get pod
NAME                          READY   STATUS    RESTARTS   AGE
configmap-volume-demo3        1/1     Running   0          29h
configmaps-env-demo           1/1     Running   0          2d1h
configmaps-volume-demo        1/1     Running   0          2d1h
configmaps-volume-demo2       2/2     Running   0          43h
downwardapi-env-demo          1/1     Running   0          8m52s

[root@k8s-master secret]# kubectl exec downwardapi-env-demo -it -- /bin/sh
[root@downwardapi-env-demo /]# env   #查看相关变量
...
THIS_APP_LABEL=demoapp
...
THIS_MEM_REQUEST=32
...
THIS_POD_NAME=downwardapi-env-demo
...
THIS_POD_NAMESPACE=default
...
THIS_CPU_LIMIT=1  #以核心数为单位


[root@downwardapi-env-demo /]# echo $THIS_POD_NAME  #直接引用
downwardapi-env-demo 

示例5:downwardAPI 通过volumeMounts挂载

[root@k8s-master secret]# cat downwardapi-volume-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: downwardapi-volume-demo
  labels:
    zone: zone1
    rack: rack100
    app: demoapp
  annotations:
    region: ease-cn
spec:
  containers:
  - name: demoapp
    image: ikubernetes/demoapp:v1.0
    resources:
      requests:
        memory: "32Mi"
        cpu: "250m"
      limits:
        memory: "64Mi"
        cpu: "500m"
    volumeMounts:
    - name: podinfo
      mountPath: /etc/podinfo    #键值的存放路径
      readOnly: false
  volumes:
  - name: podinfo
    downwardAPI:
      defaultMode: 420
      items:  #和configMap引用类似 默认只输出哪个变量给存储卷
      - fieldRef:
          fieldPath: metadata.namespace
        path: pod_namespace  #被引用的键名
      - fieldRef:
          fieldPath: metadata.labels
        path: pod_labels
      - fieldRef:
          fieldPath: metadata.annotations
        path: pod_annotations
      - resourceFieldRef:
          containerName: demoapp
          resource: limits.cpu
        path: "cpu_limit"
      - resourceFieldRef:
          containerName: demoapp
          resource: requests.memory
          divisor: "1Mi"
        path: "mem_request"
        

[root@k8s-master secret]# kubectl get pod
NAME                          READY   STATUS    RESTARTS   AGE
downwardapi-env-demo          1/1     Running   0          36m
downwardapi-volume-demo       1/1     Running   0          2m11s

#进入到容器查看配置
[root@k8s-master secret]# kubectl exec downwardapi-volume-demo -it  -- /bin/sh

[root@downwardapi-volume-demo /]# cd /etc/podinfo/
[root@downwardapi-volume-demo /etc/podinfo]# ls
cpu_limit        mem_request      pod_annotations  pod_labels       pod_namespace

[root@downwardapi-volume-demo /etc/podinfo]# cat cpu_limit 
1
[root@downwardapi-volume-demo /etc/podinfo]# cat pod_namespace 
default
[root@downwardapi-volume-demo /etc/podinfo]# cat pod_labels 
app="demoapp"
rack="rack100"
zone="zone1"

[root@downwardapi-volume-demo /etc/podinfo]# exit

你可能感兴趣的:(14.kubernetes笔记 Volume存储卷(五) Secret、downwardAPI)