Sunday, January 29, 2017

F5 management through PowerShell

I've mentioned in my vCPU upgrade article that one of the requirements of me being allowed to shut down the VM was to be sure that there were no connections on the F5 loadbalancer for the webserver.

So I needed to script against the F5 loadbalancer. The first thing you need to do, is to get the F5 PowerShell Snapin from the F5 site. An account can be made for free, then you can login and download the plugin and follow the instructions to get it installed.

Once installed, you can add the snapin with:

Add-PSSnapIn iControlSnapIn

Now you have commands to manage the F5. Great, now it's time to login. First you need to add some credentials to a variable, and I've mentioned this in a previous article too. After that, you can set up the connection to the loadbalancer:

$creds = Import-CliXml -Path "D:\akos\LB01.Cred"
Initialize-F5.iControl -HostName "192.168.1.10" -Credentials $creds

Great, now you have the power to enable and disable nodes within the loadbalancer pool with actions like:

Disable-F5.LTMNodeAddress -Node "10.0.20.3"

and

Enable-F5.LTMNodeAddress -Node "10.0.20.3"

Now disabling and enabling is fine, but knowing if there's really no connections left is what you want to have. Luckily the Internet is a great place for info, and someone on Stackoverflow created the following excellent code, which I adapted a little to suit my needs. These two excellent functions do exactly what I want it to do, namely wait around for connections to drop (with a max time, don't want to spend waiting forever), and a supporting function to get the number of connections:

function WaitForConnectionsToDrop(
    [int]$MaxWaitTime = 300,
    [string]$Node
)
{
    $connections = GetCurrentConnections -Node $Node

    $elapsed = [System.Diagnostics.Stopwatch]::StartNew();
    while($connections -gt 0 -and $elapsed.ElapsedMilliseconds -lt ($MaxWaitTime * 1000)){        

        Start-Sleep -Seconds 10

        $connections = GetCurrentConnections -Node $Node
    }
}

function GetCurrentConnections(
    [string]$Node
)
{
    $ic=Get-F5.iControl
    $connections = $ic.LocalLBNodeAddress.get_statistics($Node) | foreach{$_.statistics.statistics | where {$_.type -eq "STATISTIC_SERVER_SIDE_CURRENT_CONNECTIONS"} | foreach{$_.value.low} }
    Write-Host "$Node has $connections Connections"
    return $connections
}

(note, that last few lines are broken up due to the format of the blog, it should be one line)
The great thing is, now you can easily do the following:

foreach ($node in $serverlist){
    Disable-F5.LTMNodeAddress -Node "$node"
    WaitForConnectionsToDrop -Node "$node" -MaxWaitTime 300
    #insert whatever code you want to do, like, say upgrade vCPU's, or patch the host
    Enable-F5.LTMNodeAddress -Node "$node"
}

As you can tell, it is easy to create a script with this info that will easily disable and enable nodes. Yeay, PowerShell!

No comments:

Post a Comment