El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Easily Switch Between Product Types

You can click the drop-down list box to switch between different product types.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
Software Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Using a ConfigMap

Updated on 2024-01-26 GMT+08:00

The following example shows how to use a ConfigMap.

apiVersion: v1
kind: ConfigMap
metadata:
  name: cce-configmap
data:
  SPECIAL_LEVEL: Hello
  SPECIAL_TYPE: CCE
NOTICE:
  • When a ConfigMap is used in a workload, the workload and ConfigMap must be in the same cluster and namespace.
  • When a ConfigMap is mounted as a data volume and the ConfigMap is updated, Kubernetes updates the data in the data volume at the same time.

    For a ConfigMap data volume mounted in subPath mode, Kubernetes cannot automatically update data in the data volume when the ConfigMap is updated.

  • When a ConfigMap is used as an environment variable, data is not automatically updated when the ConfigMap is updated. To update the data, restart the pod.

Setting Workload Environment Variables

Using the console

  1. Log in to the CCE console and click the cluster name to access the cluster console.
  2. In the navigation pane, choose Workloads. Then, click Create Workload.

    When creating a workload, click Environment Variables in the Container Settings area, and click .

    • Added from ConfigMap: Select a ConfigMap to import all of its keys as environment variables.
    • Added from ConfigMap key: Import a key in a ConfigMap as the value of an environment variable.
      • Variable Name: name of an environment variable in the workload. The name can be customized and is set to the key name selected in the ConfigMap by default.
      • Variable Value/Reference: Select a ConfigMap and the key to be imported. The corresponding value is imported as a workload environment variable.

      For example, after you import the value Hello of SPECIAL_LEVEL in ConfigMap cce-configmap as the value of workload environment variable SPECIAL_LEVEL, an environment variable named SPECIAL_LEVEL with its value Hello exists in the container.

  3. Configure other workload parameters and click Create Workload.

    After the workload runs properly, log in to the container and run the following statement to check whether the ConfigMap has been set as an environment variable of the workload:

    printenv SPECIAL_LEVEL

    The example output is as follows:

    Hello

Using kubectl

  1. Use kubectl to connect to the cluster. For details, see Connecting to a Cluster Using kubectl.
  2. Create a file named nginx-configmap.yaml and edit it.

    vi nginx-configmap.yaml

    Content of the YAML file:

    • Added from a ConfigMap: To add all data in a ConfigMap to environment variables, use the envFrom parameter. The keys in the ConfigMap will become names of environment variables in the workload.
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: nginx-configmap
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: nginx-configmap
        template:
          metadata:
            labels:
              app: nginx-configmap
          spec:
            containers:
            - name: container-1
              image: nginx:latest
              envFrom:                      # Use envFrom to specify a ConfigMap to be referenced by environment variables.
              - configMapRef:
                  name: cce-configmap       # Name of the referenced ConfigMap.
            imagePullSecrets:
            - name: default-secret
    • Added from a ConfigMap key: When creating a workload, you can use a ConfigMap to set environment variables and use the valueFrom parameter to reference the key-value pair in the ConfigMap separately.
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: nginx-configmap
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: nginx-configmap
        template:
          metadata:
            labels:
              app: nginx-configmap
          spec:
            containers:
            - name: container-1
              image: nginx:latest
              env:                             # Set the environment variable in the workload.
              - name: SPECIAL_LEVEL           # Name of the environment variable in the workload.
                valueFrom:                    # Specify a ConfigMap to be referenced by the environment variable.
                  configMapKeyRef:
                    name: cce-configmap       # Name of the referenced ConfigMap.
                    key: SPECIAL_LEVEL        # Key in the referenced ConfigMap.
              - name: SPECIAL_TYPE            # Add multiple environment variables to import them at the same time.
                valueFrom:
                  configMapKeyRef:
                    name: cce-configmap
                    key: SPECIAL_TYPE
            imagePullSecrets:
            - name: default-secret

  3. Create a workload.

    kubectl apply -f nginx-configmap.yaml

  4. View the environment variable in the pod.

    1. Run the following command to view the created pod:
      kubectl get pod | grep nginx-configmap
      Expected output:
      nginx-configmap-***   1/1     Running   0              2m18s
    2. Run the following command to view the environment variables in the pod:
      kubectl exec nginx-configmap-*** -- printenv SPECIAL_LEVEL SPECIAL_TYPE

      Expected output:

      Hello
      CCE

      The ConfigMap has been set as environment variables of the workload.

Setting Command Line Parameters

You can use a ConfigMap as an environment variable to set commands or parameter values for a container by using the environment variable substitution syntax $(VAR_NAME).

Using the console

  1. Log in to the CCE console and click the cluster name to access the cluster console.
  2. In the navigation pane, choose Workloads. Then, click Create Workload.

    When creating a workload, click Environment Variables in the Container Settings area, and click . In this example, select Added from ConfigMap.

    • Added from ConfigMap: Select a ConfigMap to import all of its keys as environment variables.

  3. Click Lifecycle in the Container Settings area, click the Post-Start tab on the right, and set the following parameters:

    • Processing Method: CLI
    • Command: Enter the following three command lines. SPECIAL_LEVEL and SPECIAL_TYPE are the environment variable names in the workload, that is, the key names in the cce-configmap ConfigMap.
      /bin/bash
      -c
      echo $SPECIAL_LEVEL $SPECIAL_TYPE > /usr/share/nginx/html/index.html

  4. Set other workload parameters and click Create Workload.

    After the workload runs properly, log in to the container and run the following statement to check whether the ConfigMap has been set as an environment variable of the workload:

    cat /usr/share/nginx/html/index.html

    The example output is as follows:

    Hello CCE

Using kubectl

  1. Use kubectl to connect to the cluster. For details, see Connecting to a Cluster Using kubectl.
  2. Create a file named nginx-configmap.yaml and edit it.

    vi nginx-configmap.yaml

    As shown in the following example, the cce-configmap ConfigMap is imported to the workload. SPECIAL_LEVEL and SPECIAL_TYPE are the environment variable names in the workload, that is, the key names in the cce-configmap ConfigMap.
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-configmap
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx-configmap
      template:
        metadata:
          labels:
            app: nginx-configmap
        spec:
          containers:
          - name: container-1
            image: nginx:latest
            lifecycle:
              postStart:
                exec:
                  command: [ "/bin/sh", "-c", "echo $SPECIAL_LEVEL $SPECIAL_TYPE > /usr/share/nginx/html/index.html" ]
            envFrom:                      # Use envFrom to specify a ConfigMap to be referenced by environment variables.
            - configMapRef:
                name: cce-configmap       # Name of the referenced ConfigMap.
          imagePullSecrets:
            - name: default-secret

  3. Create a workload.

    kubectl apply -f nginx-configmap.yaml

  4. After the workload runs properly, the following content is entered into the /usr/share/nginx/html/index.html file in the container:

    1. Run the following command to view the created pod:
      kubectl get pod | grep nginx-configmap
      Expected output:
      nginx-configmap-***   1/1     Running   0              2m18s
    2. Run the following command to view the environment variables in the pod:
      kubectl exec nginx-configmap-*** -- cat /usr/share/nginx/html/index.html

      Expected output:

      Hello CCE

Attaching a ConfigMap to the Workload Data Volume

The data stored in a ConfigMap can be referenced in a volume of type ConfigMap. You can mount such a volume to a specified container path. The platform supports the separation of workload codes and configuration files. ConfigMap volumes are used to store workload configuration parameters. Before that, create ConfigMaps in advance. For details, see Creating a ConfigMap.

Using the console

  1. Log in to the CCE console and click the cluster name to access the cluster console.
  2. In the navigation pane, choose Workloads. Then, click Create Workload.

    When creating a workload, click Data Storage in the Container Settings area. Click Add Volume and select ConfigMap from the drop-down list.

  3. Configure the parameters.

    Table 1 Mounting a ConfigMap volume

    Parameter

    Description

    ConfigMap

    Select the desired ConfigMap.

    A ConfigMap must be created in advance. For details, see Creating a ConfigMap.

    Add Container Path

    Configure the following parameters:
    1. Mount Path: Enter a path of the container, for example, /tmp.
      This parameter indicates the container path to which a data volume will be mounted. Do not mount the volume to a system directory such as / or /var/run; this action may cause container errors. You are advised to mount the volume to an empty directory. If the directory is not empty, ensure that there are no files that affect container startup. Otherwise, the files will be replaced, causing container startup failures or workload creation failures.
      NOTICE:

      If a volume is mounted to a high-risk directory, use an account with minimum permissions to start the container. Otherwise, high-risk files on the host machine may be damaged.

    2. Subpath: Enter a subpath, for example, tmp.
      • A subpath is used to mount a local volume so that the same data volume is used in a single pod. If this parameter is left blank, the root path is used by default.
      • The subpath can be the key and value of a ConfigMap or secret. If the subpath is a key-value pair that does not exist, the data import does not take effect.
      • The data imported by specifying a subpath will not be updated along with the ConfigMap/secret updates.
    3. Set the permission to Read-only. Data volumes in the path are read-only.

    You can click to add multiple paths and subpaths.

Using kubectl

  1. Use kubectl to connect to the cluster. For details, see Connecting to a Cluster Using kubectl.
  2. Create a file named nginx-configmap.yaml and edit it.

    vi nginx-configmap.yaml

    As shown in the following example, after the ConfigMap volume is mounted, a configuration file with the key as the file name and value as the file content is generated in the /etc/config directory of the container.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-configmap
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx-configmap
      template:
        metadata:
          labels:
            app: nginx-configmap
        spec:
          containers:
          - name: container-1
            image: nginx:latest
            volumeMounts:
            - name: config-volume
              mountPath: /etc/config            # Mount to the /etc/config directory.
              readOnly: true
        volumes:
        - name: config-volume
          configMap:
            name: cce-configmap                 # Name of the referenced ConfigMap.

  3. Create a workload.

    kubectl apply -f nginx-configmap.yaml

  4. After the workload runs properly, the SPECIAL_LEVEL and SPECIAL_TYPE files are generated in the /etc/config directory. The contents of the files are Hello and CCE, respectively.

    1. Run the following command to view the created pod:
      kubectl get pod | grep nginx-configmap
      Expected output:
      nginx-configmap-***   1/1     Running   0              2m18s
    2. Run the following command to view the SPECIAL_LEVEL or SPECIAL_TYPE file in the pod:
      kubectl exec nginx-configmap-*** -- /etc/config/SPECIAL_LEVEL

      Expected output:

      Hello

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback