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

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

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

用于 Azure Stack 资源管理器的 Ruby SDK 提供了相关工具来帮助构建和管理基础结构。The Ruby SDK for the Azure Stack Resource Manager provides tools to help you build and manage your infrastructure. 该 SDK 中的资源提供程序包括了采用 Ruby 语言的计算、虚拟网络和存储提供程序。Resource providers in the SDK include Compute, Virtual Networks, and Storage, with the Ruby language. Ruby SDK 中的 API 配置文件可以用来在公有云 Azure 资源和 Azure Stack 上的资源之间进行切换,实现混合云开发。API profiles in the Ruby SDK enable hybrid cloud development by helping you switch between global Azure resources and resources on Azure Stack.

API 配置文件是资源提供程序和服务版本的组合。An API profile is a combination of resource providers and service versions. 可以使用 API 配置文件来组合不同的资源类型。You can use an API profile to combine different resource types.

  • 若要使用所有服务的最新版本,请使用 Azure SDK 汇总 gem 的最新配置文件。To use the latest versions of all the services, use the Latest profile of the Azure SDK rollup gem.
  • 若要使用与 Azure Stack 兼容的服务,请使用 Azure SDK 汇总 gem 的 V2019_03_01_HybridV2018_03_01 配置文件。To use the services compatible with the Azure Stack, use the V2019_03_01_Hybrid or V2018_03_01 profile of the Azure SDK rollup gem.
  • 若要使用某个服务的最新 api-version,请使用特定 gem 的最新配置文件。To use the latest api-version of a service, use the Latest profile of the specific gem. 例如,若要单独使用计算服务的最新 api-version,请使用计算 gem 的最新配置文件。For example, to use the latest api-version of compute service alone, use the Latest profile of the Compute gem.
  • 若要使用某个服务的特定 api-version,请使用在 gem 中定义的特定 API 版本。To use a specific api-version for a service, use the specific API versions defined inside the gem.

Note

可以在同一应用中组合所有选项。You can combine all of the options in the same app.

安装 Azure Ruby SDKInstall the Azure Ruby SDK

  • 遵照官方说明安装 GitFollow the official instructions to install Git.

  • 遵照官方说明安装 RubyFollow the official instructions to install Ruby.

    • 在安装时选择“将 Ruby 添加到 PATH 变量”。 When installing, choose Add Ruby to PATH variable.

    • 在 Ruby 安装过程中出现提示时,安装开发工具包。When prompted during Ruby installation, install the development kit.

    • 接下来,使用以下命令安装捆绑程序:Next, install the bundler using the following command:

      Gem install bundler
      
  • 如果不可用,请创建订阅,并保存订阅 ID 供稍后使用。If not available, create a subscription and save the subscription ID to be used later. 有关创建订阅的说明,请参阅在 Azure Stack 中创建套餐的订阅一文。Instructions to create a subscription are in the Create subscriptions to offers in Azure Stack article.

  • 创建服务主体并保存其 ID 和机密。Create a service principal and save its ID and secret. 有关为 Azure Stack 创建服务主体的说明,请参阅使用应用标识访问资源一文。Instructions to create a service principal for Azure Stack are in the Use an app identity to access resources article.

  • 确保服务主体在订阅上分配有“参与者/所有者”角色。Make sure your service principal has the contributor/owner role assigned on your subscription. 有关如何将角色分配给服务主体的说明,请参阅使用应用标识访问资源一文。Instructions on how to assign a role to a service principal are in the Use an app identity to access resources.

安装 RubyGem 包Install the RubyGem packages

可以直接安装 Azure RubyGem 包。You can install the Azure RubyGem packages directly.

gem install azure_mgmt_compute
gem install azure_mgmt_storage
gem install azure_mgmt_resources
gem install azure_mgmt_network

也可以在 Gemfile 中使用这些包。Or, use them in your Gemfile.

gem 'azure_mgmt_storage'
gem 'azure_mgmt_compute'
gem 'azure_mgmt_resources'
gem 'azure_mgmt_network'

Azure 资源管理器 Ruby SDK 为预览版,在即将推出的版本中可能会有重大界面更改。The Azure Resource Manager Ruby SDK is in preview and will likely have breaking interface changes in upcoming releases. 在次要版本中,编号数字增加可能表示重大更改。An increased number in the minor version may indicate breaking changes.

使用 azure_sdk gemUse the azure_sdk gem

azure_sdk gem 汇总了 Ruby SDK 中所有受支持的 gem。The azure_sdk gem is a rollup of all the supported gems in the Ruby SDK. 此 gem 包含的 最新 配置文件支持所有服务的最新版本。This gem consists of a Latest profile, which supports the latest version of all services. 它包括为 Azure Stack 生成的版本控制配置文件  V2017_03_09V2019_03_01_HybridIt includes versioned profiles V2017_03_09 and V2019_03_01_Hybrid, which are built for Azure Stack.

可使用以下命令安装 azure_sdk 汇总 gem:You can install the azure_sdk rollup gem with the following command:

gem install 'azure_sdk'

先决条件Prerequisites

若要将 Ruby Azure SDK 与 Azure Stack 配合使用,必须提供以下值,然后使用环境变量来设置值。To use the Ruby Azure SDK with Azure Stack, you must supply the following values, and then set the values with environment variables. 若要设置环境变量,请参阅表后针对特定操作系统的说明。To set the environmental variables, see the instructions following the 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.

Azure Stack 资源管理器终结点The Azure Stack Resource Manager endpoint

Azure 资源管理器是一种管理框架,可供管理员用来部署、管理和监视 Azure 资源。The Azure Resource Manager is a management framework that allows admins to deploy, manage, and monitor Azure resources. Azure 资源管理器可以通过单个操作以组任务而不是单个任务的形式处理这些任务。Azure Resource Manager can handle these tasks as a group, rather than individually, in a single operation.

可以从资源管理器终结点获取元数据信息。You can get the metadata info from the Resource Manager endpoint. 该终结点返回 JSON 文件,其中包含运行代码所需的信息。The endpoint returns a JSON file with the info required to run your code.

Note

Azure Stack 开发工具包 (ASDK) 中的 ResourceManagerUrl 为:https://management.local.azurestack.external/集成系统中的 ResourceManagerUrl 为:https://management.<location>.ext-<machine-name>.masd.stbtest.microsoft.com/The ResourceManagerUrl in the Azure Stack Development Kit (ASDK) is: https://management.local.azurestack.external/ The ResourceManagerUrl in integrated systems is: https://management.<location>.ext-<machine-name>.masd.stbtest.microsoft.com/
检索所需的元数据:<ResourceManagerUrl>/metadata/endpoints?api-version=1.0To retrieve the metadata required: <ResourceManagerUrl>/metadata/endpoints?api-version=1.0

示例 JSON 文件:Sample JSON file:

{
  "galleryEndpoint": "https://portal.local.azurestack.external:30015/",  
  "graphEndpoint": "https://graph.chinacloudapi.cn/",  
  "portal Endpoint": "https://portal.local.azurestack.external/",
  "authentication": {
    "loginEndpoint": "https://login.chinacloudapi.cn/", 
     "audiences": ["https://management.<yourtenant>.partner.onmschina.cn/3cc5febd-e4b7-4a85-a2ed-1d730e2f5928"]
  }
}

设置环境变量。Set environment variables

Microsoft WindowsMicrosoft Windows

若要设置环境变量,请在 Windows 命令提示符下使用以下格式:To set the environment variables, use the following format in a Windows command prompt:

set AZURE_TENANT_ID=<YOUR_TENANT_ID>

基于 macOS、Linux 和 Unix 的系统macOS, Linux, and Unix-based systems

在基于 Unix 的系统中,使用以下命令:In Unix-based systems, use the following command:

export AZURE_TENANT_ID=<YOUR_TENANT_ID>

现有 API 配置文件Existing API profiles

Azure_sdk 汇总 gem 包含以下 3 个配置文件:The Azure_sdk rollup gem has the following 3 profiles:

  • V2019_03_01_Hybrid:为 Azure Stack 生成的配置文件。V2019_03_01_Hybrid: Profile built for Azure Stack. 将此配置文件用于 Azure Stack 版本 1904 或更高版本中提供的所有最新版服务。Use this profile for all the latest versions of services available in Azure Stack version 1904 or later.
  • V2017_03_09:为 Azure Stack 生成的配置文件。V2017_03_09: Profile built for Azure Stack. 使用此配置文件可以使服务与 Azure Stack 版本 1808 或更早版本最兼容。Use this profile for services to be most compatible with Azure Stack version 1808 or earlier.
  • 最新:配置文件包含所有服务的最新版本。Latest: Profile consists of the latest versions of all services. 使用所有服务的最新版本。Use the latest versions of all the services.

有关 Azure Stack 和 API 配置文件的详细信息,请参阅 API 配置文件的摘要For more info on Azure Stack and API profiles, see the Summary of API profiles.

Azure Ruby SDK API 配置文件的使用Azure Ruby SDK API profile usage

使用以下代码实例化配置文件客户端。Use the following code to instantiate a profile client. 此参数只是 Azure Stack 或其他私有云所需要的。This parameter is only required for Azure Stack or other private clouds. 默认情况下,公有云 Azure 已经有这些设置。Global Azure already has these settings by default.

active_directory_settings = get_active_directory_settings(ENV['ARM_ENDPOINT'])

provider = MsRestAzure::ApplicationTokenProvider.new(
  ENV['AZURE_TENANT_ID'],
  ENV['AZURE_CLIENT_ID'],
  ENV['AZURE_CLIENT_SECRET'],
  active_directory_settings
)
credentials = MsRest::TokenCredentials.new(provider)
options = {
  credentials: credentials,
  subscription_id: subscription_id,
  active_directory_settings: active_directory_settings,
  base_url: ENV['ARM_ENDPOINT']
}

# Target profile built for Azure Stack
client = Azure::Resources::Profiles::V2019_03_01_Hybrid::Mgmt::Client.new(options)

可以使用配置文件客户端来访问单个资源提供程序,例如计算、存储和网络提供程序:The profile client can be used to access individual resource providers, such as Compute, Storage, and Network:

# To access the operations associated with Compute
profile_client.compute.virtual_machines.get 'RESOURCE_GROUP_NAME', 'VIRTUAL_MACHINE_NAME'

# Option 1: To access the models associated with Compute
purchase_plan_obj = profile_client.compute.model_classes.purchase_plan.new

# Option 2: To access the models associated with Compute
# Notice Namespace: Azure::Profiles::<Profile Name>::<Service Name>::Mgmt::Models::<Model Name>
purchase_plan_obj = Azure::Profiles::V2019_03_01_Hybrid::Compute::Mgmt::Models::PurchasePlan.new

定义 Azure Stack 环境设置函数Define Azure Stack environment setting functions

若要通过 Azure Stack 环境进行服务主体身份验证,请使用 get_active_directory_settings() 来定义终结点To authenticate the service principal to the Azure Stack environment, define the endpoints using get_active_directory_settings(). 此方法使用之前设置的 ARM_Endpoint 环境变量:This method uses the ARM_Endpoint environment variable that you set previously:

# Get Authentication endpoints using Arm Metadata Endpoints
def get_active_directory_settings(armEndpoint)
  settings = MsRestAzure::ActiveDirectoryServiceSettings.new
  response = Net::HTTP.get_response(URI("#{armEndpoint}/metadata/endpoints?api-version=1.0"))
  status_code = response.code
  response_content = response.body
  unless status_code == "200"
    error_model = JSON.load(response_content)
    fail MsRestAzure::AzureOperationError.new("Getting Azure Stack Metadata Endpoints", response, error_model)
  end
  result = JSON.load(response_content)
  settings.authentication_endpoint = result['authentication']['loginEndpoint'] unless result['authentication']['loginEndpoint'].nil?
  settings.token_audience = result['authentication']['audiences'][0] unless result['authentication']['audiences'][0].nil?
  settings
end

使用 API 配置文件的示例Samples using API profiles

参考 GitHub 上的以下示例,使用 Ruby 和 Azure Stack API 配置文件来创建解决方案:Use the following samples on GitHub as references for creating solutions with Ruby and Azure Stack API profiles:

示例资源管理器和组Sample Resource Manager and groups

若要运行示例,请确保已安装 Ruby。To run the sample, ensure that you've installed Ruby. 如果使用 Visual Studio Code,也请下载 Ruby SDK 扩展。If you're using Visual Studio Code, download the Ruby SDK extension as well.

Note

示例的存储库是 Hybrid-Resource-Manager-Ruby-Resources-And-GroupsThe repository for the sample is Hybrid-Resource-Manager-Ruby-Resources-And-Groups.

  1. 克隆存储库:Clone the repository:

    git clone https://github.com/Azure-Samples/Hybrid-Resource-Manager-Ruby-Resources-And-Groups.git
    
  2. 使用捆绑安装依赖项:Install the dependencies using bundle:

    cd Hybrid-Resource-Manager-Ruby-Resources-And-Groups
    bundle install
    
  3. 使用 PowerShell 创建 Azure 服务主体,然后检索所需的值。Create an Azure service principal using PowerShell and retrieve the values needed.

    有关如何创建服务主体的说明,请参阅使用 Azure PowerShell 创建具有证书的服务主体For instructions on creating a service principal, see Use Azure PowerShell to create a service principal with a certificate.

    所需值为:Values needed are:

    • 租户 IDTenant ID
    • 客户端 IDClient ID
    • 客户端机密Client secret
    • 订阅 IDSubscription ID
    • 资源管理器终结点Resource Manager endpoint

    使用从已创建的服务主体检索的信息设置以下环境变量:Set the following environment variables using the information retrieved from the service principal you created:

    • 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 Azure Stack Resource Manager URL}

    Note

    在 Windows 上,使用 set 而不是 exportOn Windows, use set instead of export.

  4. 确保将位置变量设置为你的 Azure Stack 位置,例如 LOCAL="local"Ensure the location variable is set to your Azure Stack location; for example, LOCAL="local".

  5. 若要定位正确的活动目录终结点,如果你使用的是 Azure Stack 或其他私有云,请添加以下代码行:To target the correct active directory endpoints, add the following line of code if you're using Azure Stack or other private clouds:

    active_directory_settings = get_active_directory_settings(ENV['ARM_ENDPOINT'])
    
  6. options 变量中添加 Active Directory 设置和适用于 Azure Stack 的基 URL:In the options variable, add the Active Directory settings and the base URL to work with Azure Stack:

    options = {
    credentials: credentials,
    subscription_id: subscription_id,
    active_directory_settings: active_directory_settings,
    base_url: ENV['ARM_ENDPOINT']
    }
    
  7. 创建以 Azure Stack 配置文件为目标的配置文件客户端:Create a profile client that targets the Azure Stack profile:

    client = Azure::Resources::Profiles::V2019_03_01_Hybrid::Mgmt::Client.new(options)
    
  8. 若要通过 Azure Stack 进行服务主体身份验证,应使用 get_active_directory_settings() 来定义终结点。To authenticate the service principal with Azure Stack, the endpoints should be defined using get_active_directory_settings(). 此方法使用之前设置的 ARM_Endpoint 环境变量:This method uses the ARM_Endpoint environment variable that you set previously:

    def get_active_directory_settings(armEndpoint)
      settings = MsRestAzure::ActiveDirectoryServiceSettings.new
      response = Net::HTTP.get_response(URI("#{armEndpoint}/metadata/endpoints?api-version=1.0"))
      status_code = response.code
      response_content = response.body
      unless status_code == "200"
        error_model = JSON.load(response_content)
        fail MsRestAzure::AzureOperationError.new("Getting Azure Stack Metadata Endpoints", response, error_model)
      end
      result = JSON.load(response_content)
      settings.authentication_endpoint = result['authentication']['loginEndpoint'] unless result['authentication']['loginEndpoint'].nil?
      settings.token_audience = result['authentication']['audiences'][0] unless result['authentication']['audiences'][0].nil?
      settings
    end
    
  9. 运行示例。Run the sample.

    bundle exec ruby example.rb
    

后续步骤Next steps