/
Add-AzureIpRestrictionRule.ps1
70 lines (54 loc) · 2.28 KB
/
Add-AzureIpRestrictionRule.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<#
.Synopsis
Adds an Azure Ip restriction rule to an Azure App Service.
.EXAMPLE
Add-AzureIpRestrictionRule -ResourceGroupName $ResourceGroupName -AppServiceName $AppServiceName -rule $rule
#>
function Add-AzureIpRestrictionRule
{
[CmdletBinding()]
Param
(
# Name of the resource group that contains the App Service.
[Parameter(Mandatory=$true, Position=0)]
$ResourceGroupName,
# Name of your Web or API App.
[Parameter(Mandatory=$true, Position=1)]
$AppServiceName,
# rule to add.
[Parameter(Mandatory=$true, Position=2)]
[PSCustomObject]$rule
)
$ApiVersions = Get-AzureRmResourceProvider -ProviderNamespace Microsoft.Web |
Select-Object -ExpandProperty ResourceTypes |
Where-Object ResourceTypeName -eq 'sites' |
Select-Object -ExpandProperty ApiVersions
$LatestApiVersion = $ApiVersions[0]
$WebAppConfig = Get-AzureRmResource -ResourceType 'Microsoft.Web/sites/config' -ResourceName $AppServiceName -ResourceGroupName $ResourceGroupName -ApiVersion $LatestApiVersion
$WebAppConfig.Properties.ipSecurityRestrictions = $WebAppConfig.Properties.ipSecurityRestrictions + @($rule) |
Group-Object name |
ForEach-Object { $_.Group | Select-Object -Last 1 }
Set-AzureRmResource -ResourceId $WebAppConfig.ResourceId -Properties $WebAppConfig.Properties -ApiVersion $LatestApiVersion -Force
}
############################################################
$SubscriptionId = ''
$AppServiceName = ''
$ResourceGroupName = ''
Disable-AzureRmContextAutosave -Scope Process | out-null
$ctxPath = Join-Path $env:APPDATA 'azure.ctx'
if (-not (Test-Path $ctxPath))
{
Login-AzureRmAccount
Save-AzureRmContext -Path $ctxPath -Force
}
Import-AzureRmContext -Path $ctxPath | out-null
Set-AzureRmContext -SubscriptionId $SubscriptionId | Out-Null
$clientIp = Invoke-WebRequest 'https://api.ipify.org' | Select-Object -ExpandProperty Content
$rule = [PSCustomObject]@{
ipAddress = "$($clientIp)/32"
action = "Allow"
priority = 123
name = '{0}_{1}' -f $env:computername, $env:USERNAME
description = "Automatically added ip restriction"
}
Add-AzureIpRestrictionRule -ResourceGroupName $ResourceGroupName -AppServiceName $AppServiceName -rule $rule