Last active
January 13, 2021 11:20
-
-
Save mohatb/7a468aaa30f81068f48145f10b94f417 to your computer and use it in GitHub Desktop.
create users in kubernetes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| CLUSTERNAME=mycluster.mydomain | |
| NAMESPACE=default | |
| USERNAME=myclusteruser | |
| GROUPNAME=mygroup | |
| openssl genrsa -out ${USERNAME}.key 2048 | |
| CSR_FILE=$USERNAME.csr | |
| KEY_FILE=$USERNAME.key | |
| openssl req -new -key $KEY_FILE -out $CSR_FILE -subj "/CN=$USERNAME/O=$GROUPNAME" | |
| CERTIFICATE_NAME=$USERNAME.$NAMESPACE | |
| cat <<EOF | kubectl create -f - | |
| apiVersion: certificates.k8s.io/v1beta1 | |
| kind: CertificateSigningRequest | |
| metadata: | |
| name: $CERTIFICATE_NAME | |
| spec: | |
| groups: | |
| - system:authenticated | |
| request: $(cat $CSR_FILE | base64 | tr -d '\n') | |
| usages: | |
| - digital signature | |
| - key encipherment | |
| - client auth | |
| EOF | |
| kubectl certificate approve $CERTIFICATE_NAME | |
| CRT_FILE=$USERNAME.crt | |
| kubectl get csr $CERTIFICATE_NAME -o jsonpath='{.status.certificate}' | base64 --decode > $CRT_FILE | |
| cat <<EOF | kubectl create -f - | |
| kind: Role | |
| apiVersion: rbac.authorization.k8s.io/v1beta1 | |
| metadata: | |
| namespace: $NAMESPACE | |
| name: deployment-manager | |
| rules: | |
| - apiGroups: ["", "extensions", "apps"] | |
| resources: ["deployments", "replicasets", "pods"] | |
| verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] # You can also use ["*"] | |
| EOF | |
| cat <<EOF | kubectl create -f - | |
| kind: RoleBinding | |
| apiVersion: rbac.authorization.k8s.io/v1beta1 | |
| metadata: | |
| name: $USERNAME-deployment-manager-binding | |
| namespace: $NAMESPACE | |
| subjects: | |
| - kind: User | |
| name: $USERNAME | |
| apiGroup: "" | |
| roleRef: | |
| kind: Role | |
| name: deployment-manager | |
| apiGroup: "" | |
| EOF | |
| kubectl config set-credentials $USERNAME \ | |
| --client-certificate=$(pwd)/$CRT_FILE \ | |
| --client-key=$(pwd)/$KEY_FILE | |
| kubectl config set-context $USERNAME-context --cluster=$CLUSTERNAME --namespace=$NAMESPACE --user=$USERNAME | |
| #kubectl config use-context $USERNAME-context #optional uncomment to switch to the user after the script |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment