Skip to content

Instantly share code, notes, and snippets.

@jtabuloc
Last active June 25, 2023 14:03
Show Gist options
  • Save jtabuloc/9cf98ec2676e05950979c862a44d3331 to your computer and use it in GitHub Desktop.
Save jtabuloc/9cf98ec2676e05950979c862a44d3331 to your computer and use it in GitHub Desktop.
Add or Remove IP address of running machine in Azure Account Storage network firewall
#####################################################################################
#
# Script that will get IP address machine and add/remove in storage account firewall
# Action Parameter: Add/Remove
#
#####################################################################################
param(
[string]$AccountStorageName,
[string]$Action
)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$IpCheckerSites = @('https://api.ipify.org?format=json','https://ipinfo.io/json','https://api.myip.com/','https://ip.seeip.org/jsonip?')
$Ip = $null
$Attempt = 0
$MaxAttempt = 3
$SleepDuration = 2
:loop foreach ($site in $IpCheckerSites)
{
Write-Output "Trying to get IP address from $site"
$Ip=Invoke-RestMethod $site | Select -exp ip
if ($Ip -as [IPAddress] -as [Bool])
{
# Set agentIP variable
Write-Host "Agent IP Address: $Ip"
if ($Action -eq 'Add')
{
# Add Agent IP address in storage account temporarily
az storage account network-rule add --account-name $AccountStorageName --ip-address $Ip --output none --only-show-errors
while($Attempt -le $MaxAttempt)
{
# Show info to check if ip is succussfully added
$result = az storage account show -n $AccountStorageName --query "networkRuleSet.ipRules[?ipAddressOrRange=='$Ip'].ipAddressOrRange"
# Exit if true
if($result.Length -ge 3 -and $result[1].Contains($Ip))
{
Write-Host "Agent IP Address is successfully added in $AccountStorageName firewall"
break loop
}
$Attempt++
Write-Host "Attempt #$Attempt : Agent IP Address is not yet added in $AccountStorageName network rule"
Start-Sleep -Seconds $SleepDuration
}
}
elseif ($Action -eq 'Remove')
{
# Remove Agent IP address from storage account
az storage account network-rule remove --account-name $AccountStorageName --ip-address $Ip --output none --only-show-errors
# Show info to check if ip is succussfully removed
az storage account show -n $AccountStorageName --query networkRuleSet --output none --only-show-errors
Write-Host "Agent IP Address is successfully removed from $AccountStorageName firewall"
}
else
{
Write-Host "Supported actions are Add and Remove only."
}
break
}
}
# Show error if IP can't be resolved
if (!($IP -as [IPAddress] -as [Bool])) {
Write-Output "Cannot determine Agent IP address"
throw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment