Here we go again, another quick workflow that came out of the desire to clean up idle session on my vCenter servers.
The premise is pretty simple, loop over a list of vCenter servers and find any connections that have been idle over X minutes and terminate them.
I realized pretty quickly that I have to be careful to not terminate sessions for things like Site Recovery Manager, vCloud Director, Update Manager, etc. so I built in a whitelist that leaves those accounts alone.
As far as the code it is pretty straight forward, start with a loop that loops over all the vCenters and then another loop that loops over the sessions to that vCenter:
1 2 3 4 |
for each ( var vCenter in vCenters ) { for each ( var session in vCenter.sessionManager.sessionList ) { |
Then we filter out the ones that we do not want to terminate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
if( session == null ) { System.log( "Skipping null session." ); continue; } if( session.extensionSession ) { System.log( "Skipping extension session." ); continue; } if( session.key == vCenter.sessionManager.currentSession.key ) { System.log( "Skipping this session." ); continue; } if( contains(whitelist, session.userName) ) { System.log( session.userName + " - Skipping whitelisted username." ); continue; } |
For the ones that are left, we calculate how long the sessions have been idle.
1 2 3 4 5 6 7 8 9 10 11 12 |
var idleTime = (new Date() - session.lastActiveTime) / 1000; var seconds = Math.floor(idleTime % 60); var minutes = Math.floor((idleTime % 3600) / 60); var hours = Math.floor(idleTime / 3600); var totalMinutes = (idleTime / 60); if( totalMinutes < maxIdleMinutes ) { System.log( session.userName + " - Skipping active connection." ); continue; } |
Then we kill the ones that have been idle for too long.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
System.log("Killing session for " + session.userName + "@" + vCenter.name + ", it has been idle for " + hours + " hour(s), " + minutes + " minute(s) and " + seconds + " second(s)." ); // For some reason the connetion database was not updating correctly and it would show connections that didn't exist anymore // when executed the second time, this will ignore the errors. try { var oldSessions = new Array(); oldSessions.push(session.key); vCenter.sessionManager.terminateSession(oldSessions); oldSessions = null; } catch(ex) { } |
There is not a whole lot more to say about this one, it should be pretty straight forward.
Download the package here.
Great post! There are a lot of idle session killer scripts running out there, but having it in VCO as a scheduled workflow is a great way to consolidate these types of operational automation workflows into a central solution.
Thanks for sharing the solution!
Pingback: vCenter Orchestrator Workflow for old snapshots removal | VirtCode