从 Python 使用服务管理Use service management from Python

本指南说明如何以编程方式从 Python 执行常见服务管理任务。This guide shows you how to programmatically perform common service management tasks from Python. Azure SDK for Python 中的 ServiceManagementService 类支持以编程方式访问 Azure 门户中提供的众多与服务管理相关的功能。The ServiceManagementService class in the Azure SDK for Python supports programmatic access to much of the service management-related functionality that is available in the Azure portal. 此功能可用于创建、更新和删除云服务、部署、数据管理服务和虚拟机。You can use this functionality to create, update, and delete cloud services, deployments, data management services, and virtual machines. 此功能可用于构建需要以编程方式访问服务管理的应用程序。This functionality can be useful in building applications that need programmatic access to service management.

什么是服务管理? What is service management?

利用 Azure 服务管理 API,可以编程方式访问通过 Azure 门户提供的众多服务管理功能。The Azure Service Management API provides programmatic access to much of the service management functionality available through the Azure portal. Azure SDK for Python 可用于管理云服务和存储帐户。You can use the Azure SDK for Python to manage your cloud services and storage accounts.

若要使用服务管理 API,需要创建 Azure 帐户To use the Service Management API, you need to create an Azure account.

概念 Concepts

Azure SDK for Python 可包装服务管理 API,即 REST API。The Azure SDK for Python wraps the Service Management API, which is a REST API. 所有 API 操作都是通过 SSL 执行的,并且通过使用 X.509 v3 证书互相进行身份验证。All API operations are performed over SSL and mutually authenticated by using X.509 v3 certificates. 可以从在 Azure 中运行的服务内访问管理服务。The management service can be accessed from within a service running in Azure. 还可以直接通过 Internet 从可发送 HTTPS 请求和接收 HTTPS 响应的任意应用程序访问管理服务。It also can be accessed directly over the Internet from any application that can send an HTTPS request and receive an HTTPS response.

安装 Installation

azure-servicemanagement-legacy 包中提供了本文介绍的所有功能,可以通过使用 pip 安装该包。All the features described in this article are available in the azure-servicemanagement-legacy package, which you can install by using pip. 有关安装的详细信息(例如,如果刚开始接触 Python),请参阅安装 Python 和 Azure SDKFor more information about installation (for example, if you're new to Python), see Install Python and the Azure SDK.

连接到服务管理 Connect to service management

要连接到服务管理终结点,需要 Azure 订阅 ID 和有效管理证书。To connect to the service management endpoint, you need your Azure subscription ID and a valid management certificate. 可以通过 Azure 门户获取订阅 ID。You can obtain your subscription ID through the Azure portal.

备注

现在可以在 Windows 上运行时使用通过 OpenSSL 创建的证书。You now can use certificates created with OpenSSL when running on Windows. 需要 Python 2.7.4 或更高版本。Python 2.7.4 or later is required. 我们建议使用 OpenSSL 而不是 .pfx,因为将来可能会取消对 .pfx 证书的支持。We recommend that you use OpenSSL instead of .pfx, because support for .pfx certificates is likely to be removed in the future.

Windows/Mac/Linux 上的管理证书 (OpenSSL)Management certificates on Windows/Mac/Linux (OpenSSL)

可使用 OpenSSL 创建管理证书。You can use OpenSSL to create your management certificate. 需要创建两个证书,一个用于服务器(.cer 文件),一个用于客户端(.pem 文件)。You need to create two certificates, one for the server (a .cer file) and one for the client (a .pem file). 若要创建 .pem 文件,请执行以下代码:To create the .pem file, execute:

openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem

若要创建 .cer 证书,请执行以下代码:To create the .cer certificate, execute:

openssl x509 -inform pem -in mycert.pem -outform der -out mycert.cer

有关 Azure 证书的详细信息,请参阅 Azure 云服务证书概述For more information about Azure certificates, see Certificates Overview for Azure Cloud Services. 有关 OpenSSL 参数的完整说明,请参阅 http://www.openssl.org/docs/apps/openssl.html 上的文档。For a complete description of OpenSSL parameters, see the documentation at http://www.openssl.org/docs/apps/openssl.html.

创建这些文件后,将 .cer 文件上传到 Azure。After you create these files, upload the .cer file to Azure. Azure 门户的“设置”选项卡上,选择“上传”。In the Azure portal, on the Settings tab, select Upload. 请注意 .pem 文件的保存位置。Note where you saved the .pem file.

获取订阅 ID 后,创建一个证书,将 .cer 文件上传到 Azure,然后连接到 Azure 管理终结点。After you obtain your subscription ID, create a certificate, and upload the .cer file to Azure, connect to the Azure management endpoint. 通过将订阅 ID 和 .pem 文件的路径传递给 ServiceManagementService 进行连接。Connect by passing the subscription ID and the path to the .pem file to ServiceManagementService.

from azure import *
from azure.servicemanagement import *

subscription_id = '<your_subscription_id>'
certificate_path = '<path_to_.pem_certificate>'

sms = ServiceManagementService(subscription_id, certificate_path)

在前面的示例中, sms 是一个 ServiceManagementService 对象。In the preceding example, sms is a ServiceManagementService object. ServiceManagementService 类是用于管理 Azure 服务的主类。The ServiceManagementService class is the primary class used to manage Azure services.

Windows 上的管理证书 (MakeCert)Management certificates on Windows (MakeCert)

可以使用 makecert.exe 在计算机上创建自签名管理证书。You can create a self-signed management certificate on your machine by using makecert.exe. 以管理员身份打开 Visual Studio 命令提示符并且使用以下命令,将 AzureCertificate 替换为要使用的证书名称:Open a Visual Studio command prompt as an administrator and use the following command, replacing AzureCertificate with the certificate name you want to use:

makecert -sky exchange -r -n "CN=AzureCertificate" -pe -a sha1 -len 2048 -ss My "AzureCertificate.cer"

该命令将创建 .cer 文件,然后将该文件安装在“个人”证书存储中。The command creates the .cer file, and installs it in the Personal certificate store. 有关详细信息,请参阅 Azure 云服务证书概述For more information, see Certificates Overview for Azure Cloud Services.

创建证书后,将 .cer 文件上传到 Azure。After you create the certificate, upload the .cer file to Azure. Azure 门户的“设置”选项卡上,选择“上传”。In the Azure portal, on the Settings tab, select Upload.

获取订阅 ID 后,创建一个证书,将 .cer 文件上传到 Azure,然后连接到 Azure 管理终结点。After you obtain your subscription ID, create a certificate, and upload the .cer file to Azure, connect to the Azure management endpoint. 通过将订阅 ID 和“个人”证书存储中证书的位置传递给 ServiceManagementService 进行连接(同样,将 AzureCertificate 替换为证书名称)。Connect by passing the subscription ID and the location of the certificate in your Personal certificate store to ServiceManagementService (again, replace AzureCertificate with the name of your certificate).

from azure import *
from azure.servicemanagement import *

subscription_id = '<your_subscription_id>'
certificate_path = 'CURRENT_USER\\my\\AzureCertificate'

sms = ServiceManagementService(subscription_id, certificate_path)

在前面的示例中, sms 是一个 ServiceManagementService 对象。In the preceding example, sms is a ServiceManagementService object. ServiceManagementService 类是用于管理 Azure 服务的主类。The ServiceManagementService class is the primary class used to manage Azure services.

列出可用位置 List available locations

若要列出可用于托管服务的位置,请使用 list_locations 方法:To list the locations that are available for hosting services, use the list_locations method:

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

result = sms.list_locations()
for location in result:
    print(location.name)

在创建云服务或存储服务时,需要提供有效位置。When you create a cloud service or storage service, you need to provide a valid location. list_locations 方法将始终返回当前可用位置的最新列表。The list_locations method always returns an up-to-date list of the currently available locations. 截止到本文撰写时为止,可用位置为:As of this writing, the available locations are:

  • 中国东部China East
  • 中国北部China North

创建云服务 Create a cloud service

在 Azure 中创建应用程序并运行它时,相关代码和配置统称为 Azure 云服务When you create an application and run it in Azure, the code and configuration together are called an Azure cloud service. (在早期版本的 Azure中,它称为“托管服务”。)可以使用 create_hosted_service 方法创建新的托管服务。(It was known as a hosted service in earlier Azure releases.) You can use the create_hosted_service method to create a new hosted service. 通过提供托管服务名称(它在 Azure 中必须是唯一的)、标签(自动编码为 base64)、说明和位置来创建服务。Create the service by providing a hosted service name (which must be unique in Azure), a label (automatically encoded to base64), a description, and a location.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

name = 'myhostedservice'
label = 'myhostedservice'
desc = 'my hosted service'
location = 'China East'

sms.create_hosted_service(name, label, desc, location)

可使用 list_hosted_services 方法列出订阅的所有托管服务:You can list all the hosted services for your subscription with the list_hosted_services method:

result = sms.list_hosted_services()

for hosted_service in result:
    print('Service name: ' + hosted_service.service_name)
    print('Management URL: ' + hosted_service.url)
    print('Location: ' + hosted_service.hosted_service_properties.location)
    print('')

要获取有关特定托管服务的信息,请将托管服务名称传递给 get_hosted_service_properties 方法。To get information about a particular hosted service, pass the hosted service name to the get_hosted_service_properties method.

hosted_service = sms.get_hosted_service_properties('myhostedservice')

print('Service name: ' + hosted_service.service_name)
print('Management URL: ' + hosted_service.url)
print('Location: ' + hosted_service.hosted_service_properties.location)

在创建云服务后,请使用 create_deployment 方法将代码部署到服务。After you create a cloud service, deploy your code to the service with the create_deployment method.

删除云服务 Delete a cloud service

可以通过将服务名称传递给 delete_hosted_service 方法来删除云服务。You can delete a cloud service by passing the service name to the delete_hosted_service method.

sms.delete_hosted_service('myhostedservice')

必须先删除服务的所有部署,然后才能删除服务。Before you can delete a service, all deployments for the service must first be deleted. 有关详细信息,请参阅删除部署For more information, see Delete a deployment.

删除部署 Delete a deployment

若要删除部署,请使用 delete_deployment 方法。To delete a deployment, use the delete_deployment method. 下面的示例演示如何删除名为 v1 的部署:The following example shows how to delete a deployment named v1:

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

sms.delete_deployment('myhostedservice', 'v1')

创建存储服务 Create a storage service

利用存储服务,可以访问 Azure Blob队列A storage service gives you access to Azure blobs, tables, and queues. 若要创建存储服务,需要为服务命名(名称为 3 到 24 个小写字符且在 Azure 中唯一)。To create a storage service, you need a name for the service (between 3 and 24 lowercase characters and unique within Azure). 还需要说明、标签(最多 100 个字符,自动编码为 base64)和位置。You also need a description, a label (up to 100 characters, automatically encoded to base64), and a location. 下面的示例演示如何通过指定位置来创建存储服务:The following example shows how to create a storage service by specifying a location:

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

name = 'mystorageaccount'
label = 'mystorageaccount'
location = 'China East'
desc = 'My storage account description.'

result = sms.create_storage_account(name, desc, label, location=location)

operation_result = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation_result.status)

在上面的示例中,可以通过将 create_storage_account 返回的结果传递给 get_operation_status 方法来检索 create_storage_account 操作的状态。In the preceding example, the status of the create_storage_account operation can be retrieved by passing the result returned by create_storage_account to the get_operation_status method.

可以使用 list_storage_accounts 方法列出存储帐户及其属性。You can list your storage accounts and their properties with the list_storage_accounts method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

result = sms.list_storage_accounts()
for account in result:
    print('Service name: ' + account.service_name)
    print('Location: ' + account.storage_service_properties.location)
    print('')

删除存储服务 Delete a storage service

要删除存储服务,请将存储服务名称传递给 delete_storage_account 方法。To delete a storage service, pass the storage service name to the delete_storage_account method. 删除存储服务会删除该服务中存储的所有数据(Blob、表和队列)。Deleting a storage service deletes all data stored in the service (blobs, tables, and queues).

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

sms.delete_storage_account('mystorageaccount')

列出可用操作系统 List available operating systems

要列出可用于托管服务的操作系统,请使用 list_operating_systems 方法。To list the operating systems that are available for hosting services, use the list_operating_systems method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

result = sms.list_operating_systems()

for os in result:
    print('OS: ' + os.label)
    print('Family: ' + os.family_label)
    print('Active: ' + str(os.is_active))

或者,可以使用 list_operating_system_families 方法,按系列对操作系统进行分组。Alternatively, you can use the list_operating_system_families method, which groups the operating systems by family.

result = sms.list_operating_system_families()

for family in result:
    print('Family: ' + family.label)
    for os in family.operating_systems:
        if os.is_active:
            print('OS: ' + os.label)
            print('Version: ' + os.version)
    print('')

创建操作系统映像 Create an operating system image

要将操作系统映像添加到映像存储库中,请使用 add_os_image 方法。To add an operating system image to the image repository, use the add_os_image method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

name = 'mycentos'
label = 'mycentos'
os = 'Linux' # Linux or Windows
media_link = 'url_to_storage_blob_for_source_image_vhd'

result = sms.add_os_image(label, media_link, name, os)

operation_result = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation_result.status)

若要列出可用的操作系统映像,请使用 list_os_images 方法。To list the operating system images that are available, use the list_os_images method. 这包括所有平台映像和用户映像:It includes all platform images and user images:

result = sms.list_os_images()

for image in result:
    print('Name: ' + image.name)
    print('Label: ' + image.label)
    print('OS: ' + image.os)
    print('Category: ' + image.category)
    print('Description: ' + image.description)
    print('Location: ' + image.location)
    print('Media link: ' + image.media_link)
    print('')

删除操作系统映像 Delete an operating system image

要删除用户映像,请使用 delete_os_image 方法。To delete a user image, use the delete_os_image method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

result = sms.delete_os_image('mycentos')

operation_result = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation_result.status)

创建虚拟机 Create a virtual machine

若要创建虚拟机,首先需要创建 云服务To create a virtual machine, you first need to create a cloud service. 然后使用 create_virtual_machine_deployment 方法来创建虚拟机部署。Then create the virtual machine deployment by using the create_virtual_machine_deployment method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

name = 'myvm'
location = 'China East'

#Set the location
sms.create_hosted_service(service_name=name,
    label=name,
    location=location)

# Name of an os image as returned by list_os_images
image_name = 'OpenLogic__OpenLogic-CentOS-62-20120531-en-us-30GB.vhd'

# Destination storage account container/blob where the VM disk
# will be created
media_link = 'url_to_target_storage_blob_for_vm_hd'

# Linux VM configuration, you can use WindowsConfigurationSet
# for a Windows VM instead
linux_config = LinuxConfigurationSet('myhostname', 'myuser', 'mypassword', True)

os_hd = OSVirtualHardDisk(image_name, media_link)

sms.create_virtual_machine_deployment(service_name=name,
    deployment_name=name,
    deployment_slot='production',
    label=name,
    role_name=name,
    system_config=linux_config,
    os_virtual_hard_disk=os_hd,
    role_size='Small')

删除虚拟机 Delete a virtual machine

要删除虚拟机,请首先使用 delete_deployment 方法来删除部署。To delete a virtual machine, you first delete the deployment by using the delete_deployment method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

sms.delete_deployment(service_name='myvm',
    deployment_name='myvm')

然后可以使用 delete_hosted_service 方法来删除云服务。The cloud service can then be deleted by using the delete_hosted_service method.

sms.delete_hosted_service(service_name='myvm')

基于捕获的虚拟机映像创建虚拟机Create a virtual machine from a captured virtual machine image

要捕获 VM 映像,请先调用 capture_vm_image 方法。To capture a VM image, you first call the capture_vm_image method.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

# replace the below three parameters with actual values
hosted_service_name = 'hs1'
deployment_name = 'dep1'
vm_name = 'vm1'

image_name = vm_name + 'image'
image = CaptureRoleAsVMImage    ('Specialized',
    image_name,
    image_name + 'label',
    image_name + 'description',
    'english',
    'mygroup')

result = sms.capture_vm_image(
        hosted_service_name,
        deployment_name,
        vm_name,
        image
    )

要确保成功捕获映像,请使用 list_vm_images API。To make sure that you successfully captured the image, use the list_vm_images API. 请确保结果中显示映像。Make sure your image is displayed in the results.

images = sms.list_vm_images()

最后,为了使用捕获的映像创建虚拟机,请像前面一样使用 create_virtual_machine_deployment 方法,不过这次要传入 vm_image_name。To finally create the virtual machine by using the captured image, use the create_virtual_machine_deployment method as before, but this time pass in the vm_image_name instead.

from azure import *
from azure.servicemanagement import *

sms = ServiceManagementService(subscription_id, certificate_path)

name = 'myvm'
location = 'China North'

#Set the location
sms.create_hosted_service(service_name=name,
    label=name,
    location=location)

sms.create_virtual_machine_deployment(service_name=name,
    deployment_name=name,
    deployment_slot='production',
    label=name,
    role_name=name,
    system_config=linux_config,
    os_virtual_hard_disk=None,
    role_size='Small',
    vm_image_name = image_name)

要详细了解如何在经典部署模型中捕获 Linux 虚拟机,请参阅捕获 Linux 虚拟机To learn more about how to capture a Linux virtual machine in the classic deployment model, see Capture a Linux virtual machine.

要详细了解如何在经典部署模型中捕获 Windows 虚拟机,请参阅捕获 Windows 虚拟机To learn more about how to capture a Windows virtual machine in the classic deployment model, see Capture a Windows virtual machine.

后续步骤 Next Steps

既已了解有关服务管理的基础知识,现可访问 Azure Python SDK 的完整 API 参考文档 ,轻松执行复杂任务来管理 Python 应用程序。Now that you've learned the basics of service management, you can access the Complete API reference documentation for the Azure Python SDK and perform complex tasks easily to manage your python application.

有关详细信息,请参阅 Python 开发人员中心For more information, see the Python Developer Center.