How to Create a Service Account in Kubernetes: Step-by-Step Guide
To create a service account in Kubernetes, use the
kubectl create serviceaccount [NAME] command or define it in a YAML file with kind: ServiceAccount and apply it using kubectl apply -f [file]. This creates an identity for pods to access the Kubernetes API securely.Syntax
The basic syntax to create a service account using kubectl is:
kubectl create serviceaccount [NAME]: Creates a service account with the specified name in the current namespace.kubectl apply -f [filename].yaml: Applies a YAML manifest defining a service account.
The YAML manifest must include apiVersion, kind: ServiceAccount, and metadata.name.
bash
kubectl create serviceaccount my-service-account # OR using YAML apiVersion: v1 kind: ServiceAccount metadata: name: my-service-account
Example
This example shows how to create a service account named my-service-account using a YAML file and apply it to the cluster.
yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-service-account
namespace: defaultOutput
serviceaccount/my-service-account created
Common Pitfalls
Common mistakes when creating service accounts include:
- Not specifying the namespace, which defaults to
defaultbut may cause confusion if you expect another namespace. - Trying to create a service account with a name that already exists, which will cause an error.
- Forgetting to bind roles or permissions to the service account, so it has no access rights.
Always check the namespace and ensure role bindings are set if the service account needs permissions.
bash
kubectl create serviceaccount my-service-account # If this service account already exists, you get an error: # Error from server (AlreadyExists): serviceaccounts "my-service-account" already exists # Correct approach: Use apply with YAML to update or create kubectl apply -f service-account.yaml
Quick Reference
| Command/Field | Description |
|---|---|
| kubectl create serviceaccount [NAME] | Create a service account with the given name |
| kubectl apply -f [file].yaml | Create or update a service account from YAML file |
| apiVersion: v1 | API version for service account resource |
| kind: ServiceAccount | Defines the resource type as service account |
| metadata.name | Name of the service account |
| metadata.namespace | Namespace where the service account is created (optional, defaults to 'default') |
Key Takeaways
Use kubectl create or apply with YAML to create service accounts in Kubernetes.
Always specify the service account name and optionally the namespace.
Check for existing service accounts to avoid creation errors.
Service accounts need role bindings to have permissions in the cluster.
YAML manifests provide a reusable and clear way to manage service accounts.