Service account secret is not listed. How to fix it?

ghz 1years ago ⋅ 2170 views

Question

I have used kubectl create serviceaccount sa1 to create service account. Then I used kubectl get serviceaccount sa1 -oyaml command to get service account info. But it returns as below.

apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2022-05-16T08:03:50Z"
  name: sa1
  namespace: default
  resourceVersion: "19651"
  uid: fdddacba-be9d-4e77-a849-95ca243781cc

I need to get,

secrets:
- name: <secret>

part. but it doesn't return secrets. How to fix it?


Answer

In Kubernetes 1.24, ServiceAccount token secrets are no longer automatically generated. See ["Urgent Upgrade Notes" in the 1.24 changelog file](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.24.md#urgent- upgrade-notes):

The LegacyServiceAccountTokenNoAutoGeneration feature gate is beta, and enabled by default. When enabled, Secret API objects containing service account tokens are no longer auto-generated for every ServiceAccount. Use the [TokenRequest](https://kubernetes.io/docs/reference/kubernetes- api/authentication-resources/token-request-v1/) API to acquire service account tokens, or if a non-expiring token is required, create a Secret API object for the token controller to populate with a service account token by following this [guide](https://kubernetes.io/docs/concepts/configuration/secret/#service- account-token-secrets). (#108309, @zshihang)

This means, in Kubernetes 1.24, you need to [manually create the Secret](https://kubernetes.io/docs/concepts/configuration/secret/#service- account-token-secrets); the token key in the data field will be automatically set for you.

apiVersion: v1
kind: Secret
metadata:
  name: sa1-token
  annotations:
    kubernetes.io/service-account.name: sa1
type: kubernetes.io/service-account-token

Since you're manually creating the Secret, you know its name: and don't need to look it up in the ServiceAccount object.

This approach should work fine in earlier versions of Kubernetes too.