Compare commits

...

23 Commits

Author SHA1 Message Date
Martin Šalata
c97fc465e8 Add devel to the docker releases 2021-04-05 21:01:32 +02:00
Martin Šalata
1523ba232b Set cron job to run once a week 2021-04-05 09:06:41 +02:00
Martin Šalata
42be5e1041 Ignore webhook failures to allow entering hibernation 2021-04-04 21:23:00 +02:00
Martin Šalata
5d9930238a Fix apiGroup of certificatesigningrequests 2021-04-04 21:09:13 +02:00
Martin Šalata
ed1b29e8b5 Make CertificateSigningRequest namespaced 2021-04-04 20:36:21 +02:00
Martin Šalata
761a43ed1f Fix certificate generation script arguments 2021-04-04 20:26:44 +02:00
Martin Šalata
4e360ac34f Bump docker and helm versions 2021-04-04 18:47:19 +02:00
Martin Šalata
ee0e41ff32 Add secret type in readme 2021-04-04 18:47:02 +02:00
Martin Šalata
6c4db7d4d1 Standardize secret names 2021-04-04 18:45:24 +02:00
Martin Šalata
c7708d06e5 Add info to readme 2021-04-04 18:24:50 +02:00
Martin Šalata
7b45185392 Bump the chart version to 0.0.6 2021-04-03 13:39:16 +02:00
Martin Šalata
7b2c52406e Allow ignoring secret creating errors to preserve _some_ k8s functionality in case of issues 2021-04-03 13:38:21 +02:00
Martin Šalata
9219b83a9b Parametrize target secret name 2021-04-03 13:32:06 +02:00
Martin Šalata
184e0d3c07 Fix make fmt target 2021-04-03 13:25:27 +02:00
Martin Šalata
c8b6950f98 Fix chart-releaser condition 2021-04-02 23:57:56 +02:00
Martin Šalata
af6d743799 Fix chart-releaser condition 2021-04-02 23:54:59 +02:00
Martin Šalata
c8b307852f Bump images version 2021-04-02 23:48:27 +02:00
Martin Šalata
49a95747e6 Make helm releaser more robust 2021-04-02 23:44:16 +02:00
Martin Šalata
c80ce5e9a6 Setup release of docker images to dockerhub 2021-04-02 23:15:08 +02:00
Martin Šalata
cfa76c2953 Make make target naming matching 2021-04-02 22:57:47 +02:00
Martin Šalata
ed73fc0e65 Remove setup make step 2021-04-02 22:51:36 +02:00
Martin Šalata
9e86a2da44 Fix go build parentheses 2021-04-02 22:48:10 +02:00
Martin Šalata
efeb131dd1 Add a Github workflow for building docker images 2021-04-02 22:45:52 +02:00
16 changed files with 160 additions and 62 deletions

55
.github/workflows/release-chart.yaml vendored Normal file
View File

@@ -0,0 +1,55 @@
name: Release Charts
on:
push:
branches:
- main
# TODO: add this back
# paths:
# - 'helm/**'
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
with:
ref: main
- name: Configure Git
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
- name: Install Helm
uses: azure/setup-helm@v1
with:
version: v3.4.0
- name: Helm version checker
id: helm_version_checker
continue-on-error: true
run: |
helm repo add imagepullsecret-injector https://ysoftdevs.github.io/imagepullsecret-injector
helm repo update
newVersion="$(helm show chart helm/imagepullsecret-injector | grep version: | awk '{print $2}')"
echo "Trying to upload version $newVersion"
uploadedVersions="$(helm search repo imagepullsecret-injector/imagepullsecret-injector -l | tail -n +2 | awk '{print $2}')"
echo "Found these versions in upstream: $uploadedVersions"
for uploadedVersion in $uploadedVersions; do
if [ "$newVersion" == "$uploadedVersion" ]; then
echo "Found a matching version in upstream, failing this task and skipping the release"
exit 1
fi
done
echo "No matching version found, running the release"
- name: Run chart-releaser
if: steps.helm_version_checker.outcome == 'success'
uses: helm/chart-releaser-action@master
with:
charts_dir: 'helm'
env:
CR_TOKEN: '${{ secrets.CR_TOKEN }}'

View File

@@ -1,11 +1,10 @@
name: Release Charts
name: Release docker images
on:
push:
branches:
- main
paths:
- 'helm/**'
- devel
jobs:
release:
@@ -21,14 +20,11 @@ jobs:
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
- name: Install Helm
uses: azure/setup-helm@v1
with:
version: v3.4.0
- name: Run chart-releaser
uses: helm/chart-releaser-action@master
with:
charts_dir: 'helm'
- name: Build and push docker images (make image)
run: make image
env:
CR_TOKEN: '${{ secrets.CR_TOKEN }}'
DOCKER_USER: '${{ secrets.DOCKER_USER }}'
DOCKER_TOKEN: '${{ secrets.DOCKER_TOKEN }}'
- name: Logout from dockerhub (make docker-logout)
run: make docker-logout

View File

@@ -18,7 +18,7 @@ export GOPATH ?= $(GOPATH_DEFAULT)
TESTARGS_DEFAULT := "-v"
export TESTARGS ?= $(TESTARGS_DEFAULT)
DEST := $(GOPATH)/src/$(GIT_HOST)/$(BASE_DIR)
IMAGE_TAG ?= $(shell cat "$(REPO_ROOT)/VERSION")-$(shell git describe --match=$(git rev-parse --short=8 HEAD) --tags --always --dirty)
IMAGE_TAG ?= $(shell cat "$(REPO_ROOT)/VERSION")
LOCAL_OS := $(shell uname)
@@ -45,7 +45,7 @@ endif
############################################################
fmt:
@echo "Run go fmt..."
@go fmt ./cmd/...
############################################################
# lint section
@@ -78,9 +78,15 @@ build-linux:
# image section
############################################################
image: build-image push-image
image: docker-login build-image push-image
build-image: build-linux
docker-login:
@echo ${DOCKER_TOKEN} | docker login -u ${DOCKER_USER} --password-stdin
docker-logout:
@docker logout
build-image:
@echo "Building the docker image: $(IMAGE_REPO)/$(IMAGE_NAME):$(IMAGE_TAG)..."
@docker build -t $(IMAGE_REPO)/$(IMAGE_NAME):$(IMAGE_TAG) -f build/Dockerfile .
@echo "Building the docker image: $(IMAGE_REPO)/$(GENERATOR_IMAGE_NAME):$(IMAGE_TAG)..."

View File

@@ -2,6 +2,12 @@
The responsibility of this webhook is to patch all newly created/updated service account and make sure they all contained proper imagepullsecret configuration.
This repo produces one helm chart available via helm repository https://ysoftdevs.github.io/imagepullsecret-injector. There are also 2 docker images:
- `marshallmarshall/imagepullsecret-injector` - the image containing the webhook itself
- `marshallmarshall/webhook-cert-generator` - helper image responsible for (re)generating the certificates
## Helm description
The helm chart consists of 2 parts: the certificate generator and the webhook configuration itself.
@@ -21,22 +27,35 @@ The main part is the deployment and the web hook configuration. The flow is as f
Of note is also a fact that the chart runs a lookup to the connected cluster to fetch the CA bundle for the MutatingWebhook. This means `helm template` won't work.
## Running locally
```bash
kubectl create ns imagepullsecret-injector
1. Create the prerequisite resources:
```bash
kubectl create ns imagepullsecret-injector
kubectl create secret -n imagepullsecret-injector \
generic my-cool-secret-source \
--from-literal=.dockerconfigjson='<your .dockerconfigjson configuration file>'
kubectl create secret -n imagepullsecret-injector \
generic acr-dockerconfigjson-source \
--type=kubernetes.io/dockerconfigjson \
--from-literal=.dockerconfigjson='<your .dockerconfigjson configuration file>'
```
make build-image
helm upgrade -i imagepullsecret-injector \
--create-namespace -n imagepullsecret-injector \
helm/imagepullsecret-injector
```
1. Build the images and run the chart
``` bash
make build-image
helm upgrade -i imagepullsecret-injector \
-n imagepullsecret-injector \
helm/imagepullsecret-injector
```
Alternatively, you can use the pre-built, publicly available helm chart and docker images:
```bash
helm repo add imagepullsecret-injector https://ysoftdevs.github.io/imagepullsecret-injector
helm repo update
helm upgrade -i imagepullsecret-injector \
-n imagepullsecret-injector \
magepullsecret-injector/imagepullsecret-injector
```
To test whether everything works, you can run
```bash
kubectl create ns yolo
kubectl get sa -n yolo default -ojsonpath='{.imagePullSecrets}'
```
The get command should display _some_ non-empty result.
1. To test whether everything works, you can run
```bash
kubectl create ns yolo
kubectl get sa -n yolo default -ojsonpath='{.imagePullSecrets}'
```
The `get` command should display _some_ non-empty result.

View File

@@ -1 +1 @@
v0.0.1
0.0.9

View File

@@ -1,4 +1,4 @@
FROM golang:1.14 AS builder
FROM golang:1.15 AS builder
WORKDIR /go/src/github.com/ysoftdevs/imagepullsecret-injector
COPY . .

View File

@@ -51,9 +51,11 @@ func main() {
flag.StringVar(&parameters.keyFile, "tlsKeyFile", LookupStringEnv("CONFIG_KEY_PATH", parameters.keyFile), "File containing the x509 private key to --tlsCertFile.")
flag.StringVar(&parameters.excludeNamespaces, "excludeNamespaces", LookupStringEnv("CONFIG_EXCLUDE_NAMESPACES", parameters.excludeNamespaces), "Comma-separated namespace names to ignore.")
flag.StringVar(&parameters.serviceAccounts, "serviceAccounts", LookupStringEnv("CONFIG_SERVICE_ACCOUNTS", parameters.serviceAccounts), "Comma-separated service account names to watch.")
flag.StringVar(&parameters.targetImagePullSecretName, "targetImagePullSecretName", LookupStringEnv("CONFIG_TARGET_IMAGE_PULL_SECRET_NAME", parameters.targetImagePullSecretName), "Name of the imagePullSecret secret we will create in the namespace of the mutated service account")
flag.StringVar(&parameters.sourceImagePullSecretName, "sourceImagePullSecretName", LookupStringEnv("CONFIG_SOURCE_IMAGE_PULL_SECRET_NAME", parameters.sourceImagePullSecretName), "Name of the imagePullSecret secret we use as source.")
flag.StringVar(&parameters.sourceImagePullSecretNamespace, "sourceImagePullSecretNamespace", LookupStringEnv("CONFIG_SOURCE_IMAGE_PULL_SECRET_NAMESPACE", parameters.sourceImagePullSecretNamespace), "Namespace of the imagePullSecret secret we use as source.")
flag.BoolVar(&parameters.allServiceAccounts, "allServiceAccounts", LookupBoolEnv("CONFIG_ALL_SERVICE_ACCOUNTS", parameters.allServiceAccounts), "Switch for watching all service accounts. If true, serviceAccounts parameter is ignored")
flag.BoolVar(&parameters.ignoreSecretCreationError, "ignoreSecretCreationError", LookupBoolEnv("CONFIG_IGNORE_SECRET_CREATION_ERROR", parameters.ignoreSecretCreationError), "If true, failed creation/update of secrets in the target namespace will not cause the webhook to fail")
flag.Parse()
glog.Infof("Running with config: %+v", parameters)

View File

@@ -27,10 +27,6 @@ var (
deserializer = codecs.UniversalDeserializer()
)
const (
imagePullSecretName = "my-cool-secret"
)
type WebhookServer struct {
server *http.Server
config *WhSvrParameters
@@ -44,8 +40,10 @@ type WhSvrParameters struct {
excludeNamespaces string
serviceAccounts string
allServiceAccounts bool
targetImagePullSecretName string
sourceImagePullSecretName string
sourceImagePullSecretNamespace string
ignoreSecretCreationError bool
}
var (
@@ -67,8 +65,10 @@ func DefaultParametersObject() WhSvrParameters {
excludeNamespaces: strings.Join(defaultIgnoredNamespaces, ","),
serviceAccounts: strings.Join(defaultServiceAccounts, ","),
allServiceAccounts: false,
targetImagePullSecretName: "my-cool-secret",
sourceImagePullSecretName: "my-cool-secret-source",
sourceImagePullSecretNamespace: "default",
ignoreSecretCreationError: false,
}
}
@@ -149,9 +149,9 @@ func (whsvr *WebhookServer) ensureSecrets(ar *v1beta1.AdmissionReview) error {
glog.Infof("Source secret found")
glog.Infof("Looking for the existing target secret")
secret, err := clientset.CoreV1().Secrets(namespace).Get(imagePullSecretName, metav1.GetOptions{})
secret, err := clientset.CoreV1().Secrets(namespace).Get(whsvr.config.targetImagePullSecretName, metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
glog.Errorf("Could not fetch secret %s in namespace %s: %v", imagePullSecretName, namespace, err)
glog.Errorf("Could not fetch secret %s in namespace %s: %v", whsvr.config.targetImagePullSecretName, namespace, err)
return err
}
@@ -159,13 +159,13 @@ func (whsvr *WebhookServer) ensureSecrets(ar *v1beta1.AdmissionReview) error {
glog.Infof("Target secret not found, creating a new one")
if _, createErr := clientset.CoreV1().Secrets(namespace).Create(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: imagePullSecretName,
Name: whsvr.config.targetImagePullSecretName,
Namespace: namespace,
},
Data: sourceSecret.Data,
Type: sourceSecret.Type,
}); createErr != nil {
glog.Errorf("Could not create secret %s in namespace %s: %v", imagePullSecretName, namespace, err)
glog.Errorf("Could not create secret %s in namespace %s: %v", whsvr.config.targetImagePullSecretName, namespace, err)
return err
}
glog.Infof("Target secret created successfully")
@@ -175,7 +175,7 @@ func (whsvr *WebhookServer) ensureSecrets(ar *v1beta1.AdmissionReview) error {
glog.Infof("Target secret found, updating")
secret.Data = sourceSecret.Data
if _, err := clientset.CoreV1().Secrets(namespace).Update(secret); err != nil {
glog.Errorf("Could not update secret %s in namespace %s: %v", imagePullSecretName, namespace, err)
glog.Errorf("Could not update secret %s in namespace %s: %v", whsvr.config.targetImagePullSecretName, namespace, err)
return err
}
glog.Infof("Target secret updated successfully")
@@ -230,7 +230,7 @@ func (whsvr *WebhookServer) mutateServiceAccount(ar *v1beta1.AdmissionReview) *v
if sa.ImagePullSecrets != nil {
glog.Infof("ServiceAccount is already in the correct state, skipping")
for _, lor := range sa.ImagePullSecrets {
if imagePullSecretName == lor.Name {
if whsvr.config.targetImagePullSecretName == lor.Name {
return &v1beta1.AdmissionResponse{
Allowed: true,
}
@@ -241,7 +241,7 @@ func (whsvr *WebhookServer) mutateServiceAccount(ar *v1beta1.AdmissionReview) *v
glog.Infof("ServiceAccount is missing ImagePullSecrets configuration, creating a patch")
var patch []patchOperation
patch = append(patch, addImagePullSecret(sa.ImagePullSecrets, []corev1.LocalObjectReference{{Name: imagePullSecretName}}, "/imagePullSecrets")...)
patch = append(patch, addImagePullSecret(sa.ImagePullSecrets, []corev1.LocalObjectReference{{Name: whsvr.config.targetImagePullSecretName}}, "/imagePullSecrets")...)
patchBytes, err := json.Marshal(patch)
if err != nil {
glog.Errorf("Could not marshal patch object: %v", err)
@@ -254,11 +254,15 @@ func (whsvr *WebhookServer) mutateServiceAccount(ar *v1beta1.AdmissionReview) *v
if err := whsvr.ensureSecrets(ar); err != nil {
glog.Errorf("Could not ensure existence of the imagePullSecret")
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
if !whsvr.config.ignoreSecretCreationError {
glog.Errorf("Failing the mutation process")
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
glog.Infof("ignoreSecretCreationError is true, ignoring")
}
return &v1beta1.AdmissionResponse{

View File

@@ -15,9 +15,9 @@ type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.0.4
version: 0.0.15
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
appVersion: v0.0.1
appVersion: 0.0.9

View File

@@ -89,6 +89,7 @@ apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: ${csrName}
namespace: ${namespace}
spec:
signerName: kubernetes.io/kubelet-serving
groups:

View File

@@ -5,7 +5,7 @@ metadata:
labels:
{{- include "imagepullsecret-injector.labels" . | nindent 4 }}
spec:
schedule: '* * * * *'
schedule: '* * * * 0'
jobTemplate:
metadata:
name: "{{ .Release.Name }}"
@@ -21,9 +21,12 @@ spec:
image: "{{ .Values.certificateGeneratorImage.registry }}/{{ .Values.certificateGeneratorImage.repository }}:{{ .Values.certificateGeneratorImage.tag | default .Chart.AppVersion }}"
command: ["/entrypoint/entrypoint.sh"]
args:
- --service="{{ include "imagepullsecret-injector.serviceName" . }}"
- --namespace="{{ .Release.Namespace }}"
- --secret="{{ include "imagepullsecret-injector.certificateSecretName" . }}"
- --service
- "{{ include "imagepullsecret-injector.serviceName" . }}"
- --namespace
- "{{ .Release.Namespace }}"
- --secret
- "{{ include "imagepullsecret-injector.certificateSecretName" . }}"
volumeMounts:
- mountPath: "/entrypoint"
name: entrypoint

View File

@@ -14,9 +14,12 @@ spec:
image: "{{ .Values.certificateGeneratorImage.registry }}/{{ .Values.certificateGeneratorImage.repository }}:{{ .Values.certificateGeneratorImage.tag | default .Chart.AppVersion }}"
command: ["/entrypoint/entrypoint.sh"]
args:
- --service="{{ include "imagepullsecret-injector.serviceName" . }}"
- --namespace="{{ .Release.Namespace }}"
- --secret="{{ include "imagepullsecret-injector.certificateSecretName" . }}"
- --service
- "{{ include "imagepullsecret-injector.serviceName" . }}"
- --namespace
- "{{ .Release.Namespace }}"
- --secret
- "{{ include "imagepullsecret-injector.certificateSecretName" . }}"
volumeMounts:
- mountPath: "/entrypoint"
name: entrypoint

View File

@@ -30,15 +30,16 @@ rules:
- list
- get
- apiGroups:
- "certificates.k8s.io/v1"
- certificates.k8s.io
resources:
- certificatesigningrequests
verbs:
- create
- list
- get
- delete
- apiGroups:
- "certificates.k8s.io/v1"
- certificates.k8s.io
resources:
- certificatesigningrequests/approval
verbs:

View File

@@ -36,10 +36,14 @@ spec:
value: {{ join "," .Values.imagepullsecretInjector.excludeNamespaces | quote }}
- name: CONFIG_SERVICE_ACCOUNTS
value: {{ join "," .Values.imagepullsecretInjector.saNames | quote }}
- name: CONFIG_TARGET_IMAGE_PULL_SECRET_NAME
value: {{ .Values.imagepullsecretInjector.targetSecretName | quote }}
- name: CONFIG_SOURCE_IMAGE_PULL_SECRET_NAME
value: {{ .Values.imagepullsecretInjector.dockerconfigjsonRef.secretName | quote }}
- name: CONFIG_SOURCE_IMAGE_PULL_SECRET_NAMESPACE
value: {{ .Values.imagepullsecretInjector.dockerconfigjsonRef.secretNamespace | default .Release.Namespace | quote }}
- name: CONFIG_IGNORE_SECRET_CREATION_ERROR
value: {{ .Values.imagepullsecretInjector.ignoreSecretCreationError | quote }}
- name: CONFIG_ALL_SERVICE_ACCOUNTS
value: {{ .Values.imagepullsecretInjector.allSaNames | quote }}
volumeMounts:

View File

@@ -21,3 +21,5 @@ webhooks:
resources: ["serviceaccounts"]
admissionReviewVersions: ["v1", "v1beta1"]
sideEffects: None
# The default "Fail" option prevents Gardener cluster to be hibernated
failurePolicy: Ignore

View File

@@ -12,9 +12,11 @@ certificateGeneratorImage:
imagepullsecretInjector:
dockerconfigjsonRef:
secretName: my-cool-secret-source
secretName: acr-dockerconfigjson-source
secretNamespace: ""
targetSecretName: acr-dockerconfigjson
ignoreSecretCreationError: false
allSaNames: false
saNames:
- default