Kubernetes 集群中创建一个包含 kubectl
命令的 Pod 通常用于管理和调试集群本身。这种 Pod 通常被称为“调试 Pod”或“管理 Pod”,它们的主要作用是允许从集群内部执行 Kubernetes 操作和管理任务。这可以在多种情况下非常有用:
1.创建一个名字空间(创建名字空间的目的是为了更好的隔离资源)
kubeclt create ns kubectl-admin
2.创建ServiceAccount
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-service-account
namespace: kubectl-admin
3.为ServiceAccount做RBAC权限绑定,我这里绑定的是cluster-admin的权限,当然实际情况下可以控制权限的绑定
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: admin-role-binding
subjects:
- kind: ServiceAccount
name: admin-service-account
namespace: kubectl-admin
roleRef:
kind: ClusterRole
name: cluster-admin
apiGroup: rbac.authorization.k8s.io
4.创建一个Deployment,运行容器
apiVersion: apps/v1
kind: Deployment
metadata:
name: kubectl-deployment
namespace: kubectl
spec:
replicas: 1
selector:
matchLabels:
app: kubectl-app
template:
metadata:
labels:
app: kubectl-app
spec:
serviceAccountName: admin-service-account
containers:
- name: kubectl-container
image: bitnami/kubectl
command: ["tail", "-f", "/dev/null"]
5进入容器测试kubectl命令
kubectl exec -it kubectl-deployment-576894d47-m6rws -n kubectl-admin -- /bin/bash
I have no name!@kubectl-deployment-576894d47-m6rws:/$ kubectl get ns
NAME STATUS AGE
cronjob Active 58d
default Active 183d
harbor Active 50d
harbor-private Active 57d
ingress-nginx Active 50d
ingress-test Active 50d
istio-system Active 50d
kube-node-lease Active 183d
kube-public Active 183d
kube-system Active 183d
kubectl Active 47m
mysql Active 4d9h
nginx-deployment Active 116d
pg Active 16d
pgg Active 10d
probe-test Active 116d
rook-ceph Active 41d
sonarqube Active 84d
I have no name!@kubectl-deployment-576894d47-m6rws:/$