This topic describes how to use ServiceAccount tokens to access Kubernetes clusters. This method is applicable to all types of Kubernetes clusters. This example uses a managed Kubernetes cluster.

Background information

Procedure

  1. Run the following command to obtain the internal endpoint of the API server:
    $ kubectl get endpoints kubernetes
    Internal endpoint
  2. Create the following kubernetes-public-service.yaml file. Set the ip parameter to the internal endpoint from step 1.
    apiVersion: v1
    kind: Service
    metadata:
      name: kubernetes-public
    spec:
      type: LoadBalancer
      ports:
      - name: https
        port: 443,
        protocol: TCP
        targetPort: 6443
    ---
    apiVersion: v1
    kind: Endpoints
    metadata:
      name: kubernetes-public
      namespace: default
    subsets:
    - addresses:
      - ip: <API Service address>  #Set this parameter to the internal endpoint from step 1.
      ports:
      - name: https
        port: 6443
        protocol: TCP
  3. Run the following command to deploy the public endpoints:
    $ kubectl apply -f kubernetes-public-service.yaml
  4. Run the following command to obtain the public IP of the SLB service, namely, EXTERNAL-IP:
    $ kubectl get service name
    Note The name in the command must be the same as the name in the kubernetes-public-service.yaml file from step 2. In this example, the name is set to kubernetes-public.
    Obtain the SLB public IP
  5. Run the following command to obtain the Secret corresponding to the ServiceAccount. In this example, the namespace parameter is set to default.
    $ kubectl get secret --namespace=namespace
    View Secret
  6. Run the following command to obtain the token:
    $ kubectl get secret -n --namespace=namespace -o jsonpath={.data.token} | base64 -d
    Note The namespace in the command must be the same as the namespace from step 5.
  7. Run the following command to access the managed Kubernetes cluster:
    $ curl -k -H 'Authorization: Bearer token' https://service-ip
    Note
    • The token is set to the value from step 6.
    • The service-ip is set to the public IP of the SLB service from step 4, namely, EXTERNAL-IP.

Result

After you run the command, the following message appears, indicating that you are connected to the cluster.Connection established