Skip to content
This repository has been archived by the owner on May 16, 2023. It is now read-only.

Commit

Permalink
fix clean command + optimize js script
Browse files Browse the repository at this point in the history
  • Loading branch information
jmlrt committed Nov 8, 2022
1 parent 2b7524b commit 4a590d9
Show file tree
Hide file tree
Showing 9 changed files with 143 additions and 127 deletions.
204 changes: 79 additions & 125 deletions kibana/templates/configmap-helm-scripts.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ metadata:
name: {{ template "kibana.fullname" . }}-helm-scripts
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook": pre-install,post-delete
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
{{- end }}
{{- end }}
data:
get-token.js: |
manage-es-token.js: |
const https = require('https');
const fs = require('fs');
Expand All @@ -28,57 +29,24 @@ data:
// Kubernetes API
const k8sHostname = process.env.KUBERNETES_SERVICE_HOST;
const k8sPort = process.env.KUBERNETES_SERVICE_PORT_HTTPS;
const k8sPath = 'api/v1/namespaces/{{ .Release.Namespace }}/secrets';
const k8sUrl = 'https://' + k8sHostname + ':' + k8sPort + '/' + k8sPath
const k8sPostSecretPath = 'api/v1/namespaces/{{ .Release.Namespace }}/secrets';
const k8sDeleteSecretPath = 'api/v1/namespaces/{{ .Release.Namespace }}/secrets/{{ template "kibana.fullname" . }}-es-token';
const k8sPostSecretUrl = 'https://' + k8sHostname + ':' + k8sPort + '/' + k8sPostSecretPath;
const k8sDeleteSecretUrl = 'https://' + k8sHostname + ':' + k8sPort + '/' + k8sDeleteSecretPath;
const k8sBearer = fs.readFileSync('/run/secrets/kubernetes.io/serviceaccount/token');
const k8sCa = fs.readFileSync('/run/secrets/kubernetes.io/serviceaccount/ca.crt');
// With thanks to https://stackoverflow.com/questions/57332374/how-to-chain-http-request
function requestPromise(url, options, payload) {
return new Promise((resolve, reject) => {
const request = https.request(url, options, response => {
console.log('statusCode:', response.statusCode);
// console.log('headers:', response.headers);
// TODO: remove 404 and handle it during esToken deletion
const isSuccess = response.statusCode >= 200 && response.statusCode < 300 || response.statusCode == 404;
let data = '';
response.on('data', chunk => data += chunk); // accumulate data
response.once('end', () => isSuccess ? resolve(data) : reject(data)); // resolve promise here
});
request.once('error', err => {
// This won't log anything for e.g. an HTTP 404 or 500 response,
// since from HTTP's point-of-view we successfully received a
// response.
console.log(`${options.method} ${options.path} failed: `, err.message || err);
reject(err); // if promise is not already resolved, then we can reject it here
});
if (payload) {
request.write(payload);
}
request.end();
});
}
// Delete kb-kibana token
// Post Data
const esTokenDeleteOptions = {
method: 'DELETE',
auth: esAuth,
ca: esCa,
};
// Create new kb-kibana token
const esTokenCreateOptions = {
method: 'POST',
auth: esAuth,
ca: esCa,
};
// Create new k8s secret
const secretCreateOptions = {
method: 'POST',
ca: k8sCa,
Expand All @@ -88,71 +56,22 @@ data:
'Content-Type': 'application/json',
}
};
// Chaining requests
console.log('Cleaning previous token');
requestPromise(esUrl, esTokenDeleteOptions).then(() => {
console.log('Creating new token');
requestPromise(esUrl, esTokenCreateOptions).then(response => {
const body = JSON.parse(response);
const token = body.token.value
// Encode the token in base64
const base64Token = Buffer.from(token, 'utf8').toString('base64');
// Prepare the k8s secret
secretData = JSON.stringify({
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"namespace": "{{ .Release.Namespace }}",
"name": "{{ template "kibana.fullname" . }}-es-token",
},
"type": "Opaque",
"data": {
"token": base64Token,
}
})
// Create the k8s secret
console.log('Creating K8S secret');
requestPromise(k8sUrl, secretCreateOptions, secretData).then().catch(err => {
console.error(err)
});
return;
})
}).catch(err => {
console.error(err);
});
clean-token.js: |
const https = require('https');
const fs = require('fs');
// Elasticsearch API
const esPath = '_security/service/elastic/kibana/credential/token/kb-kibana';
const esUrl = '{{ .Values.elasticsearchHosts }}' + '/' + esPath
const esUsername = process.env.ELASTICSEARCH_USERNAME;
const esPassword = process.env.ELASTICSEARCH_PASSWORD;
const esAuth = esUsername + ':' + esPassword;
const esCaFile = process.env.ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES;
const esCa = fs.readFileSync(esCaFile);
// Kubernetes API
const k8sHostname = process.env.KUBERNETES_SERVICE_HOST;
const k8sPort = process.env.KUBERNETES_SERVICE_PORT_HTTPS;
const k8sPath = 'api/v1/namespaces/{{ .Release.Namespace }}/secrets/{{ template "kibana.fullname" . }}-es-token';
const k8sUrl = 'https://' + k8sHostname + ':' + k8sPort + '/' + k8sPath
const k8sBearer = fs.readFileSync('/run/secrets/kubernetes.io/serviceaccount/token');
const k8sCa = fs.readFileSync('/run/secrets/kubernetes.io/serviceaccount/ca.crt');
const secretDeleteOptions = {
method: 'DELETE',
ca: k8sCa,
headers: {
'Authorization': 'Bearer ' + k8sBearer,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
// With thanks to https://stackoverflow.com/questions/57332374/how-to-chain-http-request
function requestPromise(url, options, payload) {
return new Promise((resolve, reject) => {
const request = https.request(url, options, response => {
console.log('statusCode:', response.statusCode);
// console.log('headers:', response.headers);
// TODO: remove 404 and handle it during esToken deletion
const isSuccess = response.statusCode >= 200 && response.statusCode < 300 || response.statusCode == 404;
Expand All @@ -177,34 +96,69 @@ data:
});
}
// Delete kb-kibana token
const esTokenDeleteOptions = {
method: 'DELETE',
auth: esAuth,
ca: esCa,
};
// Create new k8s secret
const secretDeleteOptions = {
method: 'DELETE',
ca: k8sCa,
headers: {
'Authorization': 'Bearer ' + k8sBearer,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
function createEsToken() {
// Chaining requests
console.log('Cleaning previous token');
requestPromise(esUrl, esTokenDeleteOptions).then(() => {
console.log('Creating new token');
requestPromise(esUrl, esTokenCreateOptions).then(response => {
const body = JSON.parse(response);
const token = body.token.value
// Encode the token in base64
const base64Token = Buffer.from(token, 'utf8').toString('base64');
// Prepare the k8s secret
secretData = JSON.stringify({
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"namespace": "{{ .Release.Namespace }}",
"name": "{{ template "kibana.fullname" . }}-es-token",
},
"type": "Opaque",
"data": {
"token": base64Token,
}
})
// Create the k8s secret
console.log('Creating K8S secret');
requestPromise(k8sPostSecretUrl, secretCreateOptions, secretData).then().catch(err => {
console.error(err)
});
return;
})
}).catch(err => {
console.error(err);
});
}
// Chaining requests
console.log('Cleaning token');
requestPromise(esUrl, esTokenDeleteOptions).then(() => {
// Create the k8s secret
console.log('Delete K8S secret');
requestPromise(k8sUrl, secretDeleteOptions).then().catch(err => {
function cleanEsToken() {
// Chaining requests
console.log('Cleaning token');
requestPromise(esUrl, esTokenDeleteOptions).then(() => {
// Create the k8s secret
console.log('Delete K8S secret');
requestPromise(k8sDeleteSecretUrl, secretDeleteOptions).then().catch(err => {
console.error(err)
});
return;
})
}).catch(err => {
console.error(err);
});
}).catch(err => {
console.error(err);
});
}
const command = process.argv[2];
switch (command) {
case 'create':
console.log('Creating a new Elasticsearch token for Kibana')
createEsToken();
break;
case 'clean':
console.log('Cleaning the Kibana Elasticsearch token')
cleanEsToken();
break;
default:
console.log('Unknown command');
}
6 changes: 4 additions & 2 deletions kibana/templates/post-delete-job.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-delete
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
Expand All @@ -21,7 +22,8 @@ spec:
imagePullPolicy: "{{ .Values.imagePullPolicy }}"
command: ["{{ template "kibana.home_dir" . }}/node/bin/node"]
args:
- {{ template "kibana.home_dir" . }}/helm-scripts/clean-token.js
- {{ template "kibana.home_dir" . }}/helm-scripts/manage-es-token.js
- clean
env:
- name: "ELASTICSEARCH_USERNAME"
valueFrom:
Expand All @@ -41,7 +43,7 @@ spec:
readOnly: true
- name: kibana-helm-scripts
mountPath: {{ template "kibana.home_dir" . }}/helm-scripts
serviceAccount: pre-install-{{ template "kibana.fullname" . }}
serviceAccount: post-delete-{{ template "kibana.fullname" . }}
volumes:
- name: elasticsearch-certs
secret:
Expand Down
20 changes: 20 additions & 0 deletions kibana/templates/post-delete-role.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: post-delete-{{ template "kibana.fullname" . }}
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-delete
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
{{- end }}
{{- end }}
rules:
- apiGroups:
- ""
resources:
- secrets
verbs:
- delete
21 changes: 21 additions & 0 deletions kibana/templates/post-delete-rolebinding.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: post-delete-{{ template "kibana.fullname" . }}
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-delete
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
{{- end }}
{{- end }}
subjects:
- kind: ServiceAccount
name: post-delete-{{ template "kibana.fullname" . }}
namespace: {{ .Release.Namespace | quote }}
roleRef:
kind: Role
name: post-delete-{{ template "kibana.fullname" . }}
apiGroup: rbac.authorization.k8s.io
13 changes: 13 additions & 0 deletions kibana/templates/post-delete-serviceaccount copy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: post-delete-{{ template "kibana.fullname" . }}
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-delete
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
{{- end }}
{{- end }}
3 changes: 3 additions & 0 deletions kibana/templates/pre-install-job.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
Expand All @@ -21,6 +22,8 @@ spec:
imagePullPolicy: "{{ .Values.imagePullPolicy }}"
command: ["{{ template "kibana.home_dir" . }}/node/bin/node"]
args:
- {{ template "kibana.home_dir" . }}/helm-scripts/manage-es-token.js
- create
- {{ template "kibana.home_dir" . }}/helm-scripts/get-token.js
env:
- name: "ELASTICSEARCH_USERNAME"
Expand Down
1 change: 1 addition & 0 deletions kibana/templates/pre-install-role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
Expand Down
1 change: 1 addition & 0 deletions kibana/templates/pre-install-rolebinding.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
Expand Down
1 change: 1 addition & 0 deletions kibana/templates/pre-install-serviceaccount.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
labels: {{ include "kibana.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-delete-policy": hook-succeeded
{{- if .Values.annotations }}
{{- range $key, $value := .Values.annotations }}
{{ $key }}: {{ $value | quote }}
Expand Down

0 comments on commit 4a590d9

Please sign in to comment.