Workbook Azure Automation NSG Rules AzureRunAs connection


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.


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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.