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
Cloud Data Center
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
Domain Name Service
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
DataArts Studio
GaussDB(DWS)
Cloud Search Service
DataArts Lake Formation
DataArts Fabric
Data Ingestion Service
Data Lake Visualization
Data Lake Factory
IoT
IoT Device Access
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
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Industry Video Management Service
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
Huawei Cloud Astro Canvas
Huawei Cloud Astro Zero
CodeArts Governance
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 (CCI)
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
Meeting
AI
ModelArts
PanguLargeModels
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Cloud Transformation
Cloud Adoption Framework
Well-Architected Framework
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
MacroVerse aPaaS
CloudDevice
KooDrive

Service Accounts

Updated on 2025-08-22 GMT+08:00

All requests to Kubernetes go through the API server, and they require authentication and authorization before access is granted.

  • Authentication: authenticates user identities. Kubernetes uses different authentication rules for external and internal service accounts. For details, see Authentication and Service Accounts.
  • Authorization: controls user access to resources. Role-based access control (RBAC) is used to authorize users to access resources. For details, see RBAC.
Figure 1 API server authentication and authorization

Authentication and Service Accounts

Kubernetes users are classified as service accounts (ServiceAccounts) and common accounts.

  • A service account is bound to a namespace and associated with a set of credentials. When a pod is created, a token is mounted to the pod so that the pod can be called by the API server.
  • Kubernetes does not come with pre-built objects for managing common accounts. Instead, external services are used for this purpose. For example, CCE users are managed through Identity and Access Management (IAM).

Service accounts in Kubernetes are a kind of namespace-level resources, just like pods and ConfigMaps. When a namespace is created, the system automatically generates a service account named default in the namespace.

You can run the following command to check the service account:

kubectl get sa

NAME     SECRETS   AGE
default  1         30d
NOTE:
  • In clusters earlier than v1.21, tokens are obtained by mounting the secret of a service account to a pod. Such tokens are permanent. However, this approach is not recommended in clusters of v1.21 or later. Starting from v1.25, Kubernetes no longer automatically creates secrets for service accounts as part of its community iteration policy.

    Instead, in clusters of v1.21 and later, the recommended approach is to use the TokenRequest API to obtain tokens and mount them via a projected volume to pods. These tokens remain valid only for a fixed period and become invalid once the pods are deleted. For details, see Service Account Token Security Improvement.

  • If you need a token that never expires, you can manually manage secrets for service accounts. Although a permanent service account token can be created manually, you are advised to use a short-lived token by calling the TokenRequest API for better security.

In Kubernetes clusters earlier than v1.25, a secret was automatically generated for each service account. However, in clusters of v1.25 and later, no secret is automatically created for each service account. The following describes how to check the statuses of service accounts in clusters earlier than v1.25 and clusters of v1.25 or later.

  • In a cluster earlier than v1.25, run the following command to check the status of the default service account:

    kubectl describe sa default

    If information similar to the following is displayed, the default-token-vssmw secret has been automatically created:

    Name:                  default
    Namespace:             default
    Labels:                <none>
    Annotations:           <none>
    Image pull secrets:    <none>
    Mountable secrets:     default-token-vssmw
    Tokens:                default-token-vssmw
    Events:                <none>
  • In a cluster of v1.25 or later, run the following command to check the status of the default service account:

    kubectl describe sa default

    The command output shows no secret is automatically created for the default service account.
    Name:                     default
    Namespace:                default 
    Labels:                   <none>
    Annotations:              <none>
    Image pull secrets:       <none>
    Mountable secrets:        <none>
    Tokens:                   <none>
    Events:                   <none>

When defining a pod, you can assign a service account to it by specifying the account name in the file. If no account name is specified, the default service account will be used. When receiving a request with an authentication token, the API server uses the token to check whether the service account associated with the client that sends the request allows the request to be executed.

Creating a Service Account

  1. Create a service account in the default namespace. A v1.29 cluster is used in this example.

    kubectl create serviceaccount sa-example

    serviceaccount/sa-example created

    Check whether sa-example has been created. If sa-example is displayed in the NAME column, it has been created.

    kubectl get sa

    NAME            SECRETS   AGE
    default         1         30d
    sa-example      0         2s

    Because the cluster version used in this example is later than v1.25, the service account will not have a secret created automatically. To check if a secret has been created, use the command below to view the service account details. If the output shows none for Mountable secrets and Tokens, then no secret is automatically created for the service account.

    kubectl describe sa sa-example

    Name:                   sa-example
    Namespace:              default
    Labels:                 <none>
    Annotations:            <none>
    Image pull secrets:     <none>
    Mountable secrets:      <none>
    Tokens:                 <none>
    Events:                 <none>

  2. Manually create a secret named sa-example-token and associate it with the sa-example service account. By manually managing this secret, you can obtain a token that never expires.

    kubectl apply -f - <<EOF
    apiVersion: v1 
    kind: Secret 
    metadata:
      namespace: default   
      name: sa-example-token   
      annotations:     
        kubernetes.io/service-account.name: sa-example 
    type: kubernetes.io/service-account-token 
    EOF

  3. Check whether sa-example-token has been created. If sa-example-token is present in the secrets of the default namespace, then it has been created.

    kubectl get secrets

    NAME                        TYPE                                    DATA        AGE
    default-secret              kubernetes.io/dockerconfigjson          1           6d20h
    paas.elb                    cfe/secure-opaque                       1           6d20h
    sa-example-token            kubernetes.io/service-account-token     3           16s

    Check the secret content. You can see ca.crt, namespace, and token.

    kubectl describe secret sa-example-token

    Name:         sa-example-token
    Namespace:    default
    Labels:       <none>
    Annotations:  kubernetes.io/service-account.name: sa-example
                  kubernetes.io/service-account.uid: 4b7d3e19-1dfe-4ee0-bb49-4e2e0c3c5e25
    
    Type:  kubernetes.io/service-account-token
    
    Data
    ====
    ca.crt:     1123 bytes
    namespace:  7 bytes
    token:      eyJhbGciOiJSU...

  4. Check whether the service account has been associated with the new secret, meaning if the service account has obtained the token. The command output shows that sa-example is associated with sa-example-token.

    kubectl describe sa sa-example

    Name:                 sa-example
    Namespace:            default
    Labels:               <none>
    Annotations:          <none>
    Image pull secrets:   <none>
    Mountable secrets:    <none>
    Tokens:               sa-example-token
    Events:               <none>

Using a Service Account in a Pod

It is convenient to use a service account in a pod. You only need to specify the name of the service account. The following uses nginx:latest as an example to describe how to use a service account in a pod.

  1. Create a description file named sa-pod.yaml. mysql.yaml is an example file name. You can rename it to whatever you like.

    vim sa-pod.yaml

    NOTICE:

    To enable the pod to use the token from the manually created secret, you must mount the secret to the container. For details about how to mount the secret, see the code in bold in the file.

    The file content is as follows:

    apiVersion: v1
    kind: Pod
    metadata:
      name: sa-pod
    spec:
      serviceAccountName: sa-example                  #  Specify sa-example as the service account used by the pod.
      imagePullSecrets:
      - name: default-secret
      containers:
      - image: nginx:latest
        name: container-0
        resources:
          limits:
            cpu: 100m
            memory: 200Mi
          requests:
            cpu: 100m
            memory: 200Mi
        volumeMounts:                             #  Mount the storage volume named secret-volume to the pod.
        - name: secret-volume
          readOnly: true                          #  The mounted storage volume is read-only.
          mountPath: "/etc/secret-volume"         #  Mount path of the storage volume in the container. You can specify the value as needed.
      volumes:                                    #  Define a secret volume that can be used by the pod.
      - name: secret-volume                       #   Name of the secret volume. You can specify the value as needed.
        secret:                                   #  Set the type of the storage volume to secret.
          secretName: sa-example-token            #  Mount sa-example-token to the defined storage volume.

  2. Create a pod and view its details. You can see that sa-example-token is mounted to the pod. The pod uses the token for authentication.

    kubectl create -f sa-pod.yaml

    Information similar to the following is displayed:

    pod/sa-pod created

    Check whether the pod has been created.

    kubectl get pod

    In the command output, if sa-pod is in the Running state, the pod has been created.

    NAME                     READY   STATUS              RESTARTS   AGE
    sa-pod               1/1     running             0          5s

  3. View the sa-pod pod details and check whether sa-example-token has been mounted to the pod.

    kubectl describe pod sa-pod

    Information similar to the following is displayed:

    ...
    Containers:
      container-0:
        Container ID:   
        Image:          nginx:latest
        Image ID:       
        Port:           <none>
        Host Port:      <none>
        State:          Waiting
          Reason:       ImagePullBackOff
        Ready:          False
        Restart Count:  0
        Limits:
          cpu:     100m
          memory:  200Mi
        Requests:
          cpu:        100m
          memory:     200Mi
        Environment:  <none>
        Mounts:
           #  The sa-example-token has been mounted to the pod. The pod can use the token for authentication.
          /etc/secret-volume from secret-volume (ro)                                 
           #  Automatically mounted TokenRequest. It can provide a short-term token.
          /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-2s4sw (ro)  
    ...

    You can also run the command shown here to view the corresponding files in the pod. The path after cd needs to be secret-volume.

    kubectl exec -it sa-pod -- /bin/sh

    cd /etc/secret-volume

    ls

    Information similar to the following is displayed:

    ca.crt     namespace  token

  4. Verify that the manually created service account token can work.

    1. In a Kubernetes cluster, a Service named kubernetes is created for the API server by default. Pods can be accessed through this Service. After exiting the pod by pressing Ctrl+D, view the Service details.

      kubectl get svc

      Information similar to the following is displayed:

      NAME           TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
      kubernetes     ClusterIP   10.247.0.1       <none>        443/TCP          34
    2. Access the pod and check whether the pod can access pod resources in the cluster through the API server without using the token.

      kubectl exec -it sa-pod -- /bin/sh

      curl https://10.247.0.1:443/api/v1/namespaces/default/pods

      If information similar to the following is displayed, the pod cannot directly access pod resources in the cluster through the API server:

      curl: (60) SSL certificate problem: unable to get local issuer 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.
    3. Configure the environment variables of ca.crt. Add the path of ca.crt to the CURL_CA_BUNDLE environment variable. This variable instructs curl to use the certificate file as the trust anchor.

      export CURL_CA_BUNDLE = /etc/secret-volume/ca.crt

    4. Add the token content to TOKEN.

      TOKEN=$(cat /etc/secret-volume/token)

      Check whether TOKEN has been configured.

      echo $TOKEN

      If information similar to the following is displayed, the TOKEN has been configured:

      eyJhbGciOiJSUzI1NiIsImtpZCI6I...
    5. Access the API server using the configured TOKEN.

      curl -H "Authorization: Bearer $TOKEN" https://10.247.0.1:443/api/v1/namespaces/default/pods

      If information similar to the following is displayed, it means that the pod has been authenticated and the manually created service account token is in use. If the API server returns cannot get path \"/api/v1/namespaces/default/pods\"", the pod does not have sufficient permissions. The pod can only access the API server after being authorized. For details about the authorization mechanism, see RBAC.

      "kind": "PodList",
        "apiVersion": "v1",
        "metadata": {
          "resourceVersion": "13267712"
        },
        "items": [
          {
            "metadata": {
              "name": "hpa-example-77b9b446f6-nc7b6",
      ...

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
咨询盘古Doer

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback