以编程方式上传 Azure Batch 作业应用程序包

Upload Azure Batch Job Application Package programmatically

我找到了如何通过 UI:

upload/manage Azure Batch 作业应用程序包

https://docs.microsoft.com/en-us/azure/batch/batch-application-packages

以及如何以编程方式上传和管理资源包:

https://github.com/Azure/azure-batch-samples/tree/master/CSharp/GettingStarted/02_PoolsAndResourceFiles

但关于如何以编程方式管理应用程序包,我似乎无法将 2 和 2 放在一起。在设置批处理作业时,我们可以调用 upload/manage 应用程序包的 API 端点吗?

Azure Batch 应用程序包管理操作发生在管理平面上。此命名空间的 MSDN 文档位于此处:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.management.batch

Microsoft.Azure.Management.Batch 的 nuget 包在这里:

https://www.nuget.org/packages/Microsoft.Azure.Management.Batch/

下面的示例显示了 C# 中的管理平面操作,尽管它用于 non-application 包操作:

https://github.com/Azure/azure-batch-samples/tree/master/CSharp/AccountManagement

由于这不是很简单,我将写下我的发现。 这些是通过无人值守的应用程序以编程方式上传应用程序包的步骤 - 不需要用户输入(例如 Azure 凭据)。

在 Azure 门户中:

  • 创建 Azure Batch 应用程序
  • Create a new Azure AD application(作为应用程序类型使用 Web app / API
  • 按照 these steps 创建密钥并将角色分配给 Azure Batch 帐户
  • 记下以下内容credentials/ids:
    • Azure AD 应用程序 ID
    • Azure AD 应用程序密钥
    • Azure AD tenant id
    • Subscription id
    • 批量账户名
    • 批量账号资源组名称

在您的代码中:

将整个代码放在一起看起来像这样:

private const string ResourceUri = "https://management.core.windows.net/";
private const string AuthUri = "https://login.microsoftonline.com/" + "{TenantId}";
private const string ApplicationId = "{ApplicationId}";
private const string ApplicationSecretKey = "{ApplicationSecretKey}";
private const string SubscriptionId = "{SubscriptionId}";
private const string ResourceGroupName = "{ResourceGroupName}";
private const string BatchAccountName = "{BatchAccountName}";

private async Task UploadApplicationPackageAsync() {
    // get the access token
    var authContext = new AuthenticationContext(AuthUri);
    var authResult = await authContext.AcquireTokenAsync(ResourceUri, new ClientCredential(ApplicationId, ApplicationSecretKey)).ConfigureAwait(false);

    // create the BatchManagementClient and set the subscription id
    var bmc = new BatchManagementClient(new TokenCredentials(authResult.AccessToken)) {
        SubscriptionId = SubscriptionId
    };

    // create the application package
    var createResult = await bmc.ApplicationPackage.CreateWithHttpMessagesAsync(ResourceGroupName, BatchAccountName, "MyPackage", "1.0").ConfigureAwait(false);

    // upload the package to the blob storage
    var cloudBlockBlob = new CloudBlockBlob(new Uri(createResult.Body.StorageUrl));
    cloudBlockBlob.Properties.ContentType = "application/x-zip-compressed";
    await cloudBlockBlob.UploadFromFileAsync("myZip.zip").ConfigureAwait(false);

    // create the application package
    var activateResult = await bmc.ApplicationPackage.ActivateWithHttpMessagesAsync(ResourceGroupName, BatchAccountName, "MyPackage", "1.0", "zip").ConfigureAwait(false);
}