在 Azure Stack 中将 API 版本配置文件与 Python 配合使用Use API version profiles with Python in Azure Stack

适用于:Azure Stack 集成系统和 Azure Stack 开发工具包Applies to: Azure Stack integrated systems and Azure Stack Development Kit

Python SDK 支持 API 版本配置文件将不同的云平台(例如 Azure Stack 和 Azure)用作目标。The Python SDK supports API version profiles to target different cloud platforms, such as Azure Stack and Azure. 使用 API 配置文件为混合云创建解决方案。Use API profiles in creating solutions for a hybrid cloud.

本文中的说明要求 Azure 订阅。The instructions in this article require a Azure subscription. 如果没有该订阅,可以获取 1 元人民币的试用帐户If you don't have one, you can get a 1rmb trial account.

Python 与 API 版本配置文件Python and API version profiles

Python SDK 支持以下 API 配置文件:The Python SDK supports the following API profiles:

  • latestlatest
    此配置文件以 Azure 平台中所有服务提供程序的最新 API 版本为目标。This profile targets the most recent API versions for all service providers in the Azure platform.

  • 2019-03-01-hybrid2019-03-01-hybrid
    此配置文件针对版本 1904 或更高版本的 Azure Stack 平台中所有资源提供程序的最新 API 版本。This profile targets the latest API versions for all the resource providers in the Azure Stack platform for versions 1904 or later.

  • 2018-03-01-hybrid2018-03-01-hybrid
    此配置文件针对 Azure Stack 平台中所有资源提供程序的最兼容 API 版本。This profile targets the most compatible API versions for all the resource providers in the Azure Stack platform.

  • 2017-03-09-profile2017-03-09-profile
    此配置文件以 Azure Stack 支持的资源提供程序的大多数兼容 API 版本为目标。This profile targets the most compatible API versions of the resource providers supported by Azure Stack.

    有关 API 配置文件和 Azure Stack 的详细信息,请参阅在 Azure Stack 中管理 API 版本配置文件For more info on API profiles and Azure Stack, see Manage API version profiles in Azure Stack.

安装 Azure Python SDKInstall the Azure Python SDK

  1. 官方站点安装 Git。Install Git from the official site.
  2. 有关如何安装 Python SDK 的说明,请参阅面向 Python 开发人员的 AzureFor instructions on how to install the Python SDK, see Azure for Python developers.
  3. 如果此文不适用,请创建订阅,并保存订阅 ID 供以后使用。If not available, create a subscription and save the subscription ID to use later. 有关创建订阅的说明,请参阅在 Azure Stack 中创建套餐的订阅For instructions on creating a subscription, see Create subscriptions to offers in Azure Stack.
  4. 创建服务主体并保存其 ID 和机密。Create a service principal and save its ID and secret. 有关如何为 Azure Stack 创建服务主体的说明,请参阅提供对 Azure Stack 的应用程序访问权限For instructions on how to create a service principal for Azure Stack, see Provide applications access to Azure Stack.
  5. 确保服务主体在订阅上具有“参与者/所有者”角色。Make sure your service principal has the contributor/owner role on your subscription. 有关如何为服务主体分配角色的说明,请参阅提供对 Azure Stack 的应用程序访问权限For instructions on how to assign a role to your service principal, see Provide applications access to Azure Stack.

先决条件Prerequisites

若要将 Python Azure SDK 与 Azure Stack 配合使用,必须提供以下值,然后使用环境变量来设置值。To use the Python Azure SDK with Azure Stack, you must supply the following values and then set values with environment variables. 若要设置环境变量,请参阅下表后面针对特定操作系统的说明。To set the environment variables, see the instructions after the following table, for your specific operating system.

ValueValue 环境变量Environment variables 说明Description
租户 IDTenant ID AZURE_TENANT_ID Azure Stack 租户 IDYour Azure Stack tenant ID.
客户端 IDClient ID AZURE_CLIENT_ID 在本文上一部分创建服务主体时保存的服务主体应用 ID。The service principal app ID saved when the service principal was created in the previous section of this article.
订阅 IDSubscription ID AZURE_SUBSCRIPTION_ID 使用订阅 ID 访问 Azure Stack 中的套餐。You use the subscription ID to access offers in Azure Stack.
客户端机密Client secret AZURE_CLIENT_SECRET 创建服务主体时保存的服务主体应用机密。The service principal app secret saved when the service principal was created.
资源管理器终结点Resource Manager endpoint ARM_ENDPOINT 请参阅 Azure Stack 资源管理器终结点一文。See the Azure Stack Resource Manager endpoint article.
资源位置Resource location AZURE_RESOURCE_LOCATION Azure Stack 环境的资源位置。The resource location of your Azure Stack environment.

信任 Azure Stack CA 根证书Trust the Azure Stack CA root certificate

如果使用的是 ASDK,则必须显式信任远程计算机上的 CA 根证书。If you are using the ASDK, you must explicitly trust the CA root certificate on your remote machine. 不需要信任 Azure Stack 集成系统的 CA 根证书。You do not need to trust the CA root certificate with Azure Stack integrated systems.

WindowsWindows

  1. 在计算机上找到 Python 证书存储位置。Find the Python certificate store location on your machine. 该位置可能因 Python 的安装位置而异。The location may vary, depending on where you installed Python. 打开命令提示符或权限提升的 PowerShell 提示符,然后键入以下命令:Open a command prompt or an elevated PowerShell prompt, and type the following command:

      python -c "import certifi; print(certifi.where())"
    

    记下证书存储位置,例如, ~/lib/python3.5/site-packages/certifi/cacert.pemMake a note of the certificate store location; for example, ~/lib/python3.5/site-packages/certifi/cacert.pem. 具体的路径取决于操作系统以及安装的 Python 版本。Your particular path depends on your operating system and the version of Python that you have installed.

  2. 若要信任 Azure Stack CA 根书,请将它附加到现有的 Python 证书:Trust the Azure Stack CA root certificate by appending it to the existing Python certificate:

    $pemFile = "<Fully qualified path to the PEM certificate; for ex: C:\Users\user1\Downloads\root.pem>"
    
    $root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $root.Import($pemFile)
    
    Write-Host "Extracting required information from the cert file"
    $md5Hash    = (Get-FileHash -Path $pemFile -Algorithm MD5).Hash.ToLower()
    $sha1Hash   = (Get-FileHash -Path $pemFile -Algorithm SHA1).Hash.ToLower()
    $sha256Hash = (Get-FileHash -Path $pemFile -Algorithm SHA256).Hash.ToLower()
    
    $issuerEntry  = [string]::Format("# Issuer: {0}", $root.Issuer)
    $subjectEntry = [string]::Format("# Subject: {0}", $root.Subject)
    $labelEntry   = [string]::Format("# Label: {0}", $root.Subject.Split('=')[-1])
    $serialEntry  = [string]::Format("# Serial: {0}", $root.GetSerialNumberString().ToLower())
    $md5Entry     = [string]::Format("# MD5 Fingerprint: {0}", $md5Hash)
    $sha1Entry    = [string]::Format("# SHA1 Fingerprint: {0}", $sha1Hash)
    $sha256Entry  = [string]::Format("# SHA256 Fingerprint: {0}", $sha256Hash)
    $certText = (Get-Content -Path $pemFile -Raw).ToString().Replace("`r`n","`n")
    
    $rootCertEntry = "`n" + $issuerEntry + "`n" + $subjectEntry + "`n" + $labelEntry + "`n" + `
    $serialEntry + "`n" + $md5Entry + "`n" + $sha1Entry + "`n" + $sha256Entry + "`n" + $certText
    
    Write-Host "Adding the certificate content to Python Cert store"
    Add-Content "${env:ProgramFiles(x86)}\Python35\Lib\site-packages\certifi\cacert.pem" $rootCertEntry
    
    Write-Host "Python Cert store was updated to allow the Azure Stack CA root certificate"
    

Note

如果通过 Python SDK 使用 virtualenv 进行开发(如下面的运行 Python 示例部分所述),则必须向虚拟环境证书存储添加上述证书。If you are using virtualenv for developing with Python SDK as mentioned in the following Run the Python sample section, you must add the previous certificate to your virtual environment certificate store. 路径看起来可能类似于:..\mytestenv\Lib\site-packages\certifi\cacert.pemThe path might look similar to: ..\mytestenv\Lib\site-packages\certifi\cacert.pem.

适用于 Azure Stack 的 Python 示例Python samples for Azure Stack

下面是一些适用于 Azure Stack 的、使用 Python SDK 的代码示例:Some of the code samples available for Azure Stack using the Python SDK are:

管理虚拟机示例Manage virtual machine sample

使用以下 Python 代码示例对 Azure Stack 中的虚拟机 (VM) 执行常见管理任务。Use the following Python code sample to perform common management tasks for virtual machines (VMs) in your Azure Stack. 该代码示例演示如何执行以下操作:The code sample shows you how to:

  • 创建 VM:Create VMs:
    • 创建 Linux VMCreate a Linux VM
    • 创建 Windows VMCreate a Windows VM
  • 更新 VM:Update a VM:
    • 扩展驱动器Expand a drive
    • 标记 VMTag a VM
    • 附加数据磁盘Attach data disks
    • 分离数据磁盘Detach data disks
  • 操作 VM:Operate a VM:
    • 启动 VMStart a VM
    • 停止 VMStop a VM
    • 重新启动 VMRestart a VM
  • 列出 VMList VMs
  • 删除 VMDelete a VM

若要查看执行这些操作的代码,请参阅 GitHub 存储库 Hybrid-Compute-Python-Manage-VM 中的 Python 脚本 example.py 中的 run_example() 函数。To review the code that performs these operations, see the run_example() function in the Python script example.py in the GitHub repo Hybrid-Compute-Python-Manage-VM.

每个操作都清晰地带有注释和一个 print 函数。Each operation is clearly labeled with a comment and a print function. 这些示例不一定按此列表中显示的顺序执行。The examples are not necessarily in the order shown in this list.

运行 Python 示例Run the Python sample

  1. 安装 Python(如果尚未安装)。Install Python if not already installed. 此示例(和 SDK)与 Python 2.7、3.4、3.5 和 3.6 兼容。This sample (and the SDK) is compatible with Python 2.7, 3.4, 3.5, and 3.6.

  2. 对于 Python 开发,通常建议使用虚拟环境。A general recommendation for Python development is to use a virtual environment. 有关详细信息,请参阅 Python 文档For more information, see the Python documentation.

  3. 在 Python 3 上,请使用 venv 模块安装并初始化虚拟环境(对于 Python 2.7,必须安装 virtualenv):Install and initialize the virtual environment with the venv module on Python 3 (you must install virtualenv for Python 2.7):

    python -m venv mytestenv # Might be "python3" or "py -3.6" depending on your Python installation
    cd mytestenv
    source bin/activate      # Linux shell (Bash, ZSH, etc.) only
    ./scripts/activate       # PowerShell only
    ./scripts/activate.bat   # Windows CMD only
    
  4. 克隆存储库:Clone the repository:

    git clone https://github.com/Azure-Samples/Hybrid-Compute-Python-Manage-VM.git
    
  5. 使用 pip 安装依赖项:Install the dependencies using pip:

    cd Hybrid-Compute-Python-Manage-VM
    pip install -r requirements.txt
    
  6. 创建要用于 Azure Stack 的服务主体Create a service principal to work with Azure Stack. 确保服务主体在订阅上具有“参与者/所有者”角色Make sure your service principal has the contributor/owner role on your subscription.

  7. 设置以下变量并将这些环境变量导出到当前 shell 中:Set the following variables and export these environment variables into your current shell:

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    export ARM_ENDPOINT={your AzureStack Resource Manager Endpoint}
    export AZURE_RESOURCE_LOCATION={your AzureStack Resource location}
    
  8. 若要运行此示例,Ubuntu 16.04-LTS 和 WindowsServer 2012-R2-DataCenter 映像必须存在于 Azure Stack 市场中。To run this sample, Ubuntu 16.04-LTS and WindowsServer 2012-R2-DataCenter images must be present in the Azure Stack Marketplace. 可以从 Azure 下载这些映像或者将其添加到平台映像存储库These images can be either downloaded from Azure, or added to the platform image repository.

  9. 运行示例:Run the sample:

    python example.py
    

后续步骤Next steps