Automating a PowerShell Script using Azure Automation Account

So you have have created a PowerShell script to run a job quickly, but now you want to automate that PowerShell Script at a scheduled interval. For this you can use Azure Automation account where you can add you PowerShell script as a runbook and schedule that runbook at a desired time interval. In addition to the script that you have created, you also need to add some additional lines to make Automation account use a connection. Also note that if your script is performing some action (read or write) on any other subscription where the automation account is created, then you'll have to grant Automation Account's Runas account, the access of other subscriptions (You can refer the Microsoft article here.)

So, this is the PowerShell Script that you can use in your Automation Account Runbook. 

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}




Once you add the above script with a desired PowerShell Script, it will look like as following. I've created this script to export Azure Network Security Groups in a CSV.


# PowerShell Script to export Azure Network Security Groups in CSV format using Azure Automation Account. Created by Prashant Sahu http://www.prashantsahu.com

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

Import-Module Az.Network
Import-Module Az.Storage

$outputfinal=@()
foreach ( $Subscription in $(Get-AzSubscription| Where-Object {$_.State -ne "Disabled"}) )
{
Select-AzSubscription -SubscriptionId $Subscription.SubscriptionId
$nsgs=Get-AzNetworkSecurityGroup
foreach ($nsg in $nsgs)
{
$securityrules=$nsg.SecurityRules
foreach ($securityrule in $securityrules)
{
$outputtemp = "" | SELECT  NSGName,NSGLocation,RGName,Direction,Priority,RuleName,DestinationPort,Protocol,SourceAddress,SourcePort,DestinationAddress,Action,Description
$outputtemp.NSGName=$nsg.name
$outputtemp.NSGLocation=$nsg.location
$outputtemp.RGName=$nsg.ResourceGroupName
$outputtemp.Direction=$securityrule.direction
$outputtemp.Priority=$securityrule.Priority
$outputtemp.RuleName=$securityrule.Name
$outputtemp.DestinationPort=$securityrule.DestinationPortRange -join ", "
$outputtemp.Protocol=$securityrule.Protocol -join ", "
$outputtemp.SourceAddress=$securityrule.SourceAddressPrefix -join ", "
$outputtemp.SourcePort=$securityrule.SourcePortRange -join ", "
$outputtemp.DestinationAddress=$securityrule.DestinationAddressPrefix -join ", "
$outputtemp.Action=$securityrule.Access
$outputtemp.Description=$securityrule.Description
$outputfinal += $outputtemp
}
}
}
$outputfinal | Export-Csv "$Env:temp/NSGs" -NoTypeInformation

$resourceGroupName="myresourcegroup"  
$storageAccName="mystorageaccount" 
$fileShareName="myfileshare"  
$fileName="$Env:temp/NSGs" 
$folderPath="/" 

Function UploadFiles  
{   Set-AzContext -SubscriptionId 2gdj2342-gl39-390r-h208-84957dg897g8
    $ctx=(Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName).Context  
    Set-AzStorageFileContent -ShareName $fileShareName -context $ctx -Source $fileName -Path $folderPath/"NSGs_$((Get-Date).ToString("yyyyMMdd_HHmmss")).csv" 
}  
UploadFiles      
 

Comments

Popular posts from this blog

Specifying SSH port in Ansible Inventory

Ansible-Playbook to display output of multiple show commands (using stdout_lines with Loop)

Filtering Routes in BGP using Route-maps and Prefix-list

Ansible Playbook for Network OS Upgrade with pre and post checks

VMware NSX Traffic Flow — East-West & North-South

Bypassing Proxy Server in Google Chrome

Export or Backup Azure Network Security Groups into CSV using PowerShell

Ansible-playbook for backing up running config of Cisco IOS