-
Notifications
You must be signed in to change notification settings - Fork 2
/
Add-CurrentClientIPToKeyvault.ps1
80 lines (68 loc) · 2.58 KB
/
Add-CurrentClientIPToKeyvault.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
71
72
73
74
75
76
77
78
79
80
param (
[string]$KeyVaultResourceId,
[bool]$AddClientIPToFirewall = $true
)
function Update-KeyVaultNetworkRule
{
param (
[string]$KeyVaultName,
[string]$ResourceGroupName,
[bool]$AddClientIP
)
try
{
$keyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName
$currentNetworkAcls = $keyVault.NetworkAcls
Write-Host "Fetching current IP rules for Key Vault: $KeyVaultName"
$currentIps = $currentNetworkAcls.IpAddressRanges | ForEach-Object { $_ -replace '/32$', '' }
Write-Host "Current IP rules: $( $currentIps -join ', ' )"
$currentIp = (Invoke-RestMethod -Uri "https://checkip.amazonaws.com").Trim()
Write-Host "Current client IP: $currentIp"
$ipAlreadyExists = $currentIps -contains $currentIp
$newIpRules = $currentIps
if ($AddClientIP -and -not$ipAlreadyExists)
{
Write-Host "Appending current client IP to existing IP rules."
$newIpRules += $currentIp
}
elseif (-not$AddClientIP -and $ipAlreadyExists)
{
Write-Host "Removing current client IP from existing IP rules."
$newIpRules = $newIpRules | Where-Object { $_ -ne $currentIp }
}
else
{
Write-Host "No changes needed for the IP rules."
return
}
Write-Host "Updating IP rules: $( $newIpRules -join ', ' )"
# Reapply /32 subnet notation for consistent Azure Key Vault rules format
$newIpRules = $newIpRules | ForEach-Object { "$_/32" }
Update-AzKeyVaultNetworkRuleSet -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName `
-IpAddressRange $newIpRules -Bypass $currentNetworkAcls.Bypass -DefaultAction $currentNetworkAcls.DefaultAction
Write-Host "Key Vault network configuration updated."
}
catch
{
Write-Error "An error occurred: $_"
}
}
try
{
Write-Host "Starting script to update Key Vault firewall rules based on AddClientIPToFirewall flag."
$resourceIdParts = $KeyVaultResourceId -split '/'
$resourceGroupName = $resourceIdParts[4]
$keyVaultName = $resourceIdParts[-1]
if ($null -ne $keyVaultName)
{
Update-KeyVaultNetworkRule -KeyVaultName $keyVaultName -ResourceGroupName $resourceGroupName -AddClientIP $AddClientIPToFirewall
}
else
{
Write-Error "Key Vault Resource ID not properly supplied."
}
}
catch
{
Write-Error "An error occurred: $_"
}