How to grep logs from Kubernetes pods using Cypress TAF

Bothi Palani
1 min readOct 6, 2023

--

Have you ever needed to connect to Kube pods from your automation tests to extract log messages and use it in the tests ? then this story is for you !

Let us learn about creating custom task in cypress commands.js file to execute command to connect with Kube pods and grep the log message with specific pattern.

we have to use Cypress exec to run system commands.

Generally there would be more than one pod for a service. So following code snippet loops through each pod and execute the system command to tail the log & grep for specific pattern.

If the grep command is successful then it returns code 0 else returns 1.

Cypress.Commands.add('getKubePodsLog', (path, grepString) => {
let report;
const podList = ['pod1', 'pod2'];
podList.forEach(pod => {
cy.exec(`kubectl exec -it ${pod} -- //bin/sh -c "tail -30 ${path} | grep '${grepString}'"`, {
failOnNonZeroExit: false,
})
.then(log => {
if (log.code === 0) {
report = log.stdout;
} else {
console.log(`Expected pattern not found on ${pod}`);
}
})
.then(() => report);
});
});

Use the custom command in your test to get the actual log pattern and compare with the expected result.

cy.getKubePodsLog(path, string).then((actualLog) => {
expect(actualLog).contains('expected String');
});

--

--

Bothi Palani
Bothi Palani

Written by Bothi Palani

Senior SDET & Test Automation Consultant

No responses yet