Welcome to the fourth article of the series on Shareable Links for Azure Bastion. As promised in the previous article, I will try to automate deleting a shareable link for Azure Bastion. In this article, I intend to build a PowerShell function to delete a shareable Azure Bastion link. Let's see how we can do it.
76 posts tagged with "PowerShell"
View All TagsShareable Link for Azure Bastion - Part 3
The time has come to build PowerShell Functions for the feature of Shareable Links for Azure Bastion. In this article, I will try to build a PowerShell function to create a shareable link for Azure Bastion. First, there is no way to create Bastion Shareable Links using Azure PowerShell Cmdlets. That's why we will try to come up with a be-spoke solution. At the end of the article series, we will have a couple of PowerShell Functions that can create, update, delete, and get shareable links for Azure Bastion.
Shareable Link for Azure Bastion - Part 2
Great to see you again! In the previous article, we tried to create a resource group for our lab environment. From now on, I will jump right into my script to create a lab environment. I will explain the script line by line. You can also find the script in end of the article and in my GitHub repository.
Shareable Link for Azure Bastion - Part 1
Hello Friends, I believe that you have probably heard about the Azure Bastion. It is a service that provides secure and seamless RDP/SSH connectivity to your VMs directly in the Azure portal over SSL. It removes the need to implement inbound ports for RDP/SSH and the need to manage jump boxes. You can connect to your VM using the Azure portal or Azure CLI.
I will try to automate creating a shareable link for Azure Bastion Hosts in this article series. I will use Azure PowerShell to create a shareable link(s) for Azure Bastion Host(s). Nothing stops you from generating a shareable link for Azure Bastion using the Azure Portal. This article series intends to automate provisioning a shareable link for Azure Bastion.
Azure Virtual Network Manager - Part 4
Without slowing down, we can continue to the 4th part of our Azure Virtual Network Manager series. So far, we have covered the following topics:
- Understanding of the Azure Virtual Network Manager Part 1
- Defining the scope of the Azure Virtual Network Manager Part 2
- Provisioning the Azure Virtual Network Manager Part 2
- Spining up Virtual Networks and Subnets for Lab Environment Part 3
- Create and configure Network Groups for Lab Environment Part 3
Azure Virtual Network Manager - Part 3
Greetings, In previous post, we have created the Azure Virtual Network Manager Resource. Now, we will try to understand concept of network groups and how to create them. In a nutshell, Network Groups are a collection of Virtual Networks. Network Groups are used to group Virtual Networks together. Once you have created a Network Group, you can add Virtual Networks statically or dynamically to the Network Group.
Let's start with the PowerShell Cmdlets for creating Network Groups. Hang on! We don't have virtual networks in our subscription yet. Let me share the PowerShell Cmdlets for creating Virtual Networks. I will create three Virtual Networks. You can carve out your own network map.
Azure Virtual Network Manager - Part 2
Hey Folks, Let's start diving into the Azure PowerShell Module
for creating Virtual Network Manager Resource. Initially, we will be creating the Azure Virtual Network Manager Instance. The goal of commands below is to have Resource Group and Virtual Network Manager in a region.
Azure Virtual Network Manager - Part 1
Hey Friends, In this article series, I am aiming to touch on edge spots in the new Azure Virtual Network Manager. Many organizations are running their services on Azure and having multiple virtual networks in single or multiple subscriptions. There are different ways on Azure Infrastructure that communicate between Virtual Networks, such as Hub and Spoke or Mesh topology.
📄 Introducing Azure Virtual Network Manager (AVNM)
Azure Virtual Network Manager (AVNM) is a new feature and is in preview now. AVNM is a single pane of glass for your environment that solves the connectivity and management complexity if you have multiple Virtual Networks in your organization.
Azure Firewall Policy Analytics
Hello Folks, At some point, your organization will retrospectively analyze existing firewall rules due to security and compliance posture. Imagine that you’re using Azure Firewall in your organization to generate analytics reports for existing firewall rules requiring a bespoke solution. There are many ways that you can achieve these types of reports. I used to develop a tailored solution using PowerShell and KQL queries to fit that requirement, but it might be very complex if you would like to apply this solution to large-scale environments. Thankfully, Microsoft has announced a new Azure Firewall feature that allows us to generate that report quickly and natively. We now call that feature Azure Firewall Policy Analytics.
Manage Azure Bastion Sessions with PowerShell - Part 2
Hello Folks, Welcome to the second part of the series. Previously, we discussed the fundamentals of session monitoring and management for Azure Bastion and how to get the active session and terminate the session using the REST API. In this article, we will talk about the PowerShell Function that we will use to manage the sessions. Let's get into it.
🌱Scaffolding the PowerShell Function
The Function name will be Remove-AzBastionActiveSessions
and it will have the following parameters:
- BastionHostNames (Array)
- VMNames (Array)
- SubscriptionId (String)
I tried to keep the parameters as simple as possible. The Function will have the following logic:
- Iterates through the Bastion Hosts
- Gets the active sessions for each Bastion Host
- Filters the sessions based on the VM Names
- Terminates the sessions
💻 The PowerShell Function
Function Remove-AzBastionActiveSessions {
<#
.SYNOPSIS
Author: Hasan Gural - Azure VMP
Version: BETA
.DESCRIPTION
There is no way for terminating the active sessions for the Bastion Host in the Azure PowerShell module. This function will hit the REST API directly to terminate the active sessions.
.NOTES
This function won't enable the shareable link feature for the Bastion Host. This needs to be done manually or see previous article on how to do this.
.EXAMPLE
Remove-AzBastionActiveSessions -VMNames @("vm-01", "vm-03", "vm-02") -BastionNames @("bastion-vnt-0001","bastion-vnt-0003") -SubscriptionId $subscriptionId
Function will support multiple VMs and Bastion Hosts. Just pass in the names of the VMs and Bastion Hosts and the subscription ID.
You can run the script multiple for removing the shareable links. Existing links will remain intact.
#>
[CmdletBinding()]
param (
[Parameter()]
[array]
$VMNames,
[Parameter()]
[array]
$BastionNames,
[Parameter()]
$SubscriptionId
)
$links = @() # Array to store deleted links
$header = @{
"Content-Type" = "application/json"
Authorization = ("Bearer " + (Get-AzAccessToken).Token)
}
ForEach ($bastion in $BastionNames) {
$getBastion = Get-AzBastion -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $bastion }
if ($getBastion.ProvisioningState -eq "Succeeded") {
$ResourceGroupName = $getBastion.ResourceGroupName
$Location = $getBastion.Location
$SubscriptionId = $getBastion.Id.Split('/')[2]
$Name = $getBastion.Name
Write-Output "[INFO] - ---------------------------------"
Write-Output "[INFO] - Bastion Host Name: $bastion "
Write-Output "[INFO] - Resource Group: $ResourceGroupName"
Write-Output "[INFO] - Subscription: $SubscriptionId"
Write-Output "[INFO] - Location: $Location"
Write-Output "[INFO] - ---------------------------------"
$uri = "https://management.azure.com/subscriptions/$($SubscriptionId)/resourceGroups/$($ResourceGroupName)/providers/Microsoft.Network/bastionHosts/$($Name)/getActiveSessions?api-version=2022-07-01"
$getOperationActiveSessions = (Invoke-WebRequest -Method Post -Uri $uri -Headers $header).Headers.Location[0]
Start-Sleep -Seconds 5 # Wait for retrieving the active sessions.
$getActiveSession = (Invoke-WebRequest -Method Get -Uri $getOperationActiveSessions -Headers $header).Content | ConvertFrom-Json
if ($getActiveSession) {
ForEach ($vm in $VMNames) {
$getVM = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $vm -ErrorAction SilentlyContinue
$vmSessions = $getActiveSession | Where-Object { $_.targetHostName -eq $vm }
ForEach ($session in $vmSessions) {
$taskCount = 1 # Task counter
Write-Output "[TASK 1.$($taskCount)] - Retrieving the active sessions for $vm. Please wait."
if ($getVM.ProvisioningState -eq "Succeeded") {
if ($getVM.Name -eq $session.targetHostName) {
$requestBody = @{
"sessionIds" = @($session.sessionId)
}
$uri = "https://management.azure.com/subscriptions/$($SubscriptionId)/resourceGroups/$($ResourceGroupName)/providers/Microsoft.Network/bastionHosts/$($Name)/disconnectActiveSessions?api-version=2022-07-01"
$response = Invoke-WebRequest -Method Post -Uri $uri -Headers $header -Body (ConvertTo-Json $requestBody -Depth 10)
Write-Output "[TASK 1.$($taskCount)] - Terminating the active session for $vm. Please wait. This may take a while."
Start-Sleep -Seconds 5 # Wait for the link to be created. This is to avoid the error "The link is not ready yet. Please try again later."
}
else {
Write-Output "[Error] - Active Session does not exist for the Virtual Machine: $vm"
continue
}
}
else {
Write-Output "[Error] - Virtual Machine $vm does not exist. Please check the name and try again."
continue
}
}
}
}
else {
Write-Output "[Error] - There is no active session for the Bastion Host: $bastion"
}
}
else {
Write-Output "[Error] - Bastion Host $bastion does not exist. Please check the name and try again."
continue
}
}
}
🔌 Executing the Function
The Function will be executed as follows:
$params = @{
VMNames = @("vm-01", "vm-02") # Name of Virtual Machines that you want to terminate the sessions
BastionNames = @("bastion-vnt-0001") # Name of the Bastion Hosts
SubscriptionId = $subscriptionId
}
Remove-AzBastionActiveSessions @params
✨ Example Output
In the following example, we will terminate the active sessions for the Bastion Host bastion-vnt-0001
and the Virtual Machines vm-01
and vm-02
. See the output below for active sessions before and after the execution of the Function.
I have executed the PowerShell Function below and you can see that it terminated the active sessions.
🚀 Conclusion
Imagine that you have a Bastion Host(s) that has multiple active sessions and you want to terminate them. You can use the PowerShell Function that I have shared in this article. You can also schedule this function to run periodically to terminate the active sessions. This will help you avoid running out of the Bastion Hosts.
Thanks for reading this through. For more improvements, please let me know. I will be happy to hear your feedback.