Import secrets from Kubernetes

Bothi Palani
2 min readNov 16, 2023

what if you need to run your test automation using the secrets used in the project but it is only available in the kubernetes clusters on remote machines, since there may be situations when the local copy is not always sync with the values in the remote machines.

we should be importing the secrets from kubernetes on the fly and use it when we run our test automation from local machine.

let us learn in this article about how to import the secrets from kubernetes ?

This article assumes, you have setup the kubernetes cluster and switched to the correct context on kube.

packages needs to be installed
node-jq & exec

command to get the secrets and map into the json format

kubectl get secret secret-name -o jsonpath={.data}

use node-jq to run the command to decode the data from base64 encoding and map the json values.

jq.run('. | map_values(@base64d)', path)

create the modules to execute the kube command and jq command in a file called secret.js file and run the command node secret.js

const path = './secret.json';
const jq = require('node-jq');
const { writeFileSync } = require('fs');

module.exports.importSecrets = () =>
new Promise((resolve, reject) => {
exec(`kubectl get secret secret-name -o jsonpath={.data}`, async (err, stdout) => {
if (!err) {
const decode = JSON.parse(stdout);
const temp = JSON.stringify(decode);

try {
writeFileSync(path, temp, 'utf8');
resolve(true);
} catch (error) {
console.log('An error has occurred ', error);
}
}
reject(err);
});
});


module.exports.getDecodedSecrets = config =>
new Promise(resolve => {
jq.run('. | map_values(@base64d)', path).then(output => {
resolve({ JSON.parse(output.replace(/\r?\n|\r/g, '')) }));
});
});


async function getSecrets() {
const isSecretsDownloaded = await importSecrets();
if (isSecretsDownloaded === true) {
await getDecodedSecrets().then(async secrets => {
try {
return secrets;
} catch (err) {
console.log('Error writing the secrets file', err);
return false;
}
});
} else {
console.log('Problem with importing secrets, check if you are on the correct kube context');
return false;
}
}

getSecrets();

--

--