【问题标题】:Azure VM Backup script with Python SDK带有 Python SDK 的 Azure VM 备份脚本
【发布时间】:2021-08-03 21:03:29
【问题描述】:

我正在尝试使用 Python 中的 Azure SDK 进行备份。

az-cli 示例

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

如何使用 Python 中的 Azure SDK 以简单的方式(如在 az CLI 中)轻松而干净地做到这一点?

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

我多次使用 boto3 (AWS) 使用 Python 在云中做事,但我对 Azure SDK 选项感到非常惊讶...

实际上,我正在使用 azure-mgmt-recoveryservicesbackup (https://docs.microsoft.com/en-us/python/api/azure-mgmt-recoveryservicesbackup/azure.mgmt.recoveryservicesbackup.recoveryservicesbackupclient?view=azure-python) 搜索示例

在 Python 中使用 Azure SDK 进行 VM 备份的最佳方法是什么?

【问题讨论】:

    标签: python azure sdk backup


    【解决方案1】:

    据我了解,您想知道如何触发 azure VM 备份。如果是,请参考以下步骤

    1. 创建服务主体并将 Azure RABC 角色 Contributor 角色分配给 sp

    2. 代码

    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)
    

    【讨论】:

    • 一个问题,Jim Xu:我怎样才能对特定的虚拟机而不是它们的列表做同样的事情?我在寻找关于 SDK Azure for Python 的好文档时遇到了几个问题谢谢 Jim Xu
    • 一个问题 Jim Xu:在你的 Python 脚本中,实际上我得到了“Succeeded”消息。如何通过 SDK Azure 将一个 VM 附加到备份策略?抱歉,但我不太了解 Microsoft Docs(我对 BOTO3 AWS Python SDK 更满意)我正在尝试使用以下文档:docs.microsoft.com/en-us/python/api/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多