1

All I want to do is to see if my IP is already whitelisted for the company key vault and if not then add it.

The response of az keyvault network-rule list isn't a string (if it was then I could just -match but it's something else and I can't figure out any way to use it in PowerShell.

This is what I'm trying to do:

[string] $ip = (Invoke-WebRequest -uri "http://icanhazip.com/" -UseBasicParsing).Content

[bool] $loggedIn = ((((az account show) -match "tenantId").Count) -gt 0)

if( $b -eq $False ) {
    az login
}

[bool] $alreadyAdded = (((az keyvault network-rule list --name xxx) -match "$ip".Replace(".", "\.")).Count -gt 0)
# The command returns JSON which can't be -match ed and is useless after applying ConvertFrom-Json

if( $alreadyAdded -eq $False ) {
    echo "Adding IP $ip."
    az keyvault network-rule add --name xxx --ip-address "$ip"
    # It would be good to remove old IPs.
}
else {
    echo "Adress $ip is already added."
}

This seems to be a way to get the list of current IPs, but it seems to be impossible to test in PowerShell whether this list contains $ip. Or is there a way?

> az keyvault network-rule list --name xxx --query "ipRules" | ConvertFrom-Json 

value             
-----             
xxx.133.237.168/32 
xxx.39.179.102/32  
xxx.8.15.24/32     
xxx.40.138.215/32  
xxx.42.242.94/32   
xxx.36.228.115/32  
xxx.101.245.58/32  
xxx.27.46.155/32   
xxx.103.237.247/32 
xxx.28.15.154/32   
xxx.132.244.148/32 
xxx.132.247.90/32  
xxx.249.181.76/32 
xxx.205.197.115/32
1
  • As an aside: (Invoke-WebRequest -uri "http://icanhazip.com/" -UseBasicParsing).Content can be simplified to (use Invoke-RestMethod): Invoke-RestMethod -uri http://icanhazip.com/ Commented Apr 13, 2022 at 12:35

1 Answer 1

1

Make sure you trim any whitespace from the output from the IP query:

$ip = $ip.Trim()

Then use the Where-Object command to filter on the value property of each resulting object:

$MatchingIP = az keyvault network-rule list --name xxx --query "ipRules" | ConvertFrom-Json |Where-Object value -like "$ip/32"

if($MatchingIP){
    # Found a /32 entry for $ip
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.