Hello !
Thank you for posting on Microsoft Learn.
In your case, you need to use the Azure Security Center REST API or Az.Security
module because JIT VM access is managed via Azure Security Center (Defender for Cloud).
Don't forget that :
- You cannot request JIT access on behalf of all users using a single service account, because the access is granted to the requesting identity only
- You can automate the JIT request from a central service account (like a DevOps pipeline or automation script) for specific ports, durations, IP ranges
- You need RBAC permission:
Microsoft.Security/locations/jitNetworkAccessPolicies/initiate/action
Before you create your script, you need to do the following :
- register an Azure AD App with Client Secret
- grant it
Security Reader
and JIT-specific roles at subscription/resource group level. - install the modules:
Install-Module -Name Az.Accounts -Force
Install-Module -Name Az.Security -Force
Then your script :
$tenantId = "<tenant-id>"
$appId = "<client-id>"
$clientSecret = "<client-secret>"
$subscriptionId = "<subscription-id>"
$vmResourceId = "/subscriptions/$subscriptionId/resourceGroups/<rg-name>/providers/Microsoft.Compute/virtualMachines/<vm-name>"
$location = "<vm-region>"
$secureSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($appId, $secureSecret)
Connect-AzAccount -ServicePrincipal -Credential $creds -TenantId $tenantId -Subscription $subscriptionId
$jitPolicy = Get-AzJitNetworkAccessPolicy -Location $location | Where-Object { $_.VirtualMachines.id -eq $vmResourceId }
$jitVm = @{
Id = $vmResourceId
Ports = @(
@{
Number = 3389
Protocol = "TCP"
AllowedSourceAddressPrefix = "Your.IP.Here/32"
AllowedSourceAddressPrefixType = "IPAddress"
MaxRequestAccessDuration = "PT1H"
}
)
}
$requestBody = @{
VirtualMachines = @($jitVm)
}
Start-AzJitNetworkAccessPolicy -Location $location -ResourceId $jitPolicy.Id -VirtualMachine $jitVm
If my answer helped, you don’t forget to the "Upvote" and "Accept the answer" to make it beneficial to other community members reading this thread.