Simplified everything. 42

This commit is contained in:
Jakub Vavřík
2021-06-28 17:40:08 +02:00
parent c02949b79d
commit 64b42bb818
9 changed files with 30 additions and 110 deletions

View File

@@ -57,4 +57,4 @@ Of note is also a fact that the chart runs a lookup to the connected cluster to
The `get` command should display _some_ non-empty result. The `get` command should display _some_ non-empty result.
## Releasing locally ## Releasing locally
To authenticate to the docker registry to push the images manually, you will need your own Github Personal Access Token. For more information follow this guide https://docs.github.com/en/packages/guides/migrating-to-github-container-registry-for-docker-images#authenticating-with-the-container-registry To authenticate to the docker registry to push the images manually, you will need your own Github Personal Access Token. For more information follow this guide https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-to-the-container-registry

View File

@@ -1,6 +1,7 @@
FROM alpine:3.13.4 FROM alpine:3.13.4
RUN apk add bash curl openssl \ RUN apk add bash curl openssl \
&& apk add --update coreutils jq \
&& curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" \ && curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" \
&& chmod 755 ./kubectl \ && chmod 755 ./kubectl \
&& mv ./kubectl /usr/bin/kubectl && mv ./kubectl /usr/bin/kubectl

View File

@@ -46,7 +46,7 @@ while [[ $# -gt 0 ]]; do
shift shift
done done
[ -z "${service}" ] && service=ips-injector-svc [ -z "${service}" ] && service=secret-duplicator-svc
[ -z "${secret}" ] && secret=descret-duplicator-webhook-certs [ -z "${secret}" ] && secret=descret-duplicator-webhook-certs
[ -z "${namespace}" ] && namespace=secret-duplicator [ -z "${namespace}" ] && namespace=secret-duplicator

View File

@@ -7,7 +7,7 @@ Expand the name of the chart.
{{- end }} {{- end }}
{{- define "secret-duplicator.serviceName" -}} {{- define "secret-duplicator.serviceName" -}}
ips-injector-svc secret-duplicator-svc
{{- end }} {{- end }}
{{- define "secret-duplicator.certificateSecretName" -}} {{- define "secret-duplicator.certificateSecretName" -}}

View File

@@ -13,6 +13,7 @@ spec:
containers: containers:
- name: pre-install-job - name: pre-install-job
image: "{{ .Values.certificateGeneratorImage.registry }}/{{ .Values.certificateGeneratorImage.repository }}:{{ .Values.certificateGeneratorImage.tag | default .Chart.AppVersion }}" image: "{{ .Values.certificateGeneratorImage.registry }}/{{ .Values.certificateGeneratorImage.repository }}:{{ .Values.certificateGeneratorImage.tag | default .Chart.AppVersion }}"
imagePullPolicy: Always
command: ["/entrypoint/entrypoint.sh"] command: ["/entrypoint/entrypoint.sh"]
args: args:
- --service - --service

View File

@@ -13,14 +13,14 @@ spec:
app: secret-duplicator app: secret-duplicator
template: template:
metadata: metadata:
labels: labels: {{- include "secret-duplicator.labels" . | nindent 8 }}
app: secret-duplicator app: secret-duplicator
spec: spec:
serviceAccountName: secret-duplicator serviceAccountName: secret-duplicator
containers: containers:
- name: secret-duplicator - name: secret-duplicator
image: "{{ .Values.image.registry }}/{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" image: "{{ .Values.image.registry }}/{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: IfNotPresent imagePullPolicy: Always
args: args:
- -alsologtostderr - -alsologtostderr
- -v=4 - -v=4

View File

@@ -15,11 +15,14 @@ webhooks:
path: "/mutate" path: "/mutate"
caBundle: {{ include "secret-duplicator.lookupCaBundle" . }} caBundle: {{ include "secret-duplicator.lookupCaBundle" . }}
rules: rules:
- operations: ["CREATE", "UPDATE"] - operations: ["CREATE"]
apiGroups: [""] apiGroups: [""]
apiVersions: ["v1"] apiVersions: ["v1"]
resources: ["serviceaccounts"] resources: ["namespaces"]
admissionReviewVersions: ["v1", "v1beta1"] admissionReviewVersions: ["v1", "v1beta1"]
namespaceSelector:
matchLabels:
gardener.cloud/role: shoot
sideEffects: None sideEffects: None
# The default "Fail" option prevents Gardener cluster to be hibernated # The default "Fail" option prevents Gardener cluster to be hibernated
failurePolicy: Ignore failurePolicy: Ignore

View File

@@ -18,7 +18,6 @@ rules:
- "" - ""
resources: resources:
- secrets - secrets
- serviceaccounts
verbs: verbs:
- list - list
- patch - patch

View File

@@ -7,6 +7,7 @@ import (
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
"net/http" "net/http"
"strings" "strings"
"time"
"github.com/golang/glog" "github.com/golang/glog"
"k8s.io/api/admission/v1beta1" "k8s.io/api/admission/v1beta1"
@@ -47,10 +48,6 @@ var (
metav1.NamespaceSystem, metav1.NamespaceSystem,
metav1.NamespacePublic, metav1.NamespacePublic,
} }
defaultServiceAccounts = []string{
"default",
}
) )
// NewWebhookServer constructor for WebhookServer // NewWebhookServer constructor for WebhookServer
@@ -86,12 +83,6 @@ func DefaultParametersObject() WhSvrParameters {
} }
} }
type patchOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
func init() { func init() {
_ = corev1.AddToScheme(runtimeScheme) _ = corev1.AddToScheme(runtimeScheme)
_ = admissionregistrationv1beta1.AddToScheme(runtimeScheme) _ = admissionregistrationv1beta1.AddToScheme(runtimeScheme)
@@ -100,66 +91,25 @@ func init() {
_ = v1.AddToScheme(runtimeScheme) _ = v1.AddToScheme(runtimeScheme)
} }
func addImagePullSecret(target, added []corev1.LocalObjectReference, basePath string) (patch []patchOperation) { // createSecret makes sure the target secret exists and contains annotations
first := len(target) == 0 func (whsvr *WebhookServer) createSecret(targetNamespace string) {
var value interface{} glog.Infof("Will wait 10sec before create secrets")
for _, add := range added { time.Sleep(time.Second * 10)
value = add glog.Infof("Will create secrets now")
path := basePath
if first {
first = false
value = []corev1.LocalObjectReference{add}
} else {
path = path + "/-"
}
patch = append(patch, patchOperation{
Op: "add",
Path: path,
Value: value,
})
}
return patch
}
// ensureSecrets looks up the target secret and makes sure the target secret exists and contains annotations
func (whsvr *WebhookServer) ensureSecrets(ar *v1beta1.AdmissionReview) error {
glog.Infof("Ensuring existing secrets")
targetNamespace := ar.Request.Namespace
glog.Infof("Looking for the existing target secret")
secret, err := whsvr.client.CoreV1().Secrets(targetNamespace).Get(whsvr.config.targetSecretName, metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
glog.Errorf("Could not fetch secret %s in namespace %s: %v", whsvr.config.targetSecretName, targetNamespace, err)
return err
}
if err != nil && errors.IsNotFound(err) {
glog.Infof("Target secret not found, creating a new one")
if _, createErr := whsvr.client.CoreV1().Secrets(targetNamespace).Create(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: whsvr.config.targetSecretName,
Namespace: targetNamespace,
},
Data: nil,
Type: corev1.SecretTypeOpaque,
}); createErr != nil {
glog.Errorf("Could not create secret %s in namespace %s: %v", whsvr.config.targetSecretName, targetNamespace, err)
return err
}
glog.Infof("Target secret created successfully")
return nil
}
glog.Infof("Target secret found, updating")
annotationData := strings.Split(whsvr.config.targetSecretAnnotation, "=") annotationData := strings.Split(whsvr.config.targetSecretAnnotation, "=")
secret.Annotations[annotationData[0]] = annotationData[1] if _, createErr := whsvr.client.CoreV1().Secrets(targetNamespace).Create(&corev1.Secret{
if _, err := whsvr.client.CoreV1().Secrets(targetNamespace).Update(secret); err != nil { ObjectMeta: metav1.ObjectMeta{
glog.Errorf("Could not update secret %s in namespace %s: %v", whsvr.config.targetSecretName, targetNamespace, err) Name: whsvr.config.targetSecretName,
return err Namespace: targetNamespace,
Annotations: map[string]string{annotationData[0]: annotationData[1]},
},
Data: nil,
Type: corev1.SecretTypeOpaque,
}); createErr != nil {
glog.Errorf("Could not create secret %s in namespace %s: %v", whsvr.config.targetSecretName, targetNamespace, createErr)
} }
glog.Infof("Target secret updated successfully") glog.Infof("Target secret created successfully")
return nil
} }
// shouldMutate goes through all filters and determines whether the incoming NS matches them // shouldMutate goes through all filters and determines whether the incoming NS matches them
@@ -196,42 +146,8 @@ func (whsvr *WebhookServer) mutateNamespace(ar *v1beta1.AdmissionReview) *v1beta
Allowed: true, Allowed: true,
} }
} }
secretList, err := whsvr.client.CoreV1().Secrets(ns.Name).List(metav1.ListOptions{
Watch: false,
})
if err != nil {
glog.Errorf("Could not get secret from namespace: %v", err)
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
// Check whether we already have configured secret with annotation present go whsvr.createSecret(ar.Request.Name)
if secretList != nil {
for _, item := range secretList.Items {
if item.Name == whsvr.config.targetSecretName {
annotationToCheck := strings.Split(whsvr.config.targetSecretAnnotation, "=")
if val, ok := item.Annotations[annotationToCheck[0]]; ok {
glog.Infof("Namespace is already in the correct state and contains secret %s with value %s=%s, skipping", whsvr.config.targetSecretName, annotationToCheck, val)
return &v1beta1.AdmissionResponse{
Allowed: true,
}
}
}
}
}
if err := whsvr.ensureSecrets(ar); err != nil {
glog.Errorf("Could not ensure existence of the secret")
glog.Errorf("Failing the mutation process")
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
return &v1beta1.AdmissionResponse{ return &v1beta1.AdmissionResponse{
Allowed: true, Allowed: true,