在 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 的 V2018_03_01 配置文件。To use the services compatible with the Azure Stack, use the 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, if you would like 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 application.

安装 Azure Ruby SDKInstall the Azure Ruby SDK

  • 遵照官方说明安装 GitFollow the official instructions to install Git.
  • 遵照官方说明安装 RubyFollow the official instructions to install Ruby.
    • 在安装时选择“将 Ruby 添加到 PATH 变量”。While installing, choose Add Ruby to PATH variable.
    • 在 Ruby 安装过程中根据提示安装开发工具包。Install the development kit during Ruby installation when prompted.
    • 接下来,使用以下命令安装捆绑程序: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. 此处提供创建订阅的说明。Instructions to create a subscription are here.
  • 创建服务主体并保存其 ID 和机密。Create a service principal and save its ID and secret. 此处提供创建 Azure Stack 服务主体的说明。Instructions to create a service principal for Azure Stack are here.
  • 确保服务主体在订阅上具有“参与者/所有者”角色。Make sure your service principal has contributor/owner role on your subscription. 此处提供如何为服务主体分配角色的说明。Instructions on how to assign role to service principal are here.

安装 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
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 gem, azure_sdk, 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_09V2018_03_01 。It introduces two versioned profile V2017_03_09 and V2018_03_01 profiles, 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 配合使用,必须提供以下值,然后使用环境变量来设置值。In order to use the Ruby Azure SDK with Azure Stack, you must supply the following values, and then set the values with environment variables. 请参阅表后针对操作系统的说明,了解如何设置环境变量。See the instructions after the table for your operating system on setting the environmental variables.

ValueValue 环境变量Environment variables 说明Description
租户 IDTenant ID AZURE_TENANT_IDAZURE_TENANT_ID Azure Stack 租户 ID 的值。The value of your Azure Stack tenant ID.
客户端 IDClient ID AZURE_CLIENT_IDAZURE_CLIENT_ID 在本文档上一部分创建服务主体时保存的服务主体应用程序 ID。The service principal application ID saved when service principal was created on the previous section of this document.
订阅 IDSubscription ID AZURE_SUBSCRIPTION_IDAZURE_SUBSCRIPTION_ID 订阅 ID 用于访问 Azure Stack 中的套餐。The subscription ID is how you access offers in Azure Stack.
客户端机密Client Secret AZURE_CLIENT_SECRETAZURE_CLIENT_SECRET 创建服务主体时保存的服务主体应用程序机密。The service principal application Secret saved when service principal was created.
资源管理器终结点Resource Manager Endpoint ARM_ENDPOINTARM_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 administrators 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 information from the Resource Manager endpoint. 该终结点返回 JSON 文件,以及运行代码所需的信息。The endpoint returns a JSON file with the information 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 environmental variables

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

基于 macOS、Linux 和 Unix 的系统在基于 Unix 的系统中,可以使用以下命令:macOS, Linux, and Unix-based systems In Unix based systems, you can use the following command:
export AZURE_TENANT_ID=<YOUR_TENANT_ID>

现有 API 配置文件Existing API profiles

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

  1. V2018_03_01 为 Azure Stack 生成的配置文件。V2018_03_01 Profile built for Azure Stack. 使用此配置文件可以利用 Azure Stack 中提供的所有最新版服务。Use this profile for utilizing all the latest versions of services available in Azure Stack.
  2. V2017_03_09V2017_03_09
    为 Azure Stack 生成的配置文件。Profile built for Azure Stack. 请将此配置文件用于会与 Azure Stack 最兼容的服务。Use this profile for services to be most compatible with the Azure Stack.
  3. 最新Latest
    配置文件包含所有服务的最新版本。Profile consists of latest versions of all services. 使用所有服务的最新版本。Use the latest versions of all the services.

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

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

可使用以下代码来实例化配置文件客户端。You can 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::V2018_03_01::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::V2018_03_01::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 when establishing your environmental variables:

# 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 配置文件来创建解决方案:You can use the following samples found 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 have installed Ruby. 如果使用 Visual Studio Code,也请下载 Ruby SDK 扩展。If you are using Visual Studio Code, download the Ruby SDK extension as well.

Note

Manage Azure resources and resource groups with Ruby(使用 Ruby 管理 Azure 资源和资源组)中提供了示例的存储库。You can get the repository for the sample at "Manage Azure resources and resource groups with Ruby".

  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 you retrieved from the Service Principal you created.

    • export AZURE_TENANT_ID={你的租户 ID}export AZURE_TENANT_ID={your tenant id}
    • export AZURE_CLIENT_ID={你的客户端 ID}export AZURE_CLIENT_ID={your client id}
    • export AZURE_CLIENT_SECRET={你的客户端机密}export AZURE_CLIENT_SECRET={your client secret}
    • export AZURE_SUBSCRIPTION_ID={你的订阅 ID}export AZURE_SUBSCRIPTION_ID={your subscription id}
    • export ARM_ENDPOINT={你的 AzureStack 资源管理器 URL}export ARM_ENDPOINT={your AzureStack Resource manager url}

    Note

    在 Windows 上,请使用 set 而不是 export。On 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 或其他私有云以适当的 Active Directory 终结点为目标,请在以下代码行中添加:Add the following line of code if you using Azure Stack or other private clouds to target the right active directory endpoints:

    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::V2018_03_01::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 when establishing your environmental variables:

    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