In my weblog submit contribution for this 12 months’s Festive Tech Calendar, I’ll present you the way to scale back Azure prices by automating the runtime of your Azure Bastion host(s) with Azure Automation.
The Festive Tech Calendar is a collaborative neighborhood initiative based by Gregor Suttie (Azure Greg), Richard Hooper (Pixel Robots), Keith Atherton, Simon Lee, Lisa Hoving, and Matt Boyd.
Working all through December, this initiative brings collectively a wealthy and numerous array of content material contributed by tech fans from across the globe. It provides a vibrant mixture of movies and weblog posts, all designed and shared by the neighborhood.
You’ll find all of the movies and weblog posts on https://festivetechcalendar.com/ and the Festive Tech YouTube Channel.
You can too keep up to date by following @_CloudFamily or keeping track of X for hashtags like #festivetechcalendar2024 and #CloudFamily.
However let’s get began and learn to optimize Bastion utilization prices, lower bills, and save large not simply this vacation season however all 12 months spherical.

Desk of Contents
Why use Azure Automation with Azure Bastion
Most of us who’re already conversant in Azure Bastion use it in our personal or buyer Azure environments. It’s a absolutely managed platform-as-a-service (PaaS) from Microsoft Azure, offering safe, seamless distant entry to digital machines (VMs) with out exposing them to the general public web. It’s generally deployed in private Azure setups or buyer environments.
Nonetheless, relying on which SKU you select, the pricing for Bastion hosts can add up considerably in your Azure invoice, particularly for those who don’t use them continuously. To get an thought of the present pricing, you possibly can test the present pricing by way of this hyperlink: https://azure.microsoft.com/en-us/pricing/particulars/azure-bastion/
To assist get monetary savings when utilizing Azure Bastion in an atmosphere, I sometimes configure it to solely run throughout enterprise hours. This implies you solely pay for the hours when the Azure Bastion host is actively in use, which happens solely throughout enterprise hours. This may end up in important price financial savings over time.
To successfully handle prices with Azure Bastion, you should utilize Azure Automation. On this weblog submit, I’ll present you the way to configure it to function Azure Bastion solely throughout enterprise hours, making certain you solely pay for its energetic utilization.
Azure stipulations
- An Azure subscription is required, ideally a number of subscriptions if you’re following the Cloud Adoption Framework (CAF) enterprise-scale structure. This features a connectivity and/or administration subscription, together with at the very least one corp subscription (touchdown zone) for deploying your Azure VM sources.
- An Azure Administrator account with the suitable RBAC roles, equivalent to Proprietor or Contributor on the subscription or useful resource group stage.
- An Azure Bastion host* (Primary or Commonplace), ideally operating within the administration subscription, needs to be a part of the Hub VNet with peering configured to the VNets within the company or different subscriptions internet hosting your Azure VMs.



*For those who’d prefer to create an Azure Bastion host utilizing Azure PowerShell, you possibly can discuss with this weblog submit I wrote beforehand.
Create an Azure Automation Account
To get began, we’ll want an Azure Automation Account. For these unfamiliar with it, the simplest method to create one is by way of the Azure Portal. Nonetheless, for extra superior customers, it’s preferable and safer to make use of automation to deploy it with all most popular settings utilized directly. You need to use Bicep or Terraform for this, however Azure PowerShell can also be an choice.
I’ve already written a weblog submit demonstrating the way to use an Azure PowerShell script to create an Azure Automation Account inside a selected subscription. You may entry it by way of the next hyperlink: https://wmatthyssen.com/2024/02/22/create-an-azure-automation-account-with-azure-powershell/.
You may easy run the script by way of Home windows Terminal or your most popular methodology.


Earlier than continuing to the subsequent step, be certain that the Azure Automation system-assigned id has the required Azure function assignments. Sometimes, the Contributor function on the Azure subscription internet hosting the Azure Bastion host is adequate.
Nonetheless, if the useful resource group containing the Azure Bastion sources is protected by a useful resource lock, the id should be assigned the Proprietor function to permit it to take away the lock.

As soon as your Azure Automation Account is on the market and the right function assignments have been utilized in your administration subscription, or if these had been already in place, you possibly can transfer on to the subsequent step.
Create an Azure Bastion delete runbook
After getting an Azure Automation Account in your atmosphere, the subsequent step is to create an Azure Bastion delete runbook. This includes writing a PowerShell script that deletes your Azure Bastion useful resource throughout the Azure Automation Account. The runbook can then be scheduled, for instance, after enterprise hours, or manually executed to take away the Bastion host when it’s not wanted, serving to handle your Azure prices successfully.
To get began, and if it’s not already open, sign up to the Azure Portal together with your credentials.
Subsequent, use the international search bar or navigate by means of the portal to go to your Azure Automation Account.

Then, on the Automation Account blade, click on on “Runbooks” within the left-hand menu, after which choose “Create a runbook”.

On the “Create a runbook” web page, fill in all of the required particulars equivalent to Title, Runbook sort (choose PowerShell), Runtime model, and supply a transparent description for the runbook. Then click on Subsequent.

On the subsequent web page, specify all of the required tags that you just use in your atmosphere. After including the required tags, click on Subsequent once more.


Then click on Create, and await the runbook to be created. As soon as it’s created, the runbook editor will open.

Within the runbook editor, enter the next PowerShell script to delete the Azure Bastion occasion, and click on Save to reserve it.
Simply alter the 2 variables on the prime of the script with your personal values. For those who don’t have a useful resource lock, you possibly can take away the variable and the corresponding a part of the script.
## Variables
$bastionName = "bas-hub-myh-01"
$lockName = "DoNotDeleteLock"
## Join utilizing a Managed Service Identification
strive {
$AzureConnection = (Join-AzAccount -Identification).context
}
catch {
Write-Output "There isn't a system-assigned person id. Aborting."
exit
}
## Change the present context to make use of a administration subscription
$subNameManagement = Get-AzSubscription | The place-Object {$_.Title -like "*administration*"}
Set-AzContext -SubscriptionId $subNameManagement.SubscriptionId | Out-Null
## Get the Bastion Useful resource
$bastion = Get-AzBastion | The place-Object Title -Match $bastionName
## Verify if the Bastion useful resource group has a useful resource lock; in that case, take away the useful resource lock
$rgNameBastion = $bastion.ResourceGroupName
$lock = Get-AzResourceLock -ResourceGroupName $rgNameBastion
# Verify if useful resource lock exists
if ($null -ne $lock) Out-Null
## Delete the Azure Bastion host
if ($bastion) Out-Null
else {
Write-Output "Azure Bastion '$BastionName' not present in useful resource group '$ResourceGroupName'."
}

After you have got saved the runbook, you possibly can check the code within the “Take a look at pane” by choosing the Take a look at pane. Within the check pane, click on Begin to provoke the execution of your runbook.
The runbook shall be queued for execution. If the runbook is profitable, it’s going to additionally delete the Bastion host specified within the variable you supplied.
As soon as the runbook completes, the outcomes shall be displayed on the identical web page, offering suggestions on the success or failure of the operation.

After testing, if the result’s passable (exhibits as accomplished with none errors), you possibly can shut the “Take a look at pane” to return to the principle runbook editor view.

Earlier than organising a schedule, be certain the runbook is revealed. To do that, click on on Publish within the runbook editor. Publishing the runbook makes it obtainable for execution primarily based on the schedule you’ll arrange. Click on Sure to proceed.


The final step is so as to add a schedule by choosing the “Schedules” menu merchandise and choosing “Add a schedule“.
This lets you automate the execution of your runbook at particular instances or intervals, making certain the Azure Bastion delete runbook runs as wanted with out guide intervention.

When including a brand new schedule, there are two choices: “Schedule” and “Parameters and run settings”. Because the present runbook script doesn’t require any parameters, the second choice just isn’t related. On this case, we solely must create a schedule and hyperlink it to the runbook.
So, choose “Hyperlink a schedule to your runbook” after which click on on “Add a schedule“.


Fill within the “New Schedule” parameters by offering a identify, a description, and the begin date. Set the specified hour, specify the right time zone, and select the recurrence sample, ideally set it to recur daily. After configuring all these settings, click on “Create” to avoid wasting the schedule.

Then click on “OK” the schedule the runbook.



As soon as the schedule is linked to the runbook, you possibly can transfer on to the subsequent step the place we are going to configure and arrange the Create-Bastion runbook.
Create an Azure Bastion create runbook
Along with the Azure Bastion delete runbook, you additionally must create an Azure Bastion create runbook. This runbook lets you manually redeploy the Azure Bastion host every time wanted, or for instance, 1 / 4 earlier than enterprise hours begin every day.
To start, go to Runbooks as soon as once more, and choose Create a runbook.
On the Create a runbook web page, fill in all of the required particulars equivalent to Title, Runbook sort (choose PowerShell), Runtime model, and supply a transparent description for the runbook. Then click on Subsequent.

On the subsequent web page, enter all of the required tags utilized in your atmosphere. After including the required tags, click on “Subsequent” as soon as extra.

Then click on “Create” to finalize and create the runbook.

Within the runbook editor, paste the next PowerShell script into the editor to (re-)create the Azure Bastion occasion, and click on Save to reserve it.
Be sure that to alter all of the variables on the prime of the script to match your personal values.
## Variables
$spoke = "hub"
$rgNameBastion = "rg-hub-myh-bastion-01"
$bastionName = "bas-hub-myh-01"
$lockName = "DoNotDeleteLock"
$function = "bastion"
$tagSpokeName = "Env"
$tagSpokeValue = "$($spoke[0].ToString().ToUpper())$($spoke.SubString(1))"
$tagCostCenterName = "CostCenter"
$tagCostCenterValue = "23"
$tagCriticalityName = "Criticality"
$tagCriticalityValue = "Excessive"
$tagPurposeName = "Function"
$tagPurposeValueBastion = "$($function[0].ToString().ToUpper())$($function.SubString(1))"
$tagVnetName = "VNet"
## Join utilizing a Managed Service Identification
strive {
$AzureConnection = (Join-AzAccount -Identification).context
}
catch {
Write-Output "There isn't a system-assigned person id. Aborting."
exit
}
## Change the present context to make use of a administration subscription
$subNameManagement = Get-AzSubscription | The place-Object {$_.Title -like "*administration*"}
Set-AzContext -SubscriptionId $subNameManagement.SubscriptionId | Out-Null
## Retailer the required set of tags in a hash desk
$tags = @{$tagSpokeName=$tagSpokeValue;$tagCostCenterName=$tagCostCenterValue;$tagCriticalityName=$tagCriticalityValue}
## Get the PIP and retailer as a variable
$pipNameBastion = Get-AzPublicIpAddress -ResourceGroupName $rgNameBastion
## Get the digital community with the AzureBastionSubnet
$virtualNetwork = Get-AzVirtualNetwork | The place-Object {$_.Subnets -ne $null -and $_.Subnets.Title -contains "AzureBastionSubnet"}
if ($null -ne $virtualNetwork) {
$vnetName = $virtualNetwork.Title
$rgNameNetworking = $virtualNetwork.ResourceGroupName
} else {
Write-Host ("# Digital community with 'AzureBastionSubnet' not discovered.")
}
## Redeploy Bastion host with Primary SKU
New-AzBastion -ResourceGroupName $rgNameBastion -Title $bastionName -PublicIpAddress $pipNameBastion -VirtualNetworkRgName $rgNameNetworking `
-VirtualNetworkName $vnetName | Out-Null
## Set tags on Bastion host
$bastion = Get-AzBastion -ResourceGroupName $rgNameBastion -Title $bastionName
Set-AzBastion -InputObject $bastion -Tag $tags -Pressure | Out-Null
## Lock the Azure Bastion useful resource group with a CanNotDelete lock
$lock = Get-AzResourceLock -ResourceGroupName $rgNameBastion
if ($null -eq $lock) Out-Null

After saving the runbook, you possibly can check the code by choosing the Take a look at pane. If every little thing works as anticipated, you possibly can proceed to publish it.



Then create a schedule, simply as you probably did for the Delete-Bastion runbook, however this time specify the creation time. For instance, set it to begin quarter-hour earlier than the start of enterprise hours.






Conclusion
Thanks for studying! I’m excited to be a part of this 12 months’s Festive Tech Calendar as soon as once more and hope you take pleasure in all of the superb content material being shared all through December 2024.
When you have any questions on Azure Bastion together with Azure Automation, don’t hesitate to achieve out to me on X at @wmatthyssen or join with me on LinkedIn.
Pleased studying and viewing, take care, and have an exquisite vacation season! 🎄🎆