The Role lives in booknest; the ServiceAccount lives in jenkins. A RoleBinding in booknest joins them, generated here by kubectl 5,150 create --dry-run rather than typed:
echo --- >> k8s/deployer-rbac.yaml
kubectl create rolebinding booknest-deployer --role=booknest-deployer \
--serviceaccount=jenkins:jenkins --dry-run=client -o yaml | grep -v creationTimestamp \
>> k8s/deployer-rbac.yaml
yq 'select(.kind == "RoleBinding") | {"roleRef": .roleRef.name, "subjects": .subjects}' \
k8s/deployer-rbac.yaml
kubectl apply -f k8s/deployer-rbac.yamlOutput
roleRef: booknest-deployer
subjects:
- kind: ServiceAccount
name: jenkins
namespace: jenkins
role.rbac.authorization.k8s.io/booknest-deployer created
rolebinding.rbac.authorization.k8s.io/booknest-deployer createdTest it the way Jenkins 8,793 will use it, with a short-lived token and no other credentials:
T=$(kubectl create token jenkins -n jenkins --duration=10m)
kubectl config view --raw --minify \
-o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d > ~/ca.crt
jk() { kubectl --kubeconfig=/dev/null -s https://127.0.0.1:33443 \
--certificate-authority ~/ca.crt --token "$T" -n booknest "$@"; }
jk auth whoami | grep Username
jk rollout restart deployment/web
jk rollout status deployment/web | tail -1
jk get secrets 2>&1 | fold -s -w 90
jk delete deployment web 2>&1 | fold -s -w 90
git add k8s/deployer-rbac.yaml
git commit -qm "Let Jenkins deploy BookNest with a least-privilege Role"Output
Username system:serviceaccount:jenkins:jenkins deployment.apps/web restarted deployment "web" successfully rolled out Error from server (Forbidden): secrets is forbidden: User "system:serviceaccount:jenkins:jenkins" cannot list resource "secrets" in API group "" in the namespace "booknest" Error from server (Forbidden): deployments.apps "web" is forbidden: User "system:serviceaccount:jenkins:jenkins" cannot delete resource "deployments" in API group "apps" in the namespace "booknest"
k8s/namespace.yaml, the RBAC files and the Secrets stay with administrators. In Jenkins (Kubernetes Pod Templates), use this account with a token requested per build rather than the long-lived one from Connecting Jenkins.