loadbalancerPS.psm1

<#
.Synopsis
   Supporting function for other cmdlets in module
.DESCRIPTION
   Supporting function for other cmdlets in module
#>

function Enable-SelfSignedCertificate
{
    [CmdletBinding()]
    Param()

    Process
    {
        
        add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@

        $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
        [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
        [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy -ErrorAction SilentlyContinue
    }

}

<#
.Synopsis
   Connects to a loadbalancer.org REST API to drain, halt or online a real server
.DESCRIPTION
   Connects to a loadbalancer.org REST API to drain, halt or online a real server
.EXAMPLE
   Set-LBRealServerState -APIKey 'abc123' -ConnectionURI 'https://lbmaster.domain.local:9443/api/' -Credential (get-credential loadbalancer) -VirtualService https1 -RealServer web01 -Action halt
.EXAMPLE
   $ApiKey = 'abc123'
   $uri = 'https://lbmaster.domain.local:9443/api/'
   $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'loadbalancer', (ConvertTo-SecureString -AsPlainText 'loadbalancer' -Force)
   Set-LBRealServerState -APIKey $ApiKey -ConnectionURI $uri -Credential $cred -VirtualService https1 -RealServer web01 -Action halt
.EXAMPLE
   Set-LBRealServerState -APIKey 'abc123' -ConnectionURI 'https://lbmaster.domain.local:9443/api/' -Credential (get-credential loadbalancer) -VirtualService https1 -RealServer web01 -Action online
#>

function Set-LBRealServerState
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # API Key
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$APIKey,
        # Connection URI e.g. https://10.0.0.10:9443/api/
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$ConnectionURI,
        # Virtual Service Name
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        [string]$VirtualService,

        # Real Server Name
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
        [string]$RealServer,

        # Action: drain, halt or online
        [validateset('halt','drain', 'online')][Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
        [string]$Action,
        # PSCredential object containing the API username and password, prompts if omitted
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=5)]
        [pscredential]$Credential=(Get-Credential)
    )
        Begin
    {
        Enable-SelfSignedCertificate -ErrorAction SilentlyContinue
    }
    Process
    {
        Write-Output "Performing action $Action for $realserver in $VirtualService"
        $payload = @" {
                "auth": {
                    "apikey": "$apikey"
                },
                "action": [{
                    "command": "$action"
                }],
                "syntax": [{
                    "vip": "$virtualservice",
                    "rip": "$realserver"
                }]
            }
"@

        $response = Invoke-WebRequest -Uri $uri -Method Post -Body $payload -Credential $credential -UseBasicParsing -ContentType 'application/json'
        $ss = $response.content.split(',')[3]
        
        $ss.split('"')[1]
        if (($ss.split('"')[1]) -eq 'failed'){
            $response.content
        }
        
    }

}

<#
.Synopsis
   Connects to a loadbalancer.org REST API to restart appliance services
.DESCRIPTION
   Connects to a loadbalancer.org REST API to restart appliance services, must provide service name in lower-case
   Valid services are: haproxy, ldirectord, pound, stunnel, heartbeat, waf, collectd, firewall
.EXAMPLE
   restart-LBService -APIKey 'abc123' -ConnectionURI 'https://lbmaster.local:9443/api/' -Credential (get-credential loadbalancer) -Service haproxy
.EXAMPLE
   $ApiKey = 'abc123'
   $uri = 'https://lbmaster.domain.local:9443/api/'
   $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'loadbalancer', (ConvertTo-SecureString -AsPlainText 'loadbalancer' -Force)
   restart-LBService -APIKey $APIKey -ConnectionURI $uri -Credential $cred -Service haproxy
#>

function Restart-LBService
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    
    Param
    (
        # API Key
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$APIKey,
        # Connection URI e.g. https://10.0.0.10:9443/api/
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$ConnectionURI,
        # Service Name
        [validateset('haproxy','ldirectord', 'pound', 'stunnel','heartbeat', 'waf', 'collectd', 'firewall')][Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        [string]$Service,

        # PSCredential object containing the API username and password, prompts if omitted
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=5)]
        [pscredential]$Credential=(Get-Credential)
    )

        Begin
    {
    Enable-SelfSignedCertificate -ErrorAction SilentlyContinue
    }
    Process
    {
        Write-Output "Restarting service $VirtualService"
        $payload = @" {
                "auth": {
                    "apikey": "$apikey"
                },
                "action": [{
                    "command": "restart-$service"
                }]
            }
"@

        $response = Invoke-WebRequest -Uri $uri -Method Post -Body $payload -Credential $credential -UseBasicParsing -ContentType 'application/json'

        $ss = $response.content.split(',')[1]
        
        $ss.split('"')[3]
       
        
    }
    End
    {
    }
}

<#
.Synopsis
   Connects to a loadbalancer.org REST API to reload appliance services
.DESCRIPTION
   Connects to a loadbalancer.org REST API to reload appliance services, must provide service name in lower-case
   Valid services are: haproxy, ldirectord, pound, stunnel, heartbeat, waf, collectd, firewall
.EXAMPLE
   reload-LBService -APIKey 'abc123' -ConnectionURI 'https://lbmaster.local:9443/api/' -Credential (get-credential loadbalancer) -Service haproxy
.EXAMPLE
   $ApiKey = 'abc123'
   $uri = 'https://lbmaster.domain.local:9443/api/'
   $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'loadbalancer', (ConvertTo-SecureString -AsPlainText 'loadbalancer' -Force)
   reload-LBService -APIKey $APIKey -ConnectionURI $uri -Credential $cred -Service haproxy
#>

function Reload-LBService
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    
    Param
    (
        # API Key
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$APIKey,
        # Connection URI e.g. https://10.0.0.10:9443/api/
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$ConnectionURI,
        # Service Name
        [validateset('haproxy','ldirectord', 'pound', 'stunnel','heartbeat', 'waf', 'collectd', 'firewall')][Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        [string]$Service,

        # PSCredential object containing the API username and password, prompts if omitted
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=5)]
        [pscredential]$Credential=(Get-Credential)
    )

        Begin
    {
    Enable-SelfSignedCertificate -ErrorAction SilentlyContinue
    }
    Process
    {
        Write-Output "Reloading service $VirtualService"
        $payload = @" {
                "auth": {
                    "apikey": "$apikey"
                },
                "action": [{
                    "command": "reload-$service"
                }]
            }
"@

        $response = Invoke-WebRequest -Uri $uri -Method Post -Body $payload -Credential $credential -UseBasicParsing -ContentType 'application/json'

        $ss = $response.content.split(',')[1]
        
        $ss.split('"')[3]
       
        
    }
    End
    {
    }
}

<#
.Synopsis
   Adds a real server to an exisiting VIP
.DESCRIPTION
   Connects to loadbalancer.org appliance API to add a real server to an exisiting VIP
.EXAMPLE
   New-LBRealServer -APIKey 'abc123' -ConnectionURI 'https://lbmaster.domain.local:9443/api/' -Credential (get-credential) -VIPName 'MyWebApp' -RIPName 'Web01' -RIPAddress '10.0.0.11' -Port '80' -Weight '100'
.EXAMPLE
   $ApiKey = 'abc123'
   $uri = 'https://lbmaster.domain.local:9443/api/'
   $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'loadbalancer', (ConvertTo-SecureString -AsPlainText 'loadbalancer' -Force)
   New-LBRealServer -APIKey $APIKey -ConnectionURI $uri -Credential $cred -VIPName 'MyWebApp' -RIPName 'Web01' -RIPAddress '10.0.0.11' -Port '80' -Weight '100'
#>

function New-LBRealServer
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # API Key
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$APIKey,
        # Connection URI e.g. https://10.0.0.10:9443/api/
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$ConnectionURI,
        # Name of virtual IP (e.g. 'MyWebApp')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        $VIPName,

        # Name of Real Server (e.g. 'Web01')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
        $RIPName,

        # Real Sever IP Address (e.g. '10.0.0.11')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
        $RIPAddress,

        # Real Server Port Number (e.g. '80')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=5)]
        $Port,

        # Weight of real server (e.g. '100')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=6)]
        $Weight,
        # PSCredential object containing the API username and password, prompts if omitted
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=5)]
        [pscredential]$Credential=(Get-Credential)

    )

    Begin
    {
    Enable-SelfSignedCertificate -ErrorAction SilentlyContinue
    }
    Process
    {
        $payload = @" {
                "auth": {
                    "apikey": "$apikey"
                },
                "action": [{
                    "command": "add-rip"
                }],
                "syntax": [{
                    "vip": "$VIPName",
                    "rip": "$RIPName",
                    "ip": "$RIPAddress",
                    "port": "$Port",
                    "weight": "$Weight"
                }]
            }
"@

    $response = Invoke-WebRequest -Uri $uri -Method Post -Body $payload -Credential $credential -UseBasicParsing -ContentType 'application/json'
    $result = ($response.content.split(',')[3]).split('"')[1]
    $result
    if ($result -ne 'completed') {Write-error $response.content}
    }
    End
    {
    }
}


<#
.Synopsis
   Removes a real server from an exisiting VIP
.DESCRIPTION
   Connects to loadbalancer.org appliance API to remove a real server from an exisiting VIP
.EXAMPLE
   Remove-LBRealServer -APIKey 'abc123' -ConnectionURI 'https://lbmaster.domain.local:9443/api/' -Credential (get-credential) -VIPName 'MyWebApp' -RIPName 'Web01'
.EXAMPLE
   $ApiKey = 'abc123'
   $uri = 'https://lbmaster.domain.local:9443/api/'
   $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'loadbalancer', (ConvertTo-SecureString -AsPlainText 'loadbalancer' -Force)
   Remove-LBRealServer -APIKey $APIKey -ConnectionURI $uri -Credential $cred -VIPName 'MyWebApp' -RIPName 'Web01'
#>

function Remove-LBRealServer
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # API Key
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$APIKey,
        # Connection URI e.g. https://10.0.0.10:9443/api/
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$ConnectionURI,
        # Name of virtual IP (e.g. 'MyWebApp')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        $VIPName,

        # Name of Real Server (e.g. 'Web01')
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
        $RIPName,
        # PSCredential object containing the API username and password, prompts if omitted
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=5)]
        [pscredential]$Credential=(Get-Credential)

    )

    Begin
    {
    Enable-SelfSignedCertificate -ErrorAction SilentlyContinue
    }
    Process
    {
        $payload = @" {
                "auth": {
                    "apikey": "$apikey"
                },
                "action": [{
                    "command": "delete-rip"
                }],
                "syntax": [{
                    "vip": "$VIPName",
                    "rip": "$RIPName"
                }]
            }
"@

    $response = Invoke-WebRequest -Uri $uri -Method Post -Body $payload -Credential $credential -UseBasicParsing -ContentType 'application/json'
    #$response
    $result = ($response.content.split(',')[3]).split('"')[1]
    $result
    if ($result -ne 'completed') {Write-error $response.content}
    }
    End
    {
    }
}