Richard Barraclough
Richard Barraclough

Reputation: 2964

Using response from Azure cli (json) in PowerShell

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

Upvotes: 1

Views: 1547

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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
}

Upvotes: 1

Related Questions