How to download SSL certs from kubernetes pod with cypress tests
There are few automation tests needed to have the ssl certs configured for authentication. when you run the tests on pipeline, certs are mounted on the kubernetes pods however certs needs to be downloaded and kept in local folder for running it from local machine.
Certs can be downloaded manually using the following kubectl command
kubectl cp <certs path inside pod> ./certs -n <namespace>
example
kubectl cp cypress-pod:/automation-tests/certs ./certs -n test
But when the certs are updated on the server side & if you forgot to download, your tests will be running with the old certs and fail.
So to avoid the problem, certs can also be downloaded programmatically before test execution started.
create a Javascript file with any name, I named it download-ssl-certs.js
Assumptions:
There are pods with cypress docker image running on your kube namespace and any apps which contains the SSL certs.
below code written with pod name contains ‘cypress’, you have to change it for your needs.
const fs = require('fs');
const args = process.argv;
const env = args[2];
async function importSSLCertsFromCypressPod(env) {
new Promise((resolve, reject) => {
exec(`kubectl config use-context ${env}`, async err => {
if (!err) {
exec(`kubectl get pods -o jsonpath={..metadata.name}`, async (err, stdout) => {
if (!err) {
const cypressPods = stdout.split(' ').filter(name => name.startsWith('cypress'));
exec(`kubectl cp ${cypressPods[0]}:/test-repo-name/certs/ ./certs`, async err => {
if (!err) {
await exec(`mv ./certs/..[A-Za-z0-9]*/** ./certs`, async (err, stdout) => {
if (err) {
console.log('error with moving files to certs folder', stdout);
}
});
} else {
console.log(
'There are no cypress pod running, please spin up pod using command kubectl scale deploy cypress --replicas=1',
stdout,
);
}
});
resolve(true);
}
reject(err);
});
}
});
};
async function downloadSSLCerts(env) {
try {
const path = './certs/';
const regex = /^\..*$/;
fs.readdirSync(path)
.filter(f => regex.test(f))
.map(f => fs.rmdirSync(path + f));
const sslCertDownloadStatus = await importSSLCertsFromCypressPod(env);
return !!sslCertDownloadStatus;
} catch (error) {
throw new Error(
`There are no cypress pod running, please spin up pod using command kubectl scale deploy cypress --replicas=1`,
);
}
}
downloadSSLCerts(env).then(status => {
if (status === true) {
console.log('SSL certs are downloaded successfully into ./certs folder');
}
});
when you run the following command from root of your test repo, ssl certs are downloaded in certs folder
node download-ssl-certs.js <env-name>