Creating and using Kubernetes service accounts
Create the appropriate service accounts and import into your kube.config
This is going to be a quick walkthrough on how to create a service account that you can then use in another application or service to access your cluster. One thing to note, a service account is only good for a single namespace. If you need to deploy to your “apps” and your “infrastructure” namesspaces you will need a separate service account for both namespaces.
This config will not go into the nuances of access control. This is just to get you started. Note, under the rules section I have * for access which will give your service account full access to the entire namespace. Usually you would not want that
# Creates a service account in the app namespace
apiVersion: v1
kind: ServiceAccount
metadata:
name: apps-service-account
namespace: apps
---
# Create a role in the apps namespace
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: apps-role
namespace: apps
rules:
- apiGroups:
- '*'
resources:
- '*'
verbs:
- '*'
---
# Attach the role to the service account
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: apps-role-binding
namespace: apps
subjects:
- namespace: apps
kind: ServiceAccount
name: apps-service-account
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: apps-role
---
# Create a sercret with the credentials of the service account
apiVersion: v1
kind: Secret
metadata:
name: apps-service-account-token
namespace: apps
annotations:
kubernetes.io/service-account.name: apps-service-account
type: kubernetes.io/service-account-token
After you add those manifests you’ll want to grab the secrets value from your cluster. In this example the secret would be named apps-service-account
and the value we are looking for is token
. Next we need to encode this token. If you want to be secure you should do this offline. For the sake of going the easier route we will be using this site. All you need to do now is create a kube config and enter your encoded token
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: YOUR CLUSTER CA
server: YOUR CLUSTER IP:PORT
name: default
contexts:
context:
- cluster: default
user: default
name: default
current-context: default
kind: Config
preferences: {}
users:
name: default
user:
token: YOUR ENCODED TOKEN
Some of the formatting might be spotty for that kube config. If you have trouble reading it, you can copy an existing kube config for your cluster, and change the user key at the bottom to
user:
token: ENCODED_TOKEN