1 #!powershell 2 3 # Copyright: (c) 2016, Daniele Lazzari <lazzari@mailup.com> 4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 5 6 #Requires -Module Ansible.ModuleUtils.Legacy 7 8 # win_route (Add or remove a network static route) 9 10 $params = Parse-Args $args -supports_check_mode $true 11 12 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -default $false 13 $dest = Get-AnsibleParam -obj $params -name "destination" -type "str" -failifempty $true 14 $gateway = Get-AnsibleParam -obj $params -name "gateway" -type "str" 15 $metric = Get-AnsibleParam -obj $params -name "metric" -type "int" -default 1 16 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateSet "present","absent" 17 $result = @{ 18 "changed" = $false 19 "output" = "" 20 } 21 Add-Route()22Function Add-Route { 23 Param ( 24 [Parameter(Mandatory=$true)] 25 [string]$Destination, 26 [Parameter(Mandatory=$true)] 27 [string]$Gateway, 28 [Parameter(Mandatory=$true)] 29 [int]$Metric, 30 [Parameter(Mandatory=$true)] 31 [bool]$CheckMode 32 ) 33 34 35 $IpAddress = $Destination.split('/')[0] 36 37 # Check if the static route is already present 38 $Route = Get-CimInstance win32_ip4PersistedrouteTable -Filter "Destination = '$($IpAddress)'" 39 if (!($Route)){ 40 try { 41 # Find Interface Index 42 $InterfaceIndex = Find-NetRoute -RemoteIPAddress $Gateway | Select-Object -First 1 -ExpandProperty InterfaceIndex 43 44 # Add network route 45 New-NetRoute -DestinationPrefix $Destination -NextHop $Gateway -InterfaceIndex $InterfaceIndex -RouteMetric $Metric -ErrorAction Stop -WhatIf:$CheckMode|out-null 46 $result.changed = $true 47 $result.output = "Route added" 48 49 } 50 catch { 51 $ErrorMessage = $_.Exception.Message 52 Fail-Json $result $ErrorMessage 53 } 54 } 55 else { 56 $result.output = "Static route already exists" 57 } 58 59 } 60 Remove-Route()61Function Remove-Route { 62 Param ( 63 [Parameter(Mandatory=$true)] 64 [string]$Destination, 65 [bool]$CheckMode 66 ) 67 $IpAddress = $Destination.split('/')[0] 68 $Route = Get-CimInstance win32_ip4PersistedrouteTable -Filter "Destination = '$($IpAddress)'" 69 if ($Route){ 70 try { 71 72 Remove-NetRoute -DestinationPrefix $Destination -Confirm:$false -ErrorAction Stop -WhatIf:$CheckMode 73 $result.changed = $true 74 $result.output = "Route removed" 75 } 76 catch { 77 $ErrorMessage = $_.Exception.Message 78 Fail-Json $result $ErrorMessage 79 } 80 } 81 else { 82 $result.output = "No route to remove" 83 } 84 85 } 86 87 # Set gateway if null 88 if(!($gateway)){ 89 $gateway = "0.0.0.0" 90 } 91 92 93 if ($state -eq "present"){ 94 95 Add-Route -Destination $dest -Gateway $gateway -Metric $metric -CheckMode $check_mode 96 97 } 98 else { 99 100 Remove-Route -Destination $dest -CheckMode $check_mode 101 102 } 103 104 Exit-Json $result 105