fredag 20 mars 2020

Automated backups of IaaS in Azure

Wrapped up a script that will automatically backup IaaS in Azure.
If the IaaS if tagged with NoBackup then the script will skip that IaaS since its decided it should not be included.

This script can be improved and I leave it to you to do whatever you like :)


#Authentication made via SPN
$connectionName = 'AzureRunAsConnection'

Try{
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
    Write-Output "Logging in to Azure..."
    Add-AzureRMAccount -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
    }
}

#Gets all the Azure VM's
$IaaSs = Get-AzureRmVM

#Pointing out the RSV for backup and setting the vault context for editing
Get-AzureRmRecoveryServicesVault -Name "NAME-OF-SRV" | Set-AzureRmRecoveryServicesVaultContext

#Defining the backup policy
$Policy = Get-AzureRmRecoveryServicesBackupProtectionPolicy -Name "DefaultPolicy"

#Enabling backup for each IaaS object 
foreach($IaaS in $IaaSs)
{
   
     If($IaaS.Tags.Values -eq "NoBackup")
    {
        Write-Output "Backup should not be enabled for $($IaaS.Name)"
    }
               
    Else
    {
        Write-Output "Enabling IaaS backup for VM $($IaaS.Name)"
        $RG = $IaaS.ResourceGroupName
        Enable-AzureRmRecoveryServicesBackupProtection -ResourceGroupName $RG -Name $IaaS.Name -Policy $policy
    } 
}

Inga kommentarer:

Skicka en kommentar