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
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 Secret

Updated on 2025-02-27 GMT+08:00

After secrets are created, they can be mounted as volumes or exposed as environment variables for a container.

NOTICE:

Do not perform any operation on the following secrets (for details, see Cluster Secrets):

  • Secrets under kube-system
  • default-secret and paas.elb in any namespace default-secret is used to pull private images from SWR, and paas.elb is used to connect the services in the namespace to ELB.

The following example shows how to use a secret.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  username: ******  #The value must be encoded using Base64.
  password: ******  #The value must be encoded using Base64.
NOTICE:
  • When a secret is used in a pod, it must be in the same cluster and namespace as the pod.
  • When a secret mounted as a volume is updated, Kubernetes updates the data in the volume at the same time.

    However, when a secret mounted using subPath is updated, Kubernetes cannot automatically update the data in the volume.

Configuring Environment Variables for a Workload

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 on the left, choose Workloads. In the upper right corner of the displayed page, click Create Workload.

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

    • Added from secret: Select a secret and import all keys in the secret as environment variables.

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

      For example, after you import the value of username in secret mysecret as the value of workload environment variable username, an environment variable named username exists in the container.

  3. Configure other workload parameters and click Create Workload.

    When the workload runs normally, log in to the container and run the following statement to check whether the secret has been set as an environment variable for the workload:

    printenv username

    If the output is the same as the content in the secret, the secret has been set as an environment variable for the workload.

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-secret.yaml and edit it.

    vi nginx-secret.yaml

    The content of the YAML file is as follows:

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

  3. Create a workload.

    kubectl apply -f nginx-secret.yaml

  4. View the environment variables in the pod.

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

      If the output is the same as the content in the secret, the secret has been set as an environment variable for the workload.

Configuring a Data Volume for a Workload

You can mount a secret as a volume to the specified container path. The content of a secret is user-defined. You need to create a secret in advance. For details, see Creating a Secret.

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 on the left, choose Workloads. Then click the Deployments tab. Click Create Workload in the upper right corner.

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

  3. Configure parameters for mounting a secret volume based on Table 1.

    Table 1 Parameters for mounting a secret volume

    Parameter

    Description

    Secret

    Select the desired secret.

    A secret must be created beforehand. For details, see Creating a Secret.

    Mount Path

    Enter a mount point. After the secret volume is mounted, a secret file with the key as the file name and value as the file content is generated in the mount path of the container.

    This parameter indicates the container path that the volume will be mounted to. Do not mount the volume to a system directory such as / or /var/run. This may cause container errors. Mount the volume to an empty directory. If the directory is not empty, ensure that there are no files that affect container startup. If there are such files, they will be replaced, which will lead to a container startup or workload creation failure.
    NOTICE:

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

    Subpath

    Enter a subpath of the mount path.

    • A subpath is used to mount a local volume so that the same 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 secret. If the subpath is a key-value pair that does not exist, the data import does not take effect.
    • The data imported using a subpath will not be updated along with the secret.

    Permission

    Read-only permission. The volume in the path is read-only.

    Figure 1 Mounting a secret volume

  4. Configure other parameters and click Create Workload.

    When the workload runs normally, the username and password files will be generated in the /etc/foo directory in this example. The file content is the secret values.

    Access the container and run the following statement to view the username or password file in the container:

    cat /etc/foo/username

    The expected output is the same as the content in the secret.

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-secret.yaml and edit it.

    vi nginx-secret.yaml

    In the following example, the username and password in the mysecret secret are saved in the /etc/foo directory as files.
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-secret
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx-secret
      template:
        metadata:
          labels:
            app: nginx-secret
        spec:
          containers:
          - name: container-1
            image: nginx:latest
            volumeMounts:
           - name: foo
             mountPath: /etc/foo          # Mount the secret volume to the /etc/foo directory.
             readOnly: true
        volumes:
        - name: foo
          secret:
            secretName: mysecret      # Name of the referenced secret.
    You can also use the items field to control the mapping path of secret keys. For example, store username in the /etc/foo/my-group/my-username directory in the container.
    NOTE:
    • If you use the items field to specify the mapping path of the secret keys, the keys that are not specified will not be created as files. In the following example, if the password key is not specified, the file will not be created.
    • If you want to use all keys in a secret, you must list all keys in the items field.
    • All keys listed in the items field must exist in the corresponding secret, or the volume will not be created.
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-secret
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx-secret
      template:
        metadata:
          labels:
            app: nginx-secret
        spec:
          containers:
          - name: container-1
            image: nginx:latest
            volumeMounts:
           - name: foo
             mountPath: /etc/foo          # Mount the secret volume to the /etc/foo directory.
             readOnly: true
        volumes:
        - name: foo
          secret:
            secretName: mysecret      # Name of the referenced secret.
            items:
            - key: username      # Name of the referenced key.
              path: my-group/my-username    # Mapping path of the secret key.

  3. Create a workload.

    kubectl apply -f nginx-secret.yaml

  4. Wait until the workload runs normally. The username and password files will be generated in the /etc/foo directory.

    1. Run the following command to view the created pod:
      kubectl get pod | grep nginx-secret
      Expected output:
      nginx-secret-***   1/1     Running   0              2m18s
    2. Run the following command to view the username or password file in the pod:
      kubectl exec nginx-secret-*** -- cat /etc/foo/username

      The expected output is the same as the content in the secret.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback