Hi
here is a piece of coude you could use to open or either close ports in the NSG Azure VMS running a schedule and using automation.
Requeriments
- Automation Account configurated and created
- Run as Account configurated and created
- Runbook experience-> https://docs.microsoft.com/en-us/azure/automation/manage-runbooks
- Run as connections : https://docs.microsoft.com/en-us/azure/automation/automation-connections?tabs=azure-powershell
Code :
#region BoilerplateAuthentication
#This requires a RunAs account
#AzureServicePrincipal - Represents a connection used by the Azure Run As account.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $ServicePrincipalConnection.TenantId `
-ApplicationId $ServicePrincipalConnection.ApplicationId `
-CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
$AzureContext = Select-AzureRmSubscription -SubscriptionId $ServicePrincipalConnection.SubscriptionID
#Close a Port Example
$nsg = Get-AzureRmNetworkSecurityGroup -Name "Your NSG name" -ResourceGroupName "your resoruce group name where the NSG is"
$nsg | Get-AzureRmNetworkSecurityRuleConfig -Name "your NSG rule name"
$config = Set-AzureRmNetworkSecurityRuleConfig -Name "your NSG rule name" -NetworkSecurityGroup $nsg -Priority 499 -Protocol "*" -Access "Deny" -Direction "outbound" -SourceAddressPrefix "*" -SourcePortRange "*" -DestinationAddressPrefix "Internet" -DestinationPortRange "*"
$config | Set-AzureRmNetworkSecurityGroup