Search code examples
pythonazuresdkbackup

Azure VM Backup script with Python SDK


I´m trying to do a backup with the Azure SDK in Python.

Example with az-cli

az backup protection backup-now \
--resource-group myResourceGroup \
--vault-name myRecoveryServicesVault \
--container-name myVM \
--item-name myVM \
--retain-until 18-10-2017

how can I do it in a simple way (like in the az CLI) with Azure SDK from Python easy and clean?

Example with SDK:

#!/usr/bin/python

from azure.storage import BlobService
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("container", help="the blob container")
parser.add_argument("blob", help="the blob name")
parser.add_argument("-s", "--snapshot", help="take a new snapshot", 
action="store_true")
parser.add_argument("-d", "--delete", help="delete a snapshot")
parser.add_argument("-c", "--copy", help="copy a snapshot")
args = parser.parse_args()

# To use the storage services, you need to set the AZURE_STORAGE_ACCOUNT
# and the AZURE_STORAGE_ACCESS_KEY environment variables to the storage
# account name and primary access key you obtain from the Azure Portal.

AZURE_STORAGE_ACCOUNT='mystorage'
AZURE_STORAGE_ACCESS_KEY='supercalifragilisticexpialidocious'

blob_service = BlobService(AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_ACCESS_KEY)

if args.snapshot == True:
   print '# Taking new snapshot...'
   blob_service.snapshot_blob(args.container, args.blob)
   print 'OK.'

if args.delete:
   print '# Deleting snapshot...'
   blob_service.delete_blob(args.container, args.blob, snapshot=args.delete)
   print "Deleted", args.delete

 if args.copy:
 print '# Copying snapshot...'
 src = "https://" + AZURE_STORAGE_ACCOUNT + ".blob.core.windows.net/" + args.container + "/" + args.blob + "?snapshot=" + args.copy
 dst = args.blob + "_restore"
 blob_service.copy_blob(args.container, dst, src)
 print "Copied", src, "to", dst

 print '# List of snapshots:'

 for blob in blob_service.list_blobs(args.container, include='snapshots'):
   if blob.name == args.blob:
    print blob.name, blob.snapshot

I work many times with boto3 (AWS) to do things in the cloud with Python, but I´m very surprised with the Azure SDK options...

Actually, I´m searching examples with azure-mgmt-recoveryservicesbackup (https://learn.microsoft.com/en-us/python/api/azure-mgmt-recoveryservicesbackup/azure.mgmt.recoveryservicesbackup.recoveryservicesbackupclient?view=azure-python)

What is the best way to do VM backups with Azure SDK in Python?


Solution

  • According to my understanding, you want to know how to trigger azure VM backup. If so, please refer to the following steps

    1. Create a service principal and assign Azure RABC role Contributor role to the sp

    2. Code

    from azure.mgmt.recoveryservicesbackup import RecoveryServicesBackupClient
    from azure.mgmt.recoveryservicesbackup.models import IaasVMBackupRequest , OperationStatusValues
    from azure.common.credentials  import ServicePrincipalCredentials
    from datetime import datetime, timedelta, timezone
    from msrest.paging import Paged
    import re
    import time
    from six.moves.urllib.parse import urlparse
    
    credentials = ServicePrincipalCredentials(
        client_id='',
        secret='',
        tenant=''
    )
    
    client=RecoveryServicesBackupClient(credentials=credentials,subscription_id='')
    filter_string="backupManagementType eq 'AzureIaasVM'"
    vm_name='testdocker'
    resource_group_name='andywebbot'
    vault_name='test'
    retain_until = datetime.now(timezone.utc) + timedelta(days=30)
    res =client.backup_protected_items.list(
        vault_name=vault_name,
        resource_group_name=resource_group_name,
        filter=filter_string
    )
    items =list(res) if isinstance(res, Paged) else res
    
    item =[item for item in items if item.properties.friendly_name.lower() == vm_name.lower()]
    container_name=(re.search('(?<=protectionContainers/)[^/]+', item[0].id)).group(0)
    
    protected_item_name =(re.search('(?<=protectedItems/)[^/]+', item[0].id)).group(0)
    
    
    result =client.backups.trigger(
        vault_name=vault_name,
        resource_group_name=resource_group_name,
        fabric_name='Azure',
        container_name=container_name,
        protected_item_name=protected_item_name,
        parameters=IaasVMBackupRequest(recovery_point_expiry_time_in_utc=retain_until),raw=True
    )
    
    #check the operation status
    header =result.response.headers['Azure-AsyncOperation']
    parse_object = urlparse(header)
    id=parse_object.path.split("/")[-1]
    operation_status =client.backup_operation_statuses.get(
        vault_name=vault_name,
        resource_group_name=resource_group_name,
        operation_id=id
    )
    while operation_status.status == OperationStatusValues.in_progress:
        time.sleep(3)
        operation_status =client.backup_operation_statuses.get(
        vault_name=vault_name,
        resource_group_name=resource_group_name,
        operation_id=id
        )
    print(operation_status.status)