1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| kubectl create ns secure-stack
kubectl create sa app-runner -n secure-stack
cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: app-role namespace: secure-stack rules: - apiGroups: [""] resources: ["configmaps"] verbs: ["get", "list"] resourceNames: ["app-config"] # 只能访问特定 ConfigMap --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: app-runner-binding namespace: secure-stack subjects: - kind: ServiceAccount name: app-runner namespace: secure-stack roleRef: kind: Role name: app-role apiGroup: rbac.authorization.k8s.io EOF
kubectl create configmap app-config -n secure-stack \ --from-literal=ENV=production
cat <<'EOF' | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: secure-web namespace: secure-stack spec: replicas: 2 selector: matchLabels: app: secure-web template: metadata: labels: app: secure-web spec: serviceAccountName: app-runner automountServiceAccountToken: false securityContext: runAsUser: 1001 runAsNonRoot: true fsGroup: 1001 containers: - name: web image: nginx:alpine securityContext: allowPrivilegeEscalation: false capabilities: drop: - ALL readOnlyRootFilesystem: false ports: - containerPort: 80 resources: requests: cpu: "100m" memory: "128Mi" limits: cpu: "200m" memory: "256Mi" livenessProbe: httpGet: path: / port: 80 readinessProbe: httpGet: path: / port: 80 EOF
kubectl expose deploy secure-web -n secure-stack --port=80
cat <<EOF | kubectl apply -f - apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: secure-web-policy namespace: secure-stack spec: podSelector: matchLabels: app: secure-web policyTypes: - Ingress - Egress ingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: ingress-nginx ports: - protocol: TCP port: 80 egress: - to: - namespaceSelector: {} podSelector: matchLabels: k8s-app: kube-dns ports: - protocol: UDP port: 53 EOF
kubectl get all -n secure-stack kubectl get networkpolicy -n secure-stack
|