Coder3000
Coder3000

Reputation: 417

How to create a secret for service account using Kubernetes version 1.24

I am using Kubernetes version 1.24, I have created a secret for my service account manually, but when I run kubectl get serviceaccounts, it is showing that I do not have any secrets for that service account?

Upvotes: 4

Views: 8951

Answers (4)

Thuc Tran Van
Thuc Tran Van

Reputation: 65

#!/bin/bash

SA_NAME="${1}"

kubectl create sa "$SA_NAME"

# Generate a random string for the token name
TOKEN_NAME=$(openssl rand -hex 5)

kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: "${SA_NAME}-token-${TOKEN_NAME}"
  annotations:
    kubernetes.io/service-account.name: "$SA_NAME"
type: kubernetes.io/service-account-token
EOF
./create_sa.sh jenkins

It will create a service account with name "jenkins" and generate a token for this service account

Upvotes: 0

Harsh Manvar
Harsh Manvar

Reputation: 30083

If you are on K8s version 1.24

The serviceaccount won't create the secret automatically.

You have to create it manually.

kubectl create sa <serviceaccount-name>

Example :

apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
  name: token-secret
  annotations:
    kubernetes.io/service-account.name: "<SA name>"

If you just want to create the token you can use the : kubectl create token <Name>

Read more about it : https://medium.com/@harsh.manvar111/k8s-v1-24-is-unable-to-create-a-serviceaccount-secret-798f8454e6e7

Upvotes: 7

deckerch
deckerch

Reputation: 537

I had to search a little bit to get it all together: https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/

Mainly it's just creating a secret resource file secret.yaml.

apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
  name: <name of the secret>
  annotations:
    kubernetes.io/service-account.name: "<name of the serviceaccount>"
kubectl apply -f secret.yaml

And adding the secret to the service account.

# if you have already a serviceaccount you need only the edit line
kubectl create serviceaccount <name of the serviceaccount>
kubectl edit serviceaccount <name of the serviceaccount>

And then just add the created secret (last two lines):

apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2023-04-19T06:31:47Z"
  name: <name of the serviceaccount>
  namespace: default
  resourceVersion: "312345558"
  uid: 92f6ac28-cab4-41d2-b861-6e998a7cb644
secrets:
- name: <name of the manual created secret>

Upvotes: 4

zer0
zer0

Reputation: 2899

When creating a secret manually, it needs to be manually added to the ServiceAccount. You can use kubectl edit for this.

Upvotes: 0

Related Questions