Skip to content

Instantly share code, notes, and snippets.

@egeneralov
Last active October 24, 2019 21:30
Show Gist options
  • Select an option

  • Save egeneralov/9fcd8aedf984c6104a670f2f32af65d8 to your computer and use it in GitHub Desktop.

Select an option

Save egeneralov/9fcd8aedf984c6104a670f2f32af65d8 to your computer and use it in GitHub Desktop.
#!/bin/bash -e
NAMESPACE=$1
cat << EOF | kubectl apply -f -
---
apiVersion: v1
kind: Namespace
metadata:
name: ${NAMESPACE}
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${NAMESPACE}-user
namespace: ${NAMESPACE}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: ${NAMESPACE}-user-full-access
namespace: ${NAMESPACE}
rules:
- apiGroups: ["", "extensions", "apps", "autoscaling"]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["batch"]
resources:
- jobs
- cronjobs
verbs: ["*"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: ${NAMESPACE}-user-view
namespace: ${NAMESPACE}
subjects:
- kind: ServiceAccount
name: ${NAMESPACE}-user
namespace: ${NAMESPACE}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: ${NAMESPACE}-user-full-access
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: ${NAMESPACE}
rules:
- apiGroups:
- admissionregistration.k8s.io
resources:
- validatingwebhookconfigurations
- mutatingwebhookconfigurations
verbs:
- get
- list
- watch
- apiGroups:
- ""
resources:
- namespaces
verbs:
- get
- list
- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ${NAMESPACE}
roleRef:
kind: ClusterRole
apiGroup: rbac.authorization.k8s.io
name: ${NAMESPACE}
subjects:
- kind: ServiceAccount
namespace: ${NAMESPACE}
name: ${NAMESPACE}-user
EOF
TOKEN_NAME=$(kubectl -n ${NAMESPACE} describe sa ${NAMESPACE}-user | grep Tokens | awk '{print $2}')
TOKEN=$(kubectl -n ${NAMESPACE} get secret ${TOKEN_NAME} -o "jsonpath={.data.token}" | base64 --decode)
CA=$(kubectl -n ${NAMESPACE} get secret ${TOKEN_NAME} -o "jsonpath={.data['ca\.crt']}")
cat << EOF > ${NAMESPACE}-kubeconfig.yaml
apiVersion: v1
kind: Config
preferences: {}
# Define the cluster
clusters:
- cluster:
certificate-authority-data: ${CA}
server: https://127.0.0.1:6443
name: my-cluster
# Define the user
users:
- name: ${NAMESPACE}-user
user:
as-user-extra: {}
token: ${TOKEN}
# Define the context: linking a user to a cluster
contexts:
- context:
cluster: my-cluster
namespace: ${NAMESPACE}
user: ${NAMESPACE}-user
name: ${NAMESPACE}
# Define current context
current-context: ${NAMESPACE}
EOF
echo ${PWD}/${NAMESPACE}-kubeconfig.yaml
ls -lha ${NAMESPACE}-kubeconfig.yaml
echo kubectl --kubeconfig=${NAMESPACE}-kubeconfig.yaml get pods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment