admission

一、static admission controllers

官方内置,启用就行

二、dynamic admission controllers

官方介绍

简单流程:

  • 创建一个web服务(tls)
  • 自签发证书
  • 创建Dockerfile和deployment service 文件
  • 创建MutatingWebhookConfiguration资源
  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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/bin/bash
name=mywebhook
namespace=mynamespace
go mod init ${name}
cat <<EOF > ./main.go
package main

import (
    "context"
    "encoding/json"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"

    admissionv1 "k8s.io/api/admission/v1"
    corev1 "k8s.io/api/core/v1"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type jsonPatch struct {
    OP    string      \`json:"op"\`
    Path  string      \`json:"path"\`
    Value interface{} \`json:"value"\`
}
s
func podsMutate(w http.ResponseWriter, r *http.Request) {
    admissionReviewReq := &admissionv1.AdmissionReview{}
    if err := json.NewDecoder(r.Body).Decode(admissionReviewReq); err != nil {
        return
    }

    pod := &corev1.Pod{}
    if err := json.Unmarshal(admissionReviewReq.Request.Object.Raw, pod); err != nil {
        return
    }

    labels := pod.Labels
    if pod.Labels == nil {
        labels = make(map[string]string)
    }
    labels["a"] = "1"
    var patchs []jsonPatch
    patchs = append(patchs, jsonPatch{
        OP:    "add",
        Path:  "/metadata/labels",
        Value: labels,
    })

    jsonPatchata, err := json.Marshal(patchs)
    if err != nil {
        return
    }

    patchType := admissionv1.PatchTypeJSONPatch

    resp := &admissionv1.AdmissionResponse{
        UID:       admissionReviewReq.Request.UID,
        Allowed:   true,
        Patch:     jsonPatchata,
        PatchType: &patchType,
    }

    admissionReviewResp := &admissionv1.AdmissionReview{
        TypeMeta: metav1.TypeMeta{
            Kind:       "AdmissionReview",
            APIVersion: "admission.k8s.io/v1",
        },
        Response: resp,
    }
    if err := json.NewEncoder(w).Encode(admissionReviewResp); err != nil {
        return
    }

}

func main() {

    mux := http.NewServeMux()
    server := &http.Server{
        Handler: mux,
    }

    mux.HandleFunc("/pods/mutate", podsMutate)

    ch := make(chan os.Signal, 1)
    signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        <-ch
        server.Shutdown(context.TODO())
    }()

    if err := server.ListenAndServeTLS("/etc/${name}/tls.crt", "/etc/${name}/tls.key"); err != nil &&
        err != http.ErrServerClosed {
        log.Fatalf("Failed to ListenAndServeTLS, err:%#v", err)
    }
}
EOF

go mod tidy



cat <<EOF > ./Dockerfile
FROM golang:alpine as builder
ENV GO111MODULE=on \
    GOPROXY=https://goproxy.cn,direct
ARG CONF=dev
WORKDIR /go/app
COPY go.mod .
COPY go.sum .
RUN go mod download
COPY main.go main.go
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o app .

FROM alpine:latest as prod
ARG CONF=dev
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && apk --no-cache add ca-certificates && apk add tzdata && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo "Asia/Shanghai" > /etc/timezone
WORKDIR /app/
COPY --from=0 /go/app/app .
CMD ["./app"]
EOF

docker build -t mywebhook:0.1 .



kubectl create ns ${namespace}

openssl genrsa -out ca.key 2048

openssl req -new -x509 -days 365 -key ca.key \
  -subj "/C=AU/CN=${name}"\
  -out ca.crt

openssl req -newkey rsa:2048 -nodes -keyout server.key \
  -subj "/C=AU/CN=${name}" \
  -out server.csr

openssl x509 -req \
  -extfile <(printf "subjectAltName=DNS:${name}.${namespace}.svc") \
  -days 365 \
  -in server.csr \
  -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out server.crt


kubectl create secret tls -n ${namespace} ${name} \
  --cert=server.crt \
  --key=server.key \
  --dry-run=client -o yaml \
  > ./secret.yaml


caBundle=`cat ca.crt | base64 | fold |awk BEGIN{RS=EOF}'{gsub(/\n/,"");print}'`
cat <<EOF > ./webhook.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
 name: ${name}
 namespace: ${namespace}
webhooks:
- name: ${name}.${namespace}.com
  failurePolicy: "Fail"
  matchPolicy: "Equivalent"
  rules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE","UPDATE"]
      resources: ["pods"]
      scope: "*"
  clientConfig:
    service:
      namespace: ${namespace}
      name: ${name}
      path: /pods/mutate
      port: 443
    caBundle: ${caBundle}
  admissionReviewVersions: ["v1", "v1beta1"]
  sideEffects: None
  timeoutSeconds: 10
  reinvocationPolicy: "Never"
EOF



cat <<EOF > ./deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${name}
  namespace: ${namespace}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ${name}
  template:
    metadata:
      labels:
        app: ${name}
    spec:
      containers:
        - image: ${name}:0.1
          imagePullPolicy: Never
          name: app
          volumeMounts:
            - name: tls
              mountPath: "/etc/${name}"
              readOnly: true
      volumes:
        - name: tls
          secret:
            secretName: ${name}
EOF


cat <<EOF > ./service.yaml
apiVersion: v1
kind: Service
metadata:
  name: ${name}
  namespace: ${namespace}
spec:
  type: ClusterIP
  ports:
    - port: 443
      protocol: TCP
      targetPort: 443
  selector:
    app: ${name}
EOF


cat <<EOF > ./demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: demo
  namespace: ${namespace}
spec:
  containers:
  - command:
       - sh
       - -c
       - 'sleep 10'
    image: busybox
    name: busybox
EOF

2. 部署webhook

1
2
3
4
5
6
kubectl apply -f secret.yaml
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f webhook.yaml

rm ca.crt ca.key ca.srl server.crt server.csr server.key

3. 部署demo

1
2
3
#创建webhook相关以及demo pod yaml
bash webhook.sh 
kubectl apply -f demo.yaml