Cria um novo pool dentro da conta especificada.
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}?api-version=2024-02-01
Parâmetros de URI
Nome |
Em |
Obrigatório |
Tipo |
Description |
accountName
|
path |
True
|
string
|
O nome da conta do Lote.
Regex pattern: ^[a-zA-Z0-9]+$
|
poolName
|
path |
True
|
string
|
O nome do pool. Isso deve ser exclusivo dentro da conta.
Regex pattern: ^[a-zA-Z0-9_-]+$
|
resourceGroupName
|
path |
True
|
string
|
O nome do grupo de recursos que contém a conta do Lote.
|
subscriptionId
|
path |
True
|
string
|
A ID de assinatura do Azure. Esta é uma cadeia de caracteres formatada por GUID (por exemplo, 000000000-0000-0000-0000-0000000000000)
|
api-version
|
query |
True
|
string
|
A versão da API a ser usada com a solicitação HTTP.
|
Nome |
Obrigatório |
Tipo |
Description |
If-Match
|
|
string
|
A versão do estado da entidade (ETag) do pool a ser atualizado. Um valor de "*" pode ser usado para aplicar a operação somente se o pool já existir. Se omitida, essa operação sempre será aplicada.
|
If-None-Match
|
|
string
|
Defina como '*' para permitir que um novo pool seja criado, mas para evitar a atualização de um pool existente. Outros valores serão ignorados.
|
Corpo da solicitação
Nome |
Tipo |
Description |
identity
|
BatchPoolIdentity
|
O tipo de identidade usado para o Pool do Lote.
O tipo de identidade usado para o Pool do Lote.
|
properties.applicationLicenses
|
string[]
|
A lista de licenças de aplicativo que o serviço do Lote disponibilizará em cada nó de computação no pool.
A lista de licenças de aplicativo deve ser um subconjunto de licenças de aplicativo de serviço do Lote disponíveis. Se uma licença for solicitada sem suporte, a criação do pool falhará.
|
properties.applicationPackages
|
ApplicationPackageReference[]
|
A lista de pacotes de aplicativos a serem instalados em cada nó de computação no pool.
As alterações nas referências do pacote de aplicativos afetam todos os novos nós de computação que ingressam no pool, mas não afetam os nós de computação que já estão no pool até que sejam reinicializados ou recriados. Há no máximo 10 referências de pacote de aplicativos em qualquer pool específico.
|
properties.certificates
|
CertificateReference[]
|
A lista de certificados a serem instalados em cada nó de computação no pool.
Para nós de computação do Windows, o serviço lote instala os certificados no repositório de certificados e no local especificados. Para nós de computação do Linux, os certificados são armazenados em um diretório dentro do diretório de trabalho da tarefa e uma variável de ambiente AZ_BATCH_CERTIFICATES_DIR é fornecida à tarefa para consultar esse local. Para certificados com visibilidade de 'remoteUser', um diretório 'certs' é criado no diretório base do usuário (por exemplo, /home/{user-name}/certs) e os certificados são colocados nesse diretório.
Aviso: essa propriedade foi preterida e será removida após fevereiro de 2024. Em vez disso, use a Extensão do Azure KeyVault .
|
properties.deploymentConfiguration
|
DeploymentConfiguration
|
Essa propriedade descreve como os nós do pool serão implantados usando Serviços de Nuvem ou Máquinas Virtuais.
O uso de CloudServiceConfiguration especifica que os nós devem ser criados usando o Azure Serviços de Nuvem (PaaS), enquanto VirtualMachineConfiguration usa IaaS (Azure Máquinas Virtuais).
|
properties.displayName
|
string
|
O nome de exibição do pool.
O nome de exibição não precisa ser exclusivo e pode conter caracteres Unicode até um comprimento máximo de 1024.
|
properties.interNodeCommunication
|
InterNodeCommunicationState
|
Se o pool permite comunicação direta entre nós.
Isso impõe restrições sobre quais nós podem ser atribuídos ao pool. Habilitar esse valor pode reduzir a chance do número solicitado de nós ser alocado no pool. Se não for especificado, esse valor usará como padrão 'Desabilitado'.
|
properties.metadata
|
MetadataItem[]
|
Uma lista de pares nome-valor associados ao pool como metadados.
O serviço lote não atribui nenhum significado aos metadados; é exclusivamente para o uso do código do usuário.
|
properties.mountConfiguration
|
MountConfiguration[]
|
Uma lista de sistemas de arquivos a serem montados em cada nó no pool.
Isso dá suporte a Arquivos do Azure, NFS, CIFS/SMB e Blobfuse.
|
properties.networkConfiguration
|
NetworkConfiguration
|
A configuração de rede para o pool.
A configuração de rede de um pool.
|
properties.resourceTags
|
object
|
As marcas especificadas pelo usuário associadas ao pool.
As marcas definidas pelo usuário a serem associadas ao pool de Lote do Azure. Quando especificadas, essas marcas são propagadas para os recursos do Azure de suporte associados ao pool. Essa propriedade só pode ser especificada quando a conta do Lote foi criada com a propriedade poolAllocationMode definida como 'UserSubscription'.
|
properties.scaleSettings
|
ScaleSettings
|
Configurações que definem o número de nós no pool.
Define o tamanho desejado do pool. Isso pode ser 'fixedScale' em que o targetDedicatedNodes solicitado é especificado ou 'autoScale' que define uma fórmula que é reavaliada periodicamente. Se essa propriedade não for especificada, o pool terá uma escala fixa com 0 targetDedicatedNodes.
|
properties.startTask
|
StartTask
|
Uma tarefa especificada para ser executada em cada nó de computação à medida que ele ingressa no pool.
Em uma operação PATCH (atualização), essa propriedade pode ser definida como um objeto vazio para remover a tarefa inicial do pool.
|
properties.targetNodeCommunicationMode
|
NodeCommunicationMode
|
O modo de comunicação de nó desejado para o pool.
Se omitido, o valor padrão será Default.
|
properties.taskSchedulingPolicy
|
TaskSchedulingPolicy
|
Como as tarefas são distribuídas entre nós de computação em um pool.
Se não for especificado, o padrão será spread.
|
properties.taskSlotsPerNode
|
integer
|
O número de slots de tarefas que podem ser usados para executar tarefas simultâneas em um único nó de computação no pool.
O valor padrão é 1. O valor máximo é o menor de 4 vezes o número de núcleos do vmSize do pool ou 256.
|
properties.upgradePolicy
|
UpgradePolicy
|
A política de atualização para o pool.
Descreve uma política de atualização – automática, manual ou sem interrupção.
|
properties.userAccounts
|
UserAccount[]
|
A lista de contas de usuário a serem criadas em cada nó no pool.
|
properties.vmSize
|
string
|
O tamanho das máquinas virtuais no pool. Todas as VMs em um pool têm o mesmo tamanho.
Para obter informações sobre os tamanhos disponíveis de máquinas virtuais para pools de Serviços de Nuvem (pools criados com cloudServiceConfiguration), consulte Tamanhos para Serviços de Nuvem (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). O Lote dá suporte a todos os tamanhos de VM Serviços de Nuvem, exceto ExtraSmall. Para obter informações sobre os tamanhos de VM disponíveis para pools usando imagens do Máquinas Virtuais Marketplace (pools criados com virtualMachineConfiguration), consulte Tamanhos para Máquinas Virtuais (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) ou Tamanhos para Máquinas Virtuais (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). O Lote dá suporte a todos os tamanhos de VM do Azure, exceto STANDARD_A0 e aqueles com armazenamento premium (STANDARD_GS, STANDARD_DS e séries STANDARD_DSV2).
|
Respostas
Nome |
Tipo |
Description |
200 OK
|
Pool
|
A operação foi bem-sucedida. A resposta contém a entidade do pool.
Headers
ETag: string
|
Other Status Codes
|
CloudError
|
Resposta de erro que descreve por que a operação falhou.
|
Segurança
azure_auth
Microsoft Entra fluxo de código de autenticação OAuth 2.0
Type:
oauth2
Flow:
implicit
Authorization URL:
https://login.microsoftonline.com/common/oauth2/authorize
Scopes
Nome |
Description |
user_impersonation
|
representar sua conta de usuário
|
Exemplos
CreatePool - accelerated networking
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D1_V2",
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"enableAcceleratedNetworking": true
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_accelerated_networking.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-datacenter-smalldisk",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.windows amd64",
}
},
"networkConfiguration": {
"enableAcceleratedNetworking": True,
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 1, "targetLowPriorityNodes": 0}},
"vmSize": "STANDARD_D1_V2",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.json
func ExamplePoolClient_Create_createPoolAcceleratedNetworking() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-datacenter-smalldisk"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
},
},
NetworkConfiguration: &armbatch.NetworkConfiguration{
EnableAcceleratedNetworking: to.Ptr(true),
SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](1),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
VMSize: to.Ptr("STANDARD_D1_V2"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB46CB72A227E2\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateSteady),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-04-27T03:00:34.064Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-04-27T02:59:41.859Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](1),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// CurrentNodeCommunicationMode: to.Ptr(armbatch.NodeCommunicationModeClassic),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-datacenter-smalldisk"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-04-27T02:59:41.859Z"); return t}()),
// NetworkConfiguration: &armbatch.NetworkConfiguration{
// DynamicVNetAssignmentScope: to.Ptr(armbatch.DynamicVNetAssignmentScopeNone),
// EnableAcceleratedNetworking: to.Ptr(true),
// SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
// },
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-04-27T02:59:41.859Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-04-27T02:59:41.859Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](1),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](1),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D1_V2"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.json
*/
async function createPoolAcceleratedNetworking() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-datacenter-smalldisk",
version: "latest",
},
nodeAgentSkuId: "batch.node.windows amd64",
},
},
networkConfiguration: {
enableAcceleratedNetworking: true,
subnetId:
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
scaleSettings: {
fixedScale: { targetDedicatedNodes: 1, targetLowPriorityNodes: 0 },
},
vmSize: "STANDARD_D1_V2",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D1_V2",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-datacenter-smalldisk",
Version = "latest",
}, "batch.node.windows amd64"),
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
FixedScale = new BatchAccountFixedScaleSettings()
{
TargetDedicatedNodes = 1,
TargetLowPriorityNodes = 0,
},
},
NetworkConfiguration = new BatchNetworkConfiguration()
{
SubnetId = new ResourceIdentifier("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
EnableAcceleratedNetworking = true,
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB46CB72A227E2"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB46CB72A227E2\"",
"properties": {
"lastModified": "2023-04-27T02:59:41.8592226Z",
"creationTime": "2023-04-27T02:59:41.8592226Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-04-27T02:59:41.8592226Z",
"allocationState": "Steady",
"allocationStateTransitionTime": "2023-04-27T03:00:34.0646502Z",
"vmSize": "STANDARD_D1_V2",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64"
}
},
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"dynamicVnetAssignmentScope": "none",
"enableAcceleratedNetworking": true
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 1,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-04-27T02:59:41.8592226Z"
},
"currentDedicatedNodes": 1,
"currentLowPriorityNodes": 0,
"currentNodeCommunicationMode": "Classic"
}
}
CreatePool - Custom Image
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_shared_image_gallery.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.json
func ExamplePoolClient_Create_createPoolCustomImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateSteady),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// TargetDedicatedNodes: to.Ptr[int32](0),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.json
*/
async function createPoolCustomImage() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
id: "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Id = new ResourceIdentifier("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
}, "batch.node.ubuntu 18.04"),
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Steady",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 0,
"targetLowPriorityNodes": 0
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - Full CloudServiceConfiguration
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"displayName": "my-pool-name",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Enabled",
"taskSlotsPerNode": 13,
"taskSchedulingPolicy": {
"nodeFillType": "Pack"
},
"deploymentConfiguration": {
"cloudServiceConfiguration": {
"osFamily": "4",
"osVersion": "WA-GUEST-OS-4.45_201708-01"
}
},
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "UserManaged",
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268"
]
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 6,
"targetLowPriorityNodes": 28,
"resizeTimeout": "PT8M",
"nodeDeallocationOption": "TaskCompletion"
}
},
"metadata": [
{
"name": "metadata-1",
"value": "value-1"
},
{
"name": "metadata-2",
"value": "value-2"
}
],
"startTask": {
"commandLine": "cmd /c SET",
"resourceFiles": [
{
"httpUrl": "https://testaccount.blob.core.windows.net/example-blob-file",
"filePath": "c:\\temp\\gohere",
"fileMode": "777"
}
],
"environmentSettings": [
{
"name": "MYSET",
"value": "1234"
}
],
"userIdentity": {
"autoUser": {
"scope": "Pool",
"elevationLevel": "Admin"
}
},
"maxTaskRetryCount": 6,
"waitForSuccess": true
},
"userAccounts": [
{
"name": "username1",
"password": "<ExamplePassword>",
"elevationLevel": "Admin",
"linuxUserConfiguration": {
"sshPrivateKey": "sshprivatekeyvalue",
"uid": 1234,
"gid": 4567
}
}
],
"applicationPackages": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234",
"version": "asdf"
}
],
"certificates": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567",
"storeLocation": "LocalMachine",
"storeName": "MY",
"visibility": [
"RemoteUser"
]
}
],
"applicationLicenses": [
"app-license0",
"app-license1"
]
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_cloud_service_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"applicationLicenses": ["app-license0", "app-license1"],
"applicationPackages": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234",
"version": "asdf",
}
],
"certificates": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567",
"storeLocation": "LocalMachine",
"storeName": "MY",
"visibility": ["RemoteUser"],
}
],
"deploymentConfiguration": {
"cloudServiceConfiguration": {"osFamily": "4", "osVersion": "WA-GUEST-OS-4.45_201708-01"}
},
"displayName": "my-pool-name",
"interNodeCommunication": "Enabled",
"metadata": [{"name": "metadata-1", "value": "value-1"}, {"name": "metadata-2", "value": "value-2"}],
"networkConfiguration": {
"publicIPAddressConfiguration": {
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268",
],
"provision": "UserManaged",
},
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
"scaleSettings": {
"fixedScale": {
"nodeDeallocationOption": "TaskCompletion",
"resizeTimeout": "PT8M",
"targetDedicatedNodes": 6,
"targetLowPriorityNodes": 28,
}
},
"startTask": {
"commandLine": "cmd /c SET",
"environmentSettings": [{"name": "MYSET", "value": "1234"}],
"maxTaskRetryCount": 6,
"resourceFiles": [
{
"fileMode": "777",
"filePath": "c:\\temp\\gohere",
"httpUrl": "https://testaccount.blob.core.windows.net/example-blob-file",
}
],
"userIdentity": {"autoUser": {"elevationLevel": "Admin", "scope": "Pool"}},
"waitForSuccess": True,
},
"taskSchedulingPolicy": {"nodeFillType": "Pack"},
"taskSlotsPerNode": 13,
"userAccounts": [
{
"elevationLevel": "Admin",
"linuxUserConfiguration": {"gid": 4567, "sshPrivateKey": "sshprivatekeyvalue", "uid": 1234},
"name": "username1",
"password": "<ExamplePassword>",
}
],
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_CloudServiceConfiguration.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_CloudServiceConfiguration.json
func ExamplePoolClient_Create_createPoolFullCloudServiceConfiguration() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
ApplicationLicenses: []*string{
to.Ptr("app-license0"),
to.Ptr("app-license1")},
ApplicationPackages: []*armbatch.ApplicationPackageReference{
{
ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234"),
Version: to.Ptr("asdf"),
}},
Certificates: []*armbatch.CertificateReference{
{
ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567"),
StoreLocation: to.Ptr(armbatch.CertificateStoreLocationLocalMachine),
StoreName: to.Ptr("MY"),
Visibility: []*armbatch.CertificateVisibility{
to.Ptr(armbatch.CertificateVisibilityRemoteUser)},
}},
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
CloudServiceConfiguration: &armbatch.CloudServiceConfiguration{
OSFamily: to.Ptr("4"),
OSVersion: to.Ptr("WA-GUEST-OS-4.45_201708-01"),
},
},
DisplayName: to.Ptr("my-pool-name"),
InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateEnabled),
Metadata: []*armbatch.MetadataItem{
{
Name: to.Ptr("metadata-1"),
Value: to.Ptr("value-1"),
},
{
Name: to.Ptr("metadata-2"),
Value: to.Ptr("value-2"),
}},
NetworkConfiguration: &armbatch.NetworkConfiguration{
PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
IPAddressIDs: []*string{
to.Ptr("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"),
to.Ptr("/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268")},
Provision: to.Ptr(armbatch.IPAddressProvisioningTypeUserManaged),
},
SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionTaskCompletion),
ResizeTimeout: to.Ptr("PT8M"),
TargetDedicatedNodes: to.Ptr[int32](6),
TargetLowPriorityNodes: to.Ptr[int32](28),
},
},
StartTask: &armbatch.StartTask{
CommandLine: to.Ptr("cmd /c SET"),
EnvironmentSettings: []*armbatch.EnvironmentSetting{
{
Name: to.Ptr("MYSET"),
Value: to.Ptr("1234"),
}},
MaxTaskRetryCount: to.Ptr[int32](6),
ResourceFiles: []*armbatch.ResourceFile{
{
FileMode: to.Ptr("777"),
FilePath: to.Ptr("c:\\temp\\gohere"),
HTTPURL: to.Ptr("https://testaccount.blob.core.windows.net/example-blob-file"),
}},
UserIdentity: &armbatch.UserIdentity{
AutoUser: &armbatch.AutoUserSpecification{
ElevationLevel: to.Ptr(armbatch.ElevationLevelAdmin),
Scope: to.Ptr(armbatch.AutoUserScopePool),
},
},
WaitForSuccess: to.Ptr(true),
},
TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypePack),
},
TaskSlotsPerNode: to.Ptr[int32](13),
UserAccounts: []*armbatch.UserAccount{
{
Name: to.Ptr("username1"),
ElevationLevel: to.Ptr(armbatch.ElevationLevelAdmin),
LinuxUserConfiguration: &armbatch.LinuxUserConfiguration{
Gid: to.Ptr[int32](4567),
SSHPrivateKey: to.Ptr("sshprivatekeyvalue"),
UID: to.Ptr[int32](1234),
},
Password: to.Ptr("<ExamplePassword>"),
}},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ApplicationLicenses: []*string{
// to.Ptr("app-license0"),
// to.Ptr("app-license1")},
// ApplicationPackages: []*armbatch.ApplicationPackageReference{
// {
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234"),
// Version: to.Ptr("asdf"),
// }},
// Certificates: []*armbatch.CertificateReference{
// {
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567"),
// StoreLocation: to.Ptr(armbatch.CertificateStoreLocationLocalMachine),
// StoreName: to.Ptr("MY"),
// Visibility: []*armbatch.CertificateVisibility{
// to.Ptr(armbatch.CertificateVisibilityRemoteUser)},
// }},
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// CloudServiceConfiguration: &armbatch.CloudServiceConfiguration{
// OSFamily: to.Ptr("4"),
// OSVersion: to.Ptr("WA-GUEST-OS-4.45_201708-01"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateEnabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// Metadata: []*armbatch.MetadataItem{
// {
// Name: to.Ptr("metadata-1"),
// Value: to.Ptr("value-1"),
// },
// {
// Name: to.Ptr("metadata-2"),
// Value: to.Ptr("value-2"),
// }},
// NetworkConfiguration: &armbatch.NetworkConfiguration{
// PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
// IPAddressIDs: []*string{
// to.Ptr("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"),
// to.Ptr("/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268")},
// Provision: to.Ptr(armbatch.IPAddressProvisioningTypeUserManaged),
// },
// SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
// },
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionTaskCompletion),
// ResizeTimeout: to.Ptr("PT8M"),
// TargetDedicatedNodes: to.Ptr[int32](6),
// TargetLowPriorityNodes: to.Ptr[int32](28),
// },
// },
// StartTask: &armbatch.StartTask{
// CommandLine: to.Ptr("cmd /c SET"),
// EnvironmentSettings: []*armbatch.EnvironmentSetting{
// {
// Name: to.Ptr("MYSET"),
// Value: to.Ptr("1234"),
// }},
// MaxTaskRetryCount: to.Ptr[int32](6),
// ResourceFiles: []*armbatch.ResourceFile{
// {
// FileMode: to.Ptr("777"),
// FilePath: to.Ptr("c:\\temp\\gohere"),
// HTTPURL: to.Ptr("https://testaccount.blob.core.windows.net/example-blob-file"),
// }},
// UserIdentity: &armbatch.UserIdentity{
// AutoUser: &armbatch.AutoUserSpecification{
// ElevationLevel: to.Ptr(armbatch.ElevationLevelAdmin),
// Scope: to.Ptr(armbatch.AutoUserScopePool),
// },
// },
// WaitForSuccess: to.Ptr(true),
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypePack),
// },
// TaskSlotsPerNode: to.Ptr[int32](13),
// UserAccounts: []*armbatch.UserAccount{
// {
// Name: to.Ptr("username1"),
// ElevationLevel: to.Ptr(armbatch.ElevationLevelAdmin),
// LinuxUserConfiguration: &armbatch.LinuxUserConfiguration{
// Gid: to.Ptr[int32](4567),
// UID: to.Ptr[int32](1234),
// },
// }},
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_CloudServiceConfiguration.json
*/
async function createPoolFullCloudServiceConfiguration() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
applicationLicenses: ["app-license0", "app-license1"],
applicationPackages: [
{
id: "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234",
version: "asdf",
},
],
certificates: [
{
id: "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567",
storeLocation: "LocalMachine",
storeName: "MY",
visibility: ["RemoteUser"],
},
],
deploymentConfiguration: {
cloudServiceConfiguration: {
osFamily: "4",
osVersion: "WA-GUEST-OS-4.45_201708-01",
},
},
displayName: "my-pool-name",
interNodeCommunication: "Enabled",
metadata: [
{ name: "metadata-1", value: "value-1" },
{ name: "metadata-2", value: "value-2" },
],
networkConfiguration: {
publicIPAddressConfiguration: {
ipAddressIds: [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268",
],
provision: "UserManaged",
},
subnetId:
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
scaleSettings: {
fixedScale: {
nodeDeallocationOption: "TaskCompletion",
resizeTimeout: "PT8M",
targetDedicatedNodes: 6,
targetLowPriorityNodes: 28,
},
},
startTask: {
commandLine: "cmd /c SET",
environmentSettings: [{ name: "MYSET", value: "1234" }],
maxTaskRetryCount: 6,
resourceFiles: [
{
fileMode: "777",
filePath: "c:\\temp\\gohere",
httpUrl: "https://testaccount.blob.core.windows.net/example-blob-file",
},
],
userIdentity: { autoUser: { elevationLevel: "Admin", scope: "Pool" } },
waitForSuccess: true,
},
taskSchedulingPolicy: { nodeFillType: "Pack" },
taskSlotsPerNode: 13,
userAccounts: [
{
name: "username1",
elevationLevel: "Admin",
linuxUserConfiguration: {
gid: 4567,
sshPrivateKey: "sshprivatekeyvalue",
uid: 1234,
},
password: "<ExamplePassword>",
},
],
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_CloudServiceConfiguration.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
DisplayName = "my-pool-name",
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
CloudServiceConfiguration = new BatchCloudServiceConfiguration("4")
{
OSVersion = "WA-GUEST-OS-4.45_201708-01",
},
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
FixedScale = new BatchAccountFixedScaleSettings()
{
ResizeTimeout = XmlConvert.ToTimeSpan("PT8M"),
TargetDedicatedNodes = 6,
TargetLowPriorityNodes = 28,
NodeDeallocationOption = BatchNodeDeallocationOption.TaskCompletion,
},
},
InterNodeCommunication = InterNodeCommunicationState.Enabled,
NetworkConfiguration = new BatchNetworkConfiguration()
{
SubnetId = new ResourceIdentifier("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
PublicIPAddressConfiguration = new BatchPublicIPAddressConfiguration()
{
Provision = BatchIPAddressProvisioningType.UserManaged,
IPAddressIds =
{
new ResourceIdentifier("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"),new ResourceIdentifier("/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268")
},
},
},
TaskSlotsPerNode = 13,
TaskSchedulingNodeFillType = BatchNodeFillType.Pack,
UserAccounts =
{
new BatchUserAccount("username1","<ExamplePassword>")
{
ElevationLevel = BatchUserAccountElevationLevel.Admin,
LinuxUserConfiguration = new BatchLinuxUserConfiguration()
{
Uid = 1234,
Gid = 4567,
SshPrivateKey = "sshprivatekeyvalue",
},
}
},
Metadata =
{
new BatchAccountPoolMetadataItem("metadata-1","value-1"),new BatchAccountPoolMetadataItem("metadata-2","value-2")
},
StartTask = new BatchAccountPoolStartTask()
{
CommandLine = "cmd /c SET",
ResourceFiles =
{
new BatchResourceFile()
{
HttpUri = new Uri("https://testaccount.blob.core.windows.net/example-blob-file"),
FilePath = "c:\\temp\\gohere",
FileMode = "777",
}
},
EnvironmentSettings =
{
new BatchEnvironmentSetting("MYSET")
{
Value = "1234",
}
},
UserIdentity = new BatchUserIdentity()
{
AutoUser = new BatchAutoUserSpecification()
{
Scope = BatchAutoUserScope.Pool,
ElevationLevel = BatchUserAccountElevationLevel.Admin,
},
},
MaxTaskRetryCount = 6,
WaitForSuccess = true,
},
Certificates =
{
new BatchCertificateReference(new ResourceIdentifier("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567"))
{
StoreLocation = BatchCertificateStoreLocation.LocalMachine,
StoreName = "MY",
Visibility =
{
BatchCertificateVisibility.RemoteUser
},
}
},
ApplicationPackages =
{
new BatchApplicationPackageReference(new ResourceIdentifier("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234"))
{
Version = "asdf",
}
},
ApplicationLicenses =
{
"app-license0","app-license1"
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Enabled",
"taskSlotsPerNode": 13,
"taskSchedulingPolicy": {
"nodeFillType": "Pack"
},
"deploymentConfiguration": {
"cloudServiceConfiguration": {
"osFamily": "4",
"osVersion": "WA-GUEST-OS-4.45_201708-01"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 6,
"targetLowPriorityNodes": 28,
"resizeTimeout": "PT8M",
"nodeDeallocationOption": "TaskCompletion"
}
},
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "UserManaged",
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268"
]
}
},
"metadata": [
{
"name": "metadata-1",
"value": "value-1"
},
{
"name": "metadata-2",
"value": "value-2"
}
],
"startTask": {
"commandLine": "cmd /c SET",
"resourceFiles": [
{
"httpUrl": "https://testaccount.blob.core.windows.net/example-blob-file",
"filePath": "c:\\temp\\gohere",
"fileMode": "777"
}
],
"environmentSettings": [
{
"name": "MYSET",
"value": "1234"
}
],
"userIdentity": {
"autoUser": {
"scope": "Pool",
"elevationLevel": "Admin"
}
},
"maxTaskRetryCount": 6,
"waitForSuccess": true
},
"userAccounts": [
{
"name": "username1",
"elevationLevel": "Admin",
"linuxUserConfiguration": {
"uid": 1234,
"gid": 4567
}
}
],
"applicationPackages": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234",
"version": "asdf"
}
],
"certificates": [
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567",
"storeLocation": "LocalMachine",
"storeName": "MY",
"visibility": [
"RemoteUser"
]
}
],
"applicationLicenses": [
"app-license0",
"app-license1"
],
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - Full VirtualMachineConfiguration
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-Datacenter-SmallDisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
},
"licenseType": "Windows_Server",
"dataDisks": [
{
"lun": 0,
"caching": "ReadWrite",
"diskSizeGB": 30,
"storageAccountType": "Premium_LRS"
},
{
"lun": 1,
"caching": "None",
"diskSizeGB": 200,
"storageAccountType": "Standard_LRS"
}
],
"diskEncryptionConfiguration": {
"targets": [
"OsDisk",
"TemporaryDisk"
]
},
"nodePlacementConfiguration": {
"policy": "Zonal"
},
"osDisk": {
"ephemeralOSDiskSettings": {
"placement": "CacheDisk"
}
}
}
},
"networkConfiguration": {
"endpointConfiguration": {
"inboundNatPools": [
{
"name": "testnat",
"protocol": "TCP",
"backendPort": 12001,
"frontendPortRangeStart": 15000,
"frontendPortRangeEnd": 15100,
"networkSecurityGroupRules": [
{
"access": "Allow",
"sourceAddressPrefix": "192.100.12.45",
"priority": 150,
"sourcePortRanges": [
"1",
"2"
]
},
{
"access": "Deny",
"sourceAddressPrefix": "*",
"priority": 3500,
"sourcePortRanges": [
"*"
]
}
]
}
]
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_virtual_machine_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"dataDisks": [
{"caching": "ReadWrite", "diskSizeGB": 30, "lun": 0, "storageAccountType": "Premium_LRS"},
{"caching": "None", "diskSizeGB": 200, "lun": 1, "storageAccountType": "Standard_LRS"},
],
"diskEncryptionConfiguration": {"targets": ["OsDisk", "TemporaryDisk"]},
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter-SmallDisk",
"version": "latest",
},
"licenseType": "Windows_Server",
"nodeAgentSkuId": "batch.node.windows amd64",
"nodePlacementConfiguration": {"policy": "Zonal"},
"osDisk": {"ephemeralOSDiskSettings": {"placement": "CacheDisk"}},
"windowsConfiguration": {"enableAutomaticUpdates": False},
}
},
"networkConfiguration": {
"endpointConfiguration": {
"inboundNatPools": [
{
"backendPort": 12001,
"frontendPortRangeEnd": 15100,
"frontendPortRangeStart": 15000,
"name": "testnat",
"networkSecurityGroupRules": [
{
"access": "Allow",
"priority": 150,
"sourceAddressPrefix": "192.100.12.45",
"sourcePortRanges": ["1", "2"],
},
{
"access": "Deny",
"priority": 3500,
"sourceAddressPrefix": "*",
"sourcePortRanges": ["*"],
},
],
"protocol": "TCP",
}
]
}
},
"scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration.json
func ExamplePoolClient_Create_createPoolFullVirtualMachineConfiguration() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
DataDisks: []*armbatch.DataDisk{
{
Caching: to.Ptr(armbatch.CachingTypeReadWrite),
DiskSizeGB: to.Ptr[int32](30),
Lun: to.Ptr[int32](0),
StorageAccountType: to.Ptr(armbatch.StorageAccountTypePremiumLRS),
},
{
Caching: to.Ptr(armbatch.CachingTypeNone),
DiskSizeGB: to.Ptr[int32](200),
Lun: to.Ptr[int32](1),
StorageAccountType: to.Ptr(armbatch.StorageAccountTypeStandardLRS),
}},
DiskEncryptionConfiguration: &armbatch.DiskEncryptionConfiguration{
Targets: []*armbatch.DiskEncryptionTarget{
to.Ptr(armbatch.DiskEncryptionTargetOsDisk),
to.Ptr(armbatch.DiskEncryptionTargetTemporaryDisk)},
},
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter-SmallDisk"),
Version: to.Ptr("latest"),
},
LicenseType: to.Ptr("Windows_Server"),
NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
NodePlacementConfiguration: &armbatch.NodePlacementConfiguration{
Policy: to.Ptr(armbatch.NodePlacementPolicyTypeZonal),
},
OSDisk: &armbatch.OSDisk{
EphemeralOSDiskSettings: &armbatch.DiffDiskSettings{
Placement: to.Ptr("CacheDisk"),
},
},
WindowsConfiguration: &armbatch.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(false),
},
},
},
NetworkConfiguration: &armbatch.NetworkConfiguration{
EndpointConfiguration: &armbatch.PoolEndpointConfiguration{
InboundNatPools: []*armbatch.InboundNatPool{
{
Name: to.Ptr("testnat"),
BackendPort: to.Ptr[int32](12001),
FrontendPortRangeEnd: to.Ptr[int32](15100),
FrontendPortRangeStart: to.Ptr[int32](15000),
NetworkSecurityGroupRules: []*armbatch.NetworkSecurityGroupRule{
{
Access: to.Ptr(armbatch.NetworkSecurityGroupRuleAccessAllow),
Priority: to.Ptr[int32](150),
SourceAddressPrefix: to.Ptr("192.100.12.45"),
SourcePortRanges: []*string{
to.Ptr("1"),
to.Ptr("2")},
},
{
Access: to.Ptr(armbatch.NetworkSecurityGroupRuleAccessDeny),
Priority: to.Ptr[int32](3500),
SourceAddressPrefix: to.Ptr("*"),
SourcePortRanges: []*string{
to.Ptr("*")},
}},
Protocol: to.Ptr(armbatch.InboundEndpointProtocolTCP),
}},
},
},
ScaleSettings: &armbatch.ScaleSettings{
AutoScale: &armbatch.AutoScaleSettings{
EvaluationInterval: to.Ptr("PT5M"),
Formula: to.Ptr("$TargetDedicatedNodes=1"),
},
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// DataDisks: []*armbatch.DataDisk{
// {
// Caching: to.Ptr(armbatch.CachingTypeReadWrite),
// DiskSizeGB: to.Ptr[int32](30),
// Lun: to.Ptr[int32](0),
// StorageAccountType: to.Ptr(armbatch.StorageAccountTypePremiumLRS),
// },
// {
// Caching: to.Ptr(armbatch.CachingTypeNone),
// DiskSizeGB: to.Ptr[int32](200),
// Lun: to.Ptr[int32](1),
// StorageAccountType: to.Ptr(armbatch.StorageAccountTypeStandardLRS),
// }},
// DiskEncryptionConfiguration: &armbatch.DiskEncryptionConfiguration{
// Targets: []*armbatch.DiskEncryptionTarget{
// to.Ptr(armbatch.DiskEncryptionTargetOsDisk),
// to.Ptr(armbatch.DiskEncryptionTargetTemporaryDisk)},
// },
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter-SmallDisk"),
// Version: to.Ptr("latest"),
// },
// LicenseType: to.Ptr("Windows_Server"),
// NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
// NodePlacementConfiguration: &armbatch.NodePlacementConfiguration{
// Policy: to.Ptr(armbatch.NodePlacementPolicyTypeZonal),
// },
// WindowsConfiguration: &armbatch.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(false),
// },
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// NetworkConfiguration: &armbatch.NetworkConfiguration{
// EndpointConfiguration: &armbatch.PoolEndpointConfiguration{
// InboundNatPools: []*armbatch.InboundNatPool{
// {
// Name: to.Ptr("testnat"),
// BackendPort: to.Ptr[int32](12001),
// FrontendPortRangeEnd: to.Ptr[int32](15100),
// FrontendPortRangeStart: to.Ptr[int32](15000),
// NetworkSecurityGroupRules: []*armbatch.NetworkSecurityGroupRule{
// {
// Access: to.Ptr(armbatch.NetworkSecurityGroupRuleAccessAllow),
// Priority: to.Ptr[int32](150),
// SourceAddressPrefix: to.Ptr("192.100.12.45"),
// SourcePortRanges: []*string{
// to.Ptr("1"),
// to.Ptr("2")},
// },
// {
// Access: to.Ptr(armbatch.NetworkSecurityGroupRuleAccessDeny),
// Priority: to.Ptr[int32](3500),
// SourceAddressPrefix: to.Ptr("*"),
// SourcePortRanges: []*string{
// to.Ptr("*")},
// }},
// Protocol: to.Ptr(armbatch.InboundEndpointProtocolTCP),
// }},
// },
// },
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// AutoScale: &armbatch.AutoScaleSettings{
// EvaluationInterval: to.Ptr("PT5M"),
// Formula: to.Ptr("$TargetDedicatedNodes=1"),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration.json
*/
async function createPoolFullVirtualMachineConfiguration() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
dataDisks: [
{
caching: "ReadWrite",
diskSizeGB: 30,
lun: 0,
storageAccountType: "Premium_LRS",
},
{
caching: "None",
diskSizeGB: 200,
lun: 1,
storageAccountType: "Standard_LRS",
},
],
diskEncryptionConfiguration: { targets: ["OsDisk", "TemporaryDisk"] },
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter-SmallDisk",
version: "latest",
},
licenseType: "Windows_Server",
nodeAgentSkuId: "batch.node.windows amd64",
nodePlacementConfiguration: { policy: "Zonal" },
osDisk: { ephemeralOSDiskSettings: { placement: "CacheDisk" } },
windowsConfiguration: { enableAutomaticUpdates: false },
},
},
networkConfiguration: {
endpointConfiguration: {
inboundNatPools: [
{
name: "testnat",
backendPort: 12001,
frontendPortRangeEnd: 15100,
frontendPortRangeStart: 15000,
networkSecurityGroupRules: [
{
access: "Allow",
priority: 150,
sourceAddressPrefix: "192.100.12.45",
sourcePortRanges: ["1", "2"],
},
{
access: "Deny",
priority: 3500,
sourceAddressPrefix: "*",
sourcePortRanges: ["*"],
},
],
protocol: "TCP",
},
],
},
},
scaleSettings: {
autoScale: {
evaluationInterval: "PT5M",
formula: "$TargetDedicatedNodes=1",
},
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter-SmallDisk",
Version = "latest",
}, "batch.node.windows amd64")
{
IsAutomaticUpdateEnabled = false,
DataDisks =
{
new BatchVmDataDisk(0,30)
{
Caching = BatchDiskCachingType.ReadWrite,
StorageAccountType = BatchStorageAccountType.PremiumLrs,
},new BatchVmDataDisk(1,200)
{
Caching = BatchDiskCachingType.None,
StorageAccountType = BatchStorageAccountType.StandardLrs,
}
},
LicenseType = "Windows_Server",
DiskEncryptionTargets =
{
BatchDiskEncryptionTarget.OSDisk,BatchDiskEncryptionTarget.TemporaryDisk
},
NodePlacementPolicy = BatchNodePlacementPolicyType.Zonal,
EphemeralOSDiskPlacement = BatchDiffDiskPlacement.CacheDisk,
},
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
AutoScale = new BatchAccountAutoScaleSettings("$TargetDedicatedNodes=1")
{
EvaluationInterval = XmlConvert.ToTimeSpan("PT5M"),
},
},
NetworkConfiguration = new BatchNetworkConfiguration()
{
EndpointInboundNatPools =
{
new BatchInboundNatPool("testnat",BatchInboundEndpointProtocol.Tcp,12001,15000,15100)
{
NetworkSecurityGroupRules =
{
new BatchNetworkSecurityGroupRule(150,BatchNetworkSecurityGroupRuleAccess.Allow,"192.100.12.45")
{
SourcePortRanges =
{
"1","2"
},
},new BatchNetworkSecurityGroupRule(3500,BatchNetworkSecurityGroupRuleAccess.Deny,"*")
{
SourcePortRanges =
{
"*"
},
}
},
}
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-Datacenter-SmallDisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
},
"licenseType": "Windows_Server",
"dataDisks": [
{
"lun": 0,
"caching": "ReadWrite",
"diskSizeGB": 30,
"storageAccountType": "Premium_LRS"
},
{
"lun": 1,
"caching": "None",
"diskSizeGB": 200,
"storageAccountType": "Standard_LRS"
}
],
"diskEncryptionConfiguration": {
"targets": [
"OsDisk",
"TemporaryDisk"
]
},
"nodePlacementConfiguration": {
"policy": "Zonal"
}
}
},
"networkConfiguration": {
"endpointConfiguration": {
"inboundNatPools": [
{
"name": "testnat",
"protocol": "TCP",
"backendPort": 12001,
"frontendPortRangeStart": 15000,
"frontendPortRangeEnd": 15100,
"networkSecurityGroupRules": [
{
"access": "Allow",
"sourceAddressPrefix": "192.100.12.45",
"priority": 150,
"sourcePortRanges": [
"1",
"2"
]
},
{
"access": "Deny",
"sourceAddressPrefix": "*",
"priority": 3500,
"sourcePortRanges": [
"*"
]
}
]
}
]
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - Minimal CloudServiceConfiguration
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"deploymentConfiguration": {
"cloudServiceConfiguration": {
"osFamily": "5"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 3
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_minimal_cloud_service_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {"cloudServiceConfiguration": {"osFamily": "5"}},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 3}},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalCloudServiceConfiguration.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalCloudServiceConfiguration.json
func ExamplePoolClient_Create_createPoolMinimalCloudServiceConfiguration() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
CloudServiceConfiguration: &armbatch.CloudServiceConfiguration{
OSFamily: to.Ptr("5"),
},
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](3),
},
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// CloudServiceConfiguration: &armbatch.CloudServiceConfiguration{
// OSFamily: to.Ptr("5"),
// OSVersion: to.Ptr("*"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](3),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](3),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalCloudServiceConfiguration.json
*/
async function createPoolMinimalCloudServiceConfiguration() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: { cloudServiceConfiguration: { osFamily: "5" } },
scaleSettings: { fixedScale: { targetDedicatedNodes: 3 } },
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalCloudServiceConfiguration.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
CloudServiceConfiguration = new BatchCloudServiceConfiguration("5"),
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
FixedScale = new BatchAccountFixedScaleSettings()
{
TargetDedicatedNodes = 3,
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"cloudServiceConfiguration": {
"osFamily": "5",
"osVersion": "*"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 3,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0,
"resizeOperationStatus": {
"startTime": "2017-08-28T10:22:55.9407275Z",
"targetDedicatedNodes": 3,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M"
}
}
}
CreatePool - Minimal VirtualMachineConfiguration
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18.04-LTS",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_minimal_virtual_machine_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "18.04-LTS",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalVirtualMachineConfiguration.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalVirtualMachineConfiguration.json
func ExamplePoolClient_Create_createPoolMinimalVirtualMachineConfiguration() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("18.04-LTS"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
ScaleSettings: &armbatch.ScaleSettings{
AutoScale: &armbatch.AutoScaleSettings{
EvaluationInterval: to.Ptr("PT5M"),
Formula: to.Ptr("$TargetDedicatedNodes=1"),
},
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("18.04-LTS"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// AutoScale: &armbatch.AutoScaleSettings{
// EvaluationInterval: to.Ptr("PT5M"),
// Formula: to.Ptr("$TargetDedicatedNodes=1"),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalVirtualMachineConfiguration.json
*/
async function createPoolMinimalVirtualMachineConfiguration() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "18.04-LTS",
version: "latest",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
scaleSettings: {
autoScale: {
evaluationInterval: "PT5M",
formula: "$TargetDedicatedNodes=1",
},
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_MinimalVirtualMachineConfiguration.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "18.04-LTS",
Version = "latest",
}, "batch.node.ubuntu 18.04"),
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
AutoScale = new BatchAccountAutoScaleSettings("$TargetDedicatedNodes=1")
{
EvaluationInterval = XmlConvert.ToTimeSpan("PT5M"),
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18.04-LTS",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - No public IP
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "NoPublicIPAddresses"
}
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_no_public_ip_addresses.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"networkConfiguration": {
"publicIPAddressConfiguration": {"provision": "NoPublicIPAddresses"},
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.json
func ExamplePoolClient_Create_createPoolNoPublicIp() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
NetworkConfiguration: &armbatch.NetworkConfiguration{
PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
Provision: to.Ptr(armbatch.IPAddressProvisioningTypeNoPublicIPAddresses),
},
SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateSteady),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// NetworkConfiguration: &armbatch.NetworkConfiguration{
// PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
// Provision: to.Ptr(armbatch.IPAddressProvisioningTypeNoPublicIPAddresses),
// },
// SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
// },
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// TargetDedicatedNodes: to.Ptr[int32](0),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.json
*/
async function createPoolNoPublicIP() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
id: "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
networkConfiguration: {
publicIPAddressConfiguration: { provision: "NoPublicIPAddresses" },
subnetId:
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Id = new ResourceIdentifier("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
}, "batch.node.ubuntu 18.04"),
},
NetworkConfiguration = new BatchNetworkConfiguration()
{
SubnetId = new ResourceIdentifier("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
PublicIPAddressConfiguration = new BatchPublicIPAddressConfiguration()
{
Provision = BatchIPAddressProvisioningType.NoPublicIPAddresses,
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Steady",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "NoPublicIPAddresses"
}
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 0,
"targetLowPriorityNodes": 0
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - Public IPs
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "UserManaged",
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"
]
}
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_public_ips.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"networkConfiguration": {
"publicIPAddressConfiguration": {
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"
],
"provision": "UserManaged",
},
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
func ExamplePoolClient_Create_createPoolPublicIPs() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
NetworkConfiguration: &armbatch.NetworkConfiguration{
PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
IPAddressIDs: []*string{
to.Ptr("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135")},
Provision: to.Ptr(armbatch.IPAddressProvisioningTypeUserManaged),
},
SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateSteady),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// ID: to.Ptr("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// NetworkConfiguration: &armbatch.NetworkConfiguration{
// PublicIPAddressConfiguration: &armbatch.PublicIPAddressConfiguration{
// IPAddressIDs: []*string{
// to.Ptr("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135")},
// Provision: to.Ptr(armbatch.IPAddressProvisioningTypeUserManaged),
// },
// SubnetID: to.Ptr("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
// },
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// TargetDedicatedNodes: to.Ptr[int32](0),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
*/
async function createPoolPublicIPs() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
id: "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
networkConfiguration: {
publicIPAddressConfiguration: {
ipAddressIds: [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
],
provision: "UserManaged",
},
subnetId:
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Id = new ResourceIdentifier("/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"),
}, "batch.node.ubuntu 18.04"),
},
NetworkConfiguration = new BatchNetworkConfiguration()
{
SubnetId = new ResourceIdentifier("/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123"),
PublicIPAddressConfiguration = new BatchPublicIPAddressConfiguration()
{
Provision = BatchIPAddressProvisioningType.UserManaged,
IPAddressIds =
{
new ResourceIdentifier("/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135")
},
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Steady",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"networkConfiguration": {
"subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123",
"publicIPAddressConfiguration": {
"provision": "UserManaged",
"ipAddressIds": [
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"
]
}
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 0,
"targetLowPriorityNodes": 0
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "Standard_d4s_v3",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18_04-lts-gen2",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"resourceTags": {
"TagName1": "TagValue1",
"TagName2": "TagValue2"
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_resource_tags.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "18_04-lts-gen2",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"resourceTags": {"TagName1": "TagValue1", "TagName2": "TagValue2"},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 1, "targetLowPriorityNodes": 0}},
"vmSize": "Standard_d4s_v3",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_ResourceTags.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_ResourceTags.json
func ExamplePoolClient_Create_createPoolResourceTags() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("18_04-lts-gen2"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
ResourceTags: map[string]*string{
"TagName1": to.Ptr("TagValue1"),
"TagName2": to.Ptr("TagValue2"),
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](1),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
VMSize: to.Ptr("Standard_d4s_v3"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB554F8E08BCF4\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("18_04-lts-gen2"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-09-27T07:33:13.062Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](1),
// },
// ResourceTags: map[string]*string{
// "TagName1": to.Ptr("TagValue1"),
// "TagName2": to.Ptr("TagValue2"),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](1),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4S_V3"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_ResourceTags.json
*/
async function createPoolResourceTags() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "18_04-lts-gen2",
version: "latest",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
resourceTags: { tagName1: "TagValue1", tagName2: "TagValue2" },
scaleSettings: {
fixedScale: { targetDedicatedNodes: 1, targetLowPriorityNodes: 0 },
},
vmSize: "Standard_d4s_v3",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB554F8E08BCF4"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB554F8E08BCF4\"",
"properties": {
"lastModified": "2023-06-14T07:03:58.3231917Z",
"creationTime": "2023-06-14T07:03:58.3231917Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-06-14T07:03:58.3231917Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2023-06-14T07:03:58.3231917Z",
"vmSize": "STANDARD_D4S_V3",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18_04-lts-gen2",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 1,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-09-27T07:33:13.0625789Z"
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0,
"resourceTags": {
"TagName1": "TagValue1",
"TagName2": "TagValue2"
}
}
}
CreatePool - SecurityProfile
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "Standard_d4s_v3",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18_04-lts-gen2",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
"securityProfile": {
"securityType": "trustedLaunch",
"encryptionAtHost": true,
"uefiSettings": {
"secureBootEnabled": null,
"vTpmEnabled": false
}
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_security_profile.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "18_04-lts-gen2",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
"securityProfile": {
"encryptionAtHost": True,
"securityType": "trustedLaunch",
"uefiSettings": {"secureBootEnabled": None, "vTpmEnabled": False},
},
}
},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 1, "targetLowPriorityNodes": 0}},
"vmSize": "Standard_d4s_v3",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SecurityProfile.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SecurityProfile.json
func ExamplePoolClient_Create_createPoolSecurityProfile() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("18_04-lts-gen2"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
SecurityProfile: &armbatch.SecurityProfile{
EncryptionAtHost: to.Ptr(true),
SecurityType: to.Ptr("trustedLaunch"),
UefiSettings: &armbatch.UefiSettings{
VTpmEnabled: to.Ptr(false),
},
},
},
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](1),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
VMSize: to.Ptr("Standard_d4s_v3"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB554F8E08BCF4\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("18_04-lts-gen2"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// SecurityProfile: &armbatch.SecurityProfile{
// EncryptionAtHost: to.Ptr(true),
// SecurityType: to.Ptr("trustedLaunch"),
// UefiSettings: &armbatch.UefiSettings{
// VTpmEnabled: to.Ptr(false),
// },
// },
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-14T07:03:58.323Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](1),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](1),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4S_V3"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SecurityProfile.json
*/
async function createPoolSecurityProfile() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "18_04-lts-gen2",
version: "latest",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
securityProfile: {
encryptionAtHost: true,
securityType: "trustedLaunch",
uefiSettings: { secureBootEnabled: undefined, vTpmEnabled: false },
},
},
},
scaleSettings: {
fixedScale: { targetDedicatedNodes: 1, targetLowPriorityNodes: 0 },
},
vmSize: "Standard_d4s_v3",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.batch.models.ApplicationPackageReference;
import com.azure.resourcemanager.batch.models.AutoScaleSettings;
import com.azure.resourcemanager.batch.models.AutoUserScope;
import com.azure.resourcemanager.batch.models.AutoUserSpecification;
import com.azure.resourcemanager.batch.models.AutomaticOSUpgradePolicy;
import com.azure.resourcemanager.batch.models.BatchPoolIdentity;
import com.azure.resourcemanager.batch.models.CachingType;
import com.azure.resourcemanager.batch.models.CertificateReference;
import com.azure.resourcemanager.batch.models.CertificateStoreLocation;
import com.azure.resourcemanager.batch.models.CertificateVisibility;
import com.azure.resourcemanager.batch.models.CloudServiceConfiguration;
import com.azure.resourcemanager.batch.models.ComputeNodeDeallocationOption;
import com.azure.resourcemanager.batch.models.ComputeNodeFillType;
import com.azure.resourcemanager.batch.models.DataDisk;
import com.azure.resourcemanager.batch.models.DeploymentConfiguration;
import com.azure.resourcemanager.batch.models.DiffDiskPlacement;
import com.azure.resourcemanager.batch.models.DiffDiskSettings;
import com.azure.resourcemanager.batch.models.DiskEncryptionConfiguration;
import com.azure.resourcemanager.batch.models.DiskEncryptionTarget;
import com.azure.resourcemanager.batch.models.ElevationLevel;
import com.azure.resourcemanager.batch.models.EnvironmentSetting;
import com.azure.resourcemanager.batch.models.FixedScaleSettings;
import com.azure.resourcemanager.batch.models.ImageReference;
import com.azure.resourcemanager.batch.models.InboundEndpointProtocol;
import com.azure.resourcemanager.batch.models.InboundNatPool;
import com.azure.resourcemanager.batch.models.InterNodeCommunicationState;
import com.azure.resourcemanager.batch.models.IpAddressProvisioningType;
import com.azure.resourcemanager.batch.models.LinuxUserConfiguration;
import com.azure.resourcemanager.batch.models.ManagedDisk;
import com.azure.resourcemanager.batch.models.MetadataItem;
import com.azure.resourcemanager.batch.models.NetworkConfiguration;
import com.azure.resourcemanager.batch.models.NetworkSecurityGroupRule;
import com.azure.resourcemanager.batch.models.NetworkSecurityGroupRuleAccess;
import com.azure.resourcemanager.batch.models.NodeCommunicationMode;
import com.azure.resourcemanager.batch.models.NodePlacementConfiguration;
import com.azure.resourcemanager.batch.models.NodePlacementPolicyType;
import com.azure.resourcemanager.batch.models.OSDisk;
import com.azure.resourcemanager.batch.models.PoolEndpointConfiguration;
import com.azure.resourcemanager.batch.models.PoolIdentityType;
import com.azure.resourcemanager.batch.models.PublicIpAddressConfiguration;
import com.azure.resourcemanager.batch.models.ResourceFile;
import com.azure.resourcemanager.batch.models.RollingUpgradePolicy;
import com.azure.resourcemanager.batch.models.ScaleSettings;
import com.azure.resourcemanager.batch.models.SecurityProfile;
import com.azure.resourcemanager.batch.models.SecurityTypes;
import com.azure.resourcemanager.batch.models.StartTask;
import com.azure.resourcemanager.batch.models.StorageAccountType;
import com.azure.resourcemanager.batch.models.TaskSchedulingPolicy;
import com.azure.resourcemanager.batch.models.UefiSettings;
import com.azure.resourcemanager.batch.models.UpgradeMode;
import com.azure.resourcemanager.batch.models.UpgradePolicy;
import com.azure.resourcemanager.batch.models.UserAccount;
import com.azure.resourcemanager.batch.models.UserAssignedIdentities;
import com.azure.resourcemanager.batch.models.UserIdentity;
import com.azure.resourcemanager.batch.models.VMExtension;
import com.azure.resourcemanager.batch.models.VirtualMachineConfiguration;
import com.azure.resourcemanager.batch.models.WindowsConfiguration;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for Pool Create.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SecurityProfile.json
*/
/**
* Sample code: CreatePool - SecurityProfile.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolSecurityProfile(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("18_04-lts-gen2").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")
.withSecurityProfile(new SecurityProfile().withSecurityType(SecurityTypes.TRUSTED_LAUNCH)
.withEncryptionAtHost(true).withUefiSettings(new UefiSettings().withVTpmEnabled(false)))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration_ManagedOSDisk.json
*/
/**
* Sample code: CreatePool - VirtualMachineConfiguration OSDisk.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolVirtualMachineConfigurationOSDisk(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d2s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("microsoftwindowsserver")
.withOffer("windowsserver").withSku("2022-datacenter-smalldisk"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withOsDisk(new OSDisk().withCaching(CachingType.READ_WRITE)
.withManagedDisk(new ManagedDisk().withStorageAccountType(StorageAccountType.STANDARD_SSD_LRS))
.withDiskSizeGB(100).withWriteAcceleratorEnabled(false))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_MinimalCloudServiceConfiguration.json
*/
/**
* Sample code: CreatePool - Minimal CloudServiceConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolMinimalCloudServiceConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration()
.withCloudServiceConfiguration(new CloudServiceConfiguration().withOsFamily("5")))
.withScaleSettings(new ScaleSettings().withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(3)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_MinimalVirtualMachineConfiguration.json
*/
/**
* Sample code: CreatePool - Minimal VirtualMachineConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolMinimalVirtualMachineConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(
new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration_Extensions.json
*/
/**
* Sample code: CreatePool - VirtualMachineConfiguration Extensions.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolVirtualMachineConfigurationExtensions(
com.azure.resourcemanager.batch.BatchManager manager) throws IOException {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("0001-com-ubuntu-server-focal").withSku("20_04-lts"))
.withNodeAgentSkuId("batch.node.ubuntu 20.04")
.withExtensions(Arrays.asList(new VMExtension().withName("batchextension1")
.withPublisher("Microsoft.Azure.KeyVault").withType("KeyVaultForLinux")
.withTypeHandlerVersion("2.0").withAutoUpgradeMinorVersion(true)
.withEnableAutomaticUpgrade(true)
.withSettings(SerializerFactory.createDefaultManagementSerializerAdapter().deserialize(
"{\"authenticationSettingsKey\":\"authenticationSettingsValue\",\"secretsManagementSettingsKey\":\"secretsManagementSettingsValue\"}",
Object.class, SerializerEncoding.JSON))))))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities
* .json
*/
/**
* Sample code: CreatePool - UserAssignedIdentities.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolUserAssignedIdentities(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withIdentity(new BatchPoolIdentity().withType(PoolIdentityType.USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1",
new UserAssignedIdentities(),
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2",
new UserAssignedIdentities())))
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(
new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UpgradePolicy.json
*/
/**
* Sample code: CreatePool - UpgradePolicy.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolUpgradePolicy(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-datacenter-smalldisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withWindowsConfiguration(new WindowsConfiguration().withEnableAutomaticUpdates(false))
.withNodePlacementConfiguration(
new NodePlacementConfiguration().withPolicy(NodePlacementPolicyType.ZONAL))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(2).withTargetLowPriorityNodes(0)))
.withUpgradePolicy(
new UpgradePolicy().withMode(UpgradeMode.AUTOMATIC)
.withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy().withDisableAutomaticRollback(true)
.withEnableAutomaticOSUpgrade(true).withUseRollingUpgradePolicy(true)
.withOsRollingUpgradeDeferral(true))
.withRollingUpgradePolicy(new RollingUpgradePolicy().withEnableCrossZoneUpgrade(true)
.withMaxBatchInstancePercent(20).withMaxUnhealthyInstancePercent(20)
.withMaxUnhealthyUpgradedInstancePercent(20).withPauseTimeBetweenBatches("PT0S")
.withPrioritizeUnhealthyInstances(false).withRollbackFailedInstancesOnPolicyBreach(false)))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.
* json
*/
/**
* Sample code: CreatePool - accelerated networking.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolAcceleratedNetworking(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D1_V2")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-datacenter-smalldisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withEnableAcceleratedNetworking(true))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration.json
*/
/**
* Sample code: CreatePool - Full VirtualMachineConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolFullVirtualMachineConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter-SmallDisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withWindowsConfiguration(new WindowsConfiguration().withEnableAutomaticUpdates(false))
.withDataDisks(Arrays.asList(
new DataDisk().withLun(0).withCaching(CachingType.READ_WRITE).withDiskSizeGB(30)
.withStorageAccountType(StorageAccountType.PREMIUM_LRS),
new DataDisk().withLun(1).withCaching(CachingType.NONE).withDiskSizeGB(200)
.withStorageAccountType(StorageAccountType.STANDARD_LRS)))
.withLicenseType("Windows_Server")
.withDiskEncryptionConfiguration(new DiskEncryptionConfiguration().withTargets(
Arrays.asList(DiskEncryptionTarget.OS_DISK, DiskEncryptionTarget.TEMPORARY_DISK)))
.withNodePlacementConfiguration(
new NodePlacementConfiguration().withPolicy(NodePlacementPolicyType.ZONAL))
.withOsDisk(new OSDisk().withEphemeralOSDiskSettings(
new DiffDiskSettings().withPlacement(DiffDiskPlacement.CACHE_DISK)))))
.withScaleSettings(
new ScaleSettings()
.withAutoScale(
new AutoScaleSettings().withFormula(
"$TargetDedicatedNodes=1").withEvaluationInterval(
Duration.parse("PT5M"))))
.withNetworkConfiguration(
new NetworkConfiguration()
.withEndpointConfiguration(new PoolEndpointConfiguration().withInboundNatPools(
Arrays.asList(new InboundNatPool().withName("testnat").withProtocol(InboundEndpointProtocol.TCP)
.withBackendPort(12001).withFrontendPortRangeStart(15000).withFrontendPortRangeEnd(15100)
.withNetworkSecurityGroupRules(Arrays.asList(new NetworkSecurityGroupRule()
.withPriority(150).withAccess(NetworkSecurityGroupRuleAccess.ALLOW)
.withSourceAddressPrefix("192.100.12.45").withSourcePortRanges(Arrays.asList("1", "2")),
new NetworkSecurityGroupRule().withPriority(3500)
.withAccess(NetworkSecurityGroupRuleAccess.DENY).withSourceAddressPrefix("*")
.withSourcePortRanges(Arrays.asList("*"))))))))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.
* json
*/
/**
* Sample code: CreatePool - Custom Image.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolCustomImage(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_CloudServiceConfiguration.json
*/
/**
* Sample code: CreatePool - Full CloudServiceConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolFullCloudServiceConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withDisplayName("my-pool-name").withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withCloudServiceConfiguration(
new CloudServiceConfiguration().withOsFamily("4").withOsVersion("WA-GUEST-OS-4.45_201708-01")))
.withScaleSettings(new ScaleSettings().withFixedScale(new FixedScaleSettings()
.withResizeTimeout(Duration.parse("PT8M")).withTargetDedicatedNodes(6).withTargetLowPriorityNodes(28)
.withNodeDeallocationOption(ComputeNodeDeallocationOption.TASK_COMPLETION)))
.withInterNodeCommunication(InterNodeCommunicationState.ENABLED)
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(new PublicIpAddressConfiguration()
.withProvision(IpAddressProvisioningType.USER_MANAGED)
.withIpAddressIds(Arrays.asList(
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268"))))
.withTaskSlotsPerNode(13)
.withTaskSchedulingPolicy(new TaskSchedulingPolicy().withNodeFillType(ComputeNodeFillType.PACK))
.withUserAccounts(Arrays.asList(new UserAccount().withName("username1").withPassword("fakeTokenPlaceholder")
.withElevationLevel(ElevationLevel.ADMIN)
.withLinuxUserConfiguration(new LinuxUserConfiguration().withUid(1234).withGid(4567)
.withSshPrivateKey("fakeTokenPlaceholder"))))
.withMetadata(Arrays.asList(new MetadataItem().withName("metadata-1").withValue("value-1"),
new MetadataItem().withName("metadata-2").withValue("value-2")))
.withStartTask(new StartTask().withCommandLine("cmd /c SET")
.withResourceFiles(Arrays.asList(
new ResourceFile().withHttpUrl("https://testaccount.blob.core.windows.net/example-blob-file")
.withFilePath("c:\\temp\\gohere").withFileMode("777")))
.withEnvironmentSettings(Arrays.asList(new EnvironmentSetting().withName("MYSET").withValue("1234")))
.withUserIdentity(new UserIdentity().withAutoUser(
new AutoUserSpecification().withScope(AutoUserScope.POOL).withElevationLevel(ElevationLevel.ADMIN)))
.withMaxTaskRetryCount(6).withWaitForSuccess(true))
.withCertificates(Arrays.asList(new CertificateReference().withId(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567")
.withStoreLocation(CertificateStoreLocation.LOCAL_MACHINE).withStoreName("MY")
.withVisibility(Arrays.asList(CertificateVisibility.REMOTE_USER))))
.withApplicationPackages(Arrays.asList(new ApplicationPackageReference().withId(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234")
.withVersion("asdf")))
.withApplicationLicenses(Arrays.asList("app-license0", "app-license1")).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.
* json
*/
/**
* Sample code: CreatePool - No public IP.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolNoPublicIP(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(
new PublicIpAddressConfiguration().withProvision(IpAddressProvisioningType.NO_PUBLIC_IPADDRESSES)))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_ResourceTags.json
*/
/**
* Sample code: CreatePool - ResourceTags.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolResourceTags(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("18_04-lts-gen2").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.withResourceTags(mapOf("TagName1", "TagValue1", "TagName2", "TagValue2")).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
*/
/**
* Sample code: CreatePool - Public IPs.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolPublicIPs(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(new PublicIpAddressConfiguration()
.withProvision(IpAddressProvisioningType.USER_MANAGED)
.withIpAddressIds(Arrays.asList(
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"))))
.create();
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB554F8E08BCF4"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB554F8E08BCF4\"",
"properties": {
"lastModified": "2023-06-14T07:03:58.3231917Z",
"creationTime": "2023-06-14T07:03:58.3231917Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-06-14T07:03:58.3231917Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2023-06-14T07:03:58.3231917Z",
"vmSize": "STANDARD_D4S_V3",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18_04-lts-gen2",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
"securityProfile": {
"securityType": "trustedLaunch",
"encryptionAtHost": true,
"uefiSettings": {
"vTpmEnabled": false
}
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 1,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-06-14T07:03:58.3231917Z"
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - UpgradePolicy
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "Standard_d4s_v3",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest"
},
"nodePlacementConfiguration": {
"policy": "Zonal"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 2,
"targetLowPriorityNodes": 0
}
},
"upgradePolicy": {
"mode": "automatic",
"automaticOSUpgradePolicy": {
"disableAutomaticRollback": true,
"enableAutomaticOSUpgrade": true,
"useRollingUpgradePolicy": true,
"osRollingUpgradeDeferral": true
},
"rollingUpgradePolicy": {
"enableCrossZoneUpgrade": true,
"maxBatchInstancePercent": 20,
"maxUnhealthyInstancePercent": 20,
"maxUnhealthyUpgradedInstancePercent": 20,
"pauseTimeBetweenBatches": "PT0S",
"prioritizeUnhealthyInstances": false,
"rollbackFailedInstancesOnPolicyBreach": false
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_upgrade_policy.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.windows amd64",
"nodePlacementConfiguration": {"policy": "Zonal"},
"windowsConfiguration": {"enableAutomaticUpdates": False},
}
},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 2, "targetLowPriorityNodes": 0}},
"upgradePolicy": {
"automaticOSUpgradePolicy": {
"disableAutomaticRollback": True,
"enableAutomaticOSUpgrade": True,
"osRollingUpgradeDeferral": True,
"useRollingUpgradePolicy": True,
},
"mode": "automatic",
"rollingUpgradePolicy": {
"enableCrossZoneUpgrade": True,
"maxBatchInstancePercent": 20,
"maxUnhealthyInstancePercent": 20,
"maxUnhealthyUpgradedInstancePercent": 20,
"pauseTimeBetweenBatches": "PT0S",
"prioritizeUnhealthyInstances": False,
"rollbackFailedInstancesOnPolicyBreach": False,
},
},
"vmSize": "Standard_d4s_v3",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UpgradePolicy.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UpgradePolicy.json
func ExamplePoolClient_Create_createPoolUpgradePolicy() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2019-datacenter-smalldisk"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
NodePlacementConfiguration: &armbatch.NodePlacementConfiguration{
Policy: to.Ptr(armbatch.NodePlacementPolicyTypeZonal),
},
WindowsConfiguration: &armbatch.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(false),
},
},
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](2),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
UpgradePolicy: &armbatch.UpgradePolicy{
AutomaticOSUpgradePolicy: &armbatch.AutomaticOSUpgradePolicy{
DisableAutomaticRollback: to.Ptr(true),
EnableAutomaticOSUpgrade: to.Ptr(true),
OSRollingUpgradeDeferral: to.Ptr(true),
UseRollingUpgradePolicy: to.Ptr(true),
},
Mode: to.Ptr(armbatch.UpgradeModeAutomatic),
RollingUpgradePolicy: &armbatch.RollingUpgradePolicy{
EnableCrossZoneUpgrade: to.Ptr(true),
MaxBatchInstancePercent: to.Ptr[int32](20),
MaxUnhealthyInstancePercent: to.Ptr[int32](20),
MaxUnhealthyUpgradedInstancePercent: to.Ptr[int32](20),
PauseTimeBetweenBatches: to.Ptr("PT0S"),
PrioritizeUnhealthyInstances: to.Ptr(false),
RollbackFailedInstancesOnPolicyBreach: to.Ptr(false),
},
},
VMSize: to.Ptr("Standard_d4s_v3"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB51E64D3C3B69\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T06:16:44.237Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T06:16:44.237Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2019-datacenter-smalldisk"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
// NodePlacementConfiguration: &armbatch.NodePlacementConfiguration{
// Policy: to.Ptr(armbatch.NodePlacementPolicyTypeZonal),
// },
// WindowsConfiguration: &armbatch.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(false),
// },
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T06:16:44.237Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T06:16:44.237Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T06:16:44.237Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](2),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](2),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// UpgradePolicy: &armbatch.UpgradePolicy{
// AutomaticOSUpgradePolicy: &armbatch.AutomaticOSUpgradePolicy{
// DisableAutomaticRollback: to.Ptr(true),
// EnableAutomaticOSUpgrade: to.Ptr(true),
// OSRollingUpgradeDeferral: to.Ptr(true),
// UseRollingUpgradePolicy: to.Ptr(true),
// },
// Mode: to.Ptr(armbatch.UpgradeModeAutomatic),
// RollingUpgradePolicy: &armbatch.RollingUpgradePolicy{
// EnableCrossZoneUpgrade: to.Ptr(true),
// MaxBatchInstancePercent: to.Ptr[int32](20),
// MaxUnhealthyInstancePercent: to.Ptr[int32](20),
// MaxUnhealthyUpgradedInstancePercent: to.Ptr[int32](20),
// PauseTimeBetweenBatches: to.Ptr("PT0S"),
// PrioritizeUnhealthyInstances: to.Ptr(false),
// RollbackFailedInstancesOnPolicyBreach: to.Ptr(false),
// },
// },
// VMSize: to.Ptr("STANDARD_D4S_V3"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UpgradePolicy.json
*/
async function createPoolUpgradePolicy() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2019-datacenter-smalldisk",
version: "latest",
},
nodeAgentSkuId: "batch.node.windows amd64",
nodePlacementConfiguration: { policy: "Zonal" },
windowsConfiguration: { enableAutomaticUpdates: false },
},
},
scaleSettings: {
fixedScale: { targetDedicatedNodes: 2, targetLowPriorityNodes: 0 },
},
upgradePolicy: {
automaticOSUpgradePolicy: {
disableAutomaticRollback: true,
enableAutomaticOSUpgrade: true,
osRollingUpgradeDeferral: true,
useRollingUpgradePolicy: true,
},
mode: "automatic",
rollingUpgradePolicy: {
enableCrossZoneUpgrade: true,
maxBatchInstancePercent: 20,
maxUnhealthyInstancePercent: 20,
maxUnhealthyUpgradedInstancePercent: 20,
pauseTimeBetweenBatches: "PT0S",
prioritizeUnhealthyInstances: false,
rollbackFailedInstancesOnPolicyBreach: false,
},
},
vmSize: "Standard_d4s_v3",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB51E64D3C3B69"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB51E64D3C3B69\"",
"properties": {
"lastModified": "2023-05-11T06:16:44.2372184Z",
"creationTime": "2023-05-11T06:16:44.2372184Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-05-11T06:16:44.2372184Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2023-05-11T06:16:44.2372184Z",
"vmSize": "STANDARD_D4S_V3",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
},
"nodePlacementConfiguration": {
"policy": "Zonal"
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 2,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 2,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-05-11T06:16:44.2372184Z"
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0,
"upgradePolicy": {
"mode": "automatic",
"automaticOSUpgradePolicy": {
"disableAutomaticRollback": true,
"enableAutomaticOSUpgrade": true,
"useRollingUpgradePolicy": true,
"osRollingUpgradeDeferral": true
},
"rollingUpgradePolicy": {
"enableCrossZoneUpgrade": true,
"maxBatchInstancePercent": 20,
"maxUnhealthyInstancePercent": 20,
"maxUnhealthyUpgradedInstancePercent": 20,
"pauseTimeBetweenBatches": "PT0S",
"prioritizeUnhealthyInstances": false,
"rollbackFailedInstancesOnPolicyBreach": false
}
}
}
}
CreatePool - UserAssignedIdentities
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18.04-LTS",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
}
},
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {},
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_user_assigned_identities.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {},
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {},
},
},
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "18.04-LTS",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04",
}
},
"scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}},
"vmSize": "STANDARD_D4",
},
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities.json
func ExamplePoolClient_Create_createPoolUserAssignedIdentities() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Identity: &armbatch.PoolIdentity{
Type: to.Ptr(armbatch.PoolIdentityTypeUserAssigned),
UserAssignedIdentities: map[string]*armbatch.UserAssignedIdentities{
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {},
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {},
},
},
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("18.04-LTS"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
},
},
ScaleSettings: &armbatch.ScaleSettings{
AutoScale: &armbatch.AutoScaleSettings{
EvaluationInterval: to.Ptr("PT5M"),
Formula: to.Ptr("$TargetDedicatedNodes=1"),
},
},
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Identity: &armbatch.PoolIdentity{
// Type: to.Ptr(armbatch.PoolIdentityTypeUserAssigned),
// UserAssignedIdentities: map[string]*armbatch.UserAssignedIdentities{
// "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armbatch.UserAssignedIdentities{
// ClientID: to.Ptr("clientId1"),
// PrincipalID: to.Ptr("principalId1"),
// },
// "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armbatch.UserAssignedIdentities{
// ClientID: to.Ptr("clientId2"),
// PrincipalID: to.Ptr("principalId2"),
// },
// },
// },
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-01T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-01T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("18.04-LTS"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 18.04"),
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-01T10:22:55.940Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-01T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// AutoScale: &armbatch.AutoScaleSettings{
// EvaluationInterval: to.Ptr("PT5M"),
// Formula: to.Ptr("$TargetDedicatedNodes=1"),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities.json
*/
async function createPoolUserAssignedIdentities() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "18.04-LTS",
version: "latest",
},
nodeAgentSkuId: "batch.node.ubuntu 18.04",
},
},
identity: {
type: "UserAssigned",
userAssignedIdentities: {
"/subscriptions/subid/resourceGroups/defaultAzurebatchJapaneast/providers/MicrosoftManagedIdentity/userAssignedIdentities/id1":
{},
"/subscriptions/subid/resourceGroups/defaultAzurebatchJapaneast/providers/MicrosoftManagedIdentity/userAssignedIdentities/id2":
{},
},
},
scaleSettings: {
autoScale: {
evaluationInterval: "PT5M",
formula: "$TargetDedicatedNodes=1",
},
},
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
Identity = new ManagedServiceIdentity("UserAssigned")
{
UserAssignedIdentities =
{
[new ResourceIdentifier("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1")] = new UserAssignedIdentity(),
[new ResourceIdentifier("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2")] = new UserAssignedIdentity(),
},
},
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "18.04-LTS",
Version = "latest",
}, "batch.node.ubuntu 18.04"),
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
AutoScale = new BatchAccountAutoScaleSettings("$TargetDedicatedNodes=1")
{
EvaluationInterval = XmlConvert.ToTimeSpan("PT5M"),
},
},
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2020-10-01T10:22:55.9407275Z",
"creationTime": "2020-10-01T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2020-10-01T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2020-10-01T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18.04-LTS",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.ubuntu 18.04"
}
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
},
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {
"principalId": "principalId1",
"clientId": "clientId1"
},
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {
"principalId": "principalId2",
"clientId": "clientId2"
}
}
}
}
CreatePool - VirtualMachineConfiguration Extensions
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "STANDARD_D4",
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "0001-com-ubuntu-server-focal",
"sku": "20_04-lts"
},
"nodeAgentSkuId": "batch.node.ubuntu 20.04",
"extensions": [
{
"name": "batchextension1",
"type": "KeyVaultForLinux",
"publisher": "Microsoft.Azure.KeyVault",
"typeHandlerVersion": "2.0",
"autoUpgradeMinorVersion": true,
"enableAutomaticUpgrade": true,
"settings": {
"secretsManagementSettingsKey": "secretsManagementSettingsValue",
"authenticationSettingsKey": "authenticationSettingsValue"
}
}
]
}
},
"targetNodeCommunicationMode": "Default"
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_virtual_machine_configuration_extensions.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"extensions": [
{
"autoUpgradeMinorVersion": True,
"enableAutomaticUpgrade": True,
"name": "batchextension1",
"publisher": "Microsoft.Azure.KeyVault",
"settings": {
"authenticationSettingsKey": "authenticationSettingsValue",
"secretsManagementSettingsKey": "secretsManagementSettingsValue",
},
"type": "KeyVaultForLinux",
"typeHandlerVersion": "2.0",
}
],
"imageReference": {
"offer": "0001-com-ubuntu-server-focal",
"publisher": "Canonical",
"sku": "20_04-lts",
},
"nodeAgentSkuId": "batch.node.ubuntu 20.04",
}
},
"scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}},
"targetNodeCommunicationMode": "Default",
"vmSize": "STANDARD_D4",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_Extensions.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_Extensions.json
func ExamplePoolClient_Create_createPoolVirtualMachineConfigurationExtensions() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("0001-com-ubuntu-server-focal"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("20_04-lts"),
},
NodeAgentSKUID: to.Ptr("batch.node.ubuntu 20.04"),
Extensions: []*armbatch.VMExtension{
{
Name: to.Ptr("batchextension1"),
Type: to.Ptr("KeyVaultForLinux"),
AutoUpgradeMinorVersion: to.Ptr(true),
EnableAutomaticUpgrade: to.Ptr(true),
Publisher: to.Ptr("Microsoft.Azure.KeyVault"),
Settings: map[string]any{
"authenticationSettingsKey": "authenticationSettingsValue",
"secretsManagementSettingsKey": "secretsManagementSettingsValue",
},
TypeHandlerVersion: to.Ptr("2.0"),
}},
},
},
ScaleSettings: &armbatch.ScaleSettings{
AutoScale: &armbatch.AutoScaleSettings{
EvaluationInterval: to.Ptr("PT5M"),
Formula: to.Ptr("$TargetDedicatedNodes=1"),
},
},
TargetNodeCommunicationMode: to.Ptr(armbatch.NodeCommunicationModeDefault),
VMSize: to.Ptr("STANDARD_D4"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8D4EDFEBFADF4AB\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("0001-com-ubuntu-server-focal"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("20_04-lts"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.ubuntu 20.04"),
// Extensions: []*armbatch.VMExtension{
// {
// Name: to.Ptr("batchextension1"),
// Type: to.Ptr("KeyVaultForLinux"),
// AutoUpgradeMinorVersion: to.Ptr(true),
// EnableAutomaticUpgrade: to.Ptr(true),
// Publisher: to.Ptr("Microsoft.Azure.KeyVault"),
// Settings: map[string]any{
// "authenticationSettingsKey": "authenticationSettingsValue",
// "secretsManagementSettingsKey": "secretsManagementSettingsValue",
// },
// TypeHandlerVersion: to.Ptr("2.0"),
// }},
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-08-28T10:22:55.940Z"); return t}()),
// ScaleSettings: &armbatch.ScaleSettings{
// AutoScale: &armbatch.AutoScaleSettings{
// EvaluationInterval: to.Ptr("PT5M"),
// Formula: to.Ptr("$TargetDedicatedNodes=1"),
// },
// },
// TargetNodeCommunicationMode: to.Ptr(armbatch.NodeCommunicationModeDefault),
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D4"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_Extensions.json
*/
async function createPoolVirtualMachineConfigurationExtensions() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "0001-com-ubuntu-server-focal",
publisher: "Canonical",
sku: "20_04-lts",
},
nodeAgentSkuId: "batch.node.ubuntu 20.04",
extensions: [
{
name: "batchextension1",
type: "KeyVaultForLinux",
autoUpgradeMinorVersion: true,
enableAutomaticUpgrade: true,
publisher: "Microsoft.Azure.KeyVault",
settings: {
authenticationSettingsKey: "authenticationSettingsValue",
secretsManagementSettingsKey: "secretsManagementSettingsValue",
},
typeHandlerVersion: "2.0",
},
],
},
},
scaleSettings: {
autoScale: {
evaluationInterval: "PT5M",
formula: "$TargetDedicatedNodes=1",
},
},
targetNodeCommunicationMode: "Default",
vmSize: "STANDARD_D4",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Batch.Models;
using Azure.ResourceManager.Models;
// Generated from example definition: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_Extensions.json
// this example is just showing the usage of "Pool_Create" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this BatchAccountResource created on azure
// for more information of creating BatchAccountResource, please refer to the document of BatchAccountResource
string subscriptionId = "subid";
string resourceGroupName = "default-azurebatch-japaneast";
string accountName = "sampleacct";
ResourceIdentifier batchAccountResourceId = BatchAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
BatchAccountResource batchAccount = client.GetBatchAccountResource(batchAccountResourceId);
// get the collection of this BatchAccountPoolResource
BatchAccountPoolCollection collection = batchAccount.GetBatchAccountPools();
// invoke the operation
string poolName = "testpool";
BatchAccountPoolData data = new BatchAccountPoolData()
{
VmSize = "STANDARD_D4",
DeploymentConfiguration = new BatchDeploymentConfiguration()
{
VmConfiguration = new BatchVmConfiguration(new BatchImageReference()
{
Publisher = "Canonical",
Offer = "0001-com-ubuntu-server-focal",
Sku = "20_04-lts",
}, "batch.node.ubuntu 20.04")
{
Extensions =
{
new BatchVmExtension("batchextension1","Microsoft.Azure.KeyVault","KeyVaultForLinux")
{
TypeHandlerVersion = "2.0",
AutoUpgradeMinorVersion = true,
EnableAutomaticUpgrade = true,
Settings = BinaryData.FromObjectAsJson(new Dictionary<string, object>()
{
["authenticationSettingsKey"] = "authenticationSettingsValue",
["secretsManagementSettingsKey"] = "secretsManagementSettingsValue"}),
}
},
},
},
ScaleSettings = new BatchAccountPoolScaleSettings()
{
AutoScale = new BatchAccountAutoScaleSettings("$TargetDedicatedNodes=1")
{
EvaluationInterval = XmlConvert.ToTimeSpan("PT5M"),
},
},
TargetNodeCommunicationMode = NodeCommunicationMode.Default,
};
ArmOperation<BatchAccountPoolResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, poolName, data);
BatchAccountPoolResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
BatchAccountPoolData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8D4EDFEBFADF4AB"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8D4EDFEBFADF4AB\"",
"properties": {
"lastModified": "2017-08-28T10:22:55.9407275Z",
"creationTime": "2017-08-28T10:22:55.9407275Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2017-08-28T10:22:55.9407275Z",
"vmSize": "STANDARD_D4",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"scaleSettings": {
"autoScale": {
"formula": "$TargetDedicatedNodes=1",
"evaluationInterval": "PT5M"
}
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0,
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "Canonical",
"offer": "0001-com-ubuntu-server-focal",
"sku": "20_04-lts"
},
"nodeAgentSkuId": "batch.node.ubuntu 20.04",
"extensions": [
{
"name": "batchextension1",
"type": "KeyVaultForLinux",
"publisher": "Microsoft.Azure.KeyVault",
"typeHandlerVersion": "2.0",
"autoUpgradeMinorVersion": true,
"enableAutomaticUpgrade": true,
"settings": {
"secretsManagementSettingsKey": "secretsManagementSettingsValue",
"authenticationSettingsKey": "authenticationSettingsValue"
}
}
]
}
},
"targetNodeCommunicationMode": "Default"
}
}
CreatePool - VirtualMachineConfiguration OSDisk
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "Standard_d2s_v3",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "microsoftwindowsserver",
"offer": "windowsserver",
"sku": "2022-datacenter-smalldisk"
},
"osDisk": {
"diskSizeGB": 100,
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"caching": "ReadWrite",
"writeAcceleratorEnabled": false
},
"nodeAgentSkuId": "batch.node.windows amd64"
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_virtual_machine_configuration_managed_os_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "windowsserver",
"publisher": "microsoftwindowsserver",
"sku": "2022-datacenter-smalldisk",
},
"nodeAgentSkuId": "batch.node.windows amd64",
"osDisk": {
"caching": "ReadWrite",
"diskSizeGB": 100,
"managedDisk": {"storageAccountType": "StandardSSD_LRS"},
"writeAcceleratorEnabled": False,
},
}
},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 1, "targetLowPriorityNodes": 0}},
"vmSize": "Standard_d2s_v3",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ManagedOSDisk.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ManagedOSDisk.json
func ExamplePoolClient_Create_createPoolVirtualMachineConfigurationOsDisk() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("windowsserver"),
Publisher: to.Ptr("microsoftwindowsserver"),
SKU: to.Ptr("2022-datacenter-smalldisk"),
},
NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
OSDisk: &armbatch.OSDisk{
Caching: to.Ptr(armbatch.CachingTypeReadWrite),
DiskSizeGB: to.Ptr[int32](100),
ManagedDisk: &armbatch.ManagedDisk{
StorageAccountType: to.Ptr(armbatch.StorageAccountTypeStandardSSDLRS),
},
WriteAcceleratorEnabled: to.Ptr(false),
},
},
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](1),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
VMSize: to.Ptr("Standard_d2s_v3"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("testpool"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB51F396992B8D\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-08-24T02:12:27.752Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-08-24T02:12:27.752Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("windowsserver"),
// Publisher: to.Ptr("microsoftwindowsserver"),
// SKU: to.Ptr("2022-datacenter-smalldisk"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
// OSDisk: &armbatch.OSDisk{
// Caching: to.Ptr(armbatch.CachingTypeReadWrite),
// DiskSizeGB: to.Ptr[int32](100),
// ManagedDisk: &armbatch.ManagedDisk{
// StorageAccountType: to.Ptr(armbatch.StorageAccountTypeStandardSSDLRS),
// },
// WriteAcceleratorEnabled: to.Ptr(false),
// },
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-08-24T02:12:27.752Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-08-24T02:12:27.752Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-08-24T02:12:27.752Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](1),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](1),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// VMSize: to.Ptr("STANDARD_D2_V3"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ManagedOSDisk.json
*/
async function createPoolVirtualMachineConfigurationOSDisk() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "windowsserver",
publisher: "microsoftwindowsserver",
sku: "2022-datacenter-smalldisk",
},
nodeAgentSkuId: "batch.node.windows amd64",
osDisk: {
caching: "ReadWrite",
diskSizeGB: 100,
managedDisk: { storageAccountType: "StandardSSD_LRS" },
writeAcceleratorEnabled: false,
},
},
},
scaleSettings: {
fixedScale: { targetDedicatedNodes: 1, targetLowPriorityNodes: 0 },
},
vmSize: "Standard_d2s_v3",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB51F14DC1A8AD"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "testpool",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB51F396992B8D\"",
"properties": {
"lastModified": "2023-08-24T02:12:27.7527697Z",
"creationTime": "2023-08-24T02:12:27.7527697Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-08-24T02:12:27.7527697Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2023-08-24T02:12:27.7527697Z",
"vmSize": "STANDARD_D2_V3",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "microsoftwindowsserver",
"offer": "windowsserver",
"sku": "2022-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"diskSizeGB": 100,
"writeAcceleratorEnabled": false
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 1,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 1,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-08-24T02:12:27.7527697Z"
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0
}
}
CreatePool - VirtualMachineConfiguration ServiceArtifactReference
Sample Request
PUT https://management.azure.com/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool?api-version=2024-02-01
{
"properties": {
"vmSize": "Standard_d4s_v3",
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
},
"serviceArtifactReference": {
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 2,
"targetLowPriorityNodes": 0
}
},
"upgradePolicy": {
"mode": "automatic",
"automaticOSUpgradePolicy": {
"enableAutomaticOSUpgrade": true
}
}
}
}
from azure.identity import DefaultAzureCredential
from azure.mgmt.batch import BatchManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-batch
# USAGE
python pool_create_virtual_machine_configuration_service_artifact_reference.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = BatchManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.pool.create(
resource_group_name="default-azurebatch-japaneast",
account_name="sampleacct",
pool_name="testpool",
parameters={
"properties": {
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest",
},
"nodeAgentSkuId": "batch.node.windows amd64",
"serviceArtifactReference": {
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"
},
"windowsConfiguration": {"enableAutomaticUpdates": False},
}
},
"scaleSettings": {"fixedScale": {"targetDedicatedNodes": 2, "targetLowPriorityNodes": 0}},
"upgradePolicy": {"automaticOSUpgradePolicy": {"enableAutomaticOSUpgrade": True}, "mode": "automatic"},
"vmSize": "Standard_d4s_v3",
}
},
)
print(response)
# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ServiceArtifactReference.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armbatch_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/batch/armbatch/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/cf5ad1932d00c7d15497705ad6b71171d3d68b1e/specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ServiceArtifactReference.json
func ExamplePoolClient_Create_createPoolVirtualMachineConfigurationServiceArtifactReference() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armbatch.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := clientFactory.NewPoolClient().Create(ctx, "default-azurebatch-japaneast", "sampleacct", "testpool", armbatch.Pool{
Properties: &armbatch.PoolProperties{
DeploymentConfiguration: &armbatch.DeploymentConfiguration{
VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
ImageReference: &armbatch.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2019-datacenter-smalldisk"),
Version: to.Ptr("latest"),
},
NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
ServiceArtifactReference: &armbatch.ServiceArtifactReference{
ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"),
},
WindowsConfiguration: &armbatch.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(false),
},
},
},
ScaleSettings: &armbatch.ScaleSettings{
FixedScale: &armbatch.FixedScaleSettings{
TargetDedicatedNodes: to.Ptr[int32](2),
TargetLowPriorityNodes: to.Ptr[int32](0),
},
},
UpgradePolicy: &armbatch.UpgradePolicy{
AutomaticOSUpgradePolicy: &armbatch.AutomaticOSUpgradePolicy{
EnableAutomaticOSUpgrade: to.Ptr(true),
},
Mode: to.Ptr(armbatch.UpgradeModeAutomatic),
},
VMSize: to.Ptr("Standard_d4s_v3"),
},
}, &armbatch.PoolClientCreateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.Pool = armbatch.Pool{
// Name: to.Ptr("mypool41"),
// Type: to.Ptr("Microsoft.Batch/batchAccounts/pools"),
// Etag: to.Ptr("W/\"0x8DB51F396992B8D\""),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool"),
// Properties: &armbatch.PoolProperties{
// AllocationState: to.Ptr(armbatch.AllocationStateResizing),
// AllocationStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T07:44:44.858Z"); return t}()),
// CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T07:44:44.858Z"); return t}()),
// CurrentDedicatedNodes: to.Ptr[int32](0),
// CurrentLowPriorityNodes: to.Ptr[int32](0),
// DeploymentConfiguration: &armbatch.DeploymentConfiguration{
// VirtualMachineConfiguration: &armbatch.VirtualMachineConfiguration{
// ImageReference: &armbatch.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2019-datacenter-smalldisk"),
// Version: to.Ptr("latest"),
// },
// NodeAgentSKUID: to.Ptr("batch.node.windows amd64"),
// ServiceArtifactReference: &armbatch.ServiceArtifactReference{
// ID: to.Ptr("/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"),
// },
// WindowsConfiguration: &armbatch.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(false),
// },
// },
// },
// InterNodeCommunication: to.Ptr(armbatch.InterNodeCommunicationStateDisabled),
// LastModified: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T07:44:44.858Z"); return t}()),
// ProvisioningState: to.Ptr(armbatch.PoolProvisioningStateSucceeded),
// ProvisioningStateTransitionTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T07:44:44.858Z"); return t}()),
// ResizeOperationStatus: &armbatch.ResizeOperationStatus{
// NodeDeallocationOption: to.Ptr(armbatch.ComputeNodeDeallocationOptionRequeue),
// ResizeTimeout: to.Ptr("PT15M"),
// StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-11T07:44:44.858Z"); return t}()),
// TargetDedicatedNodes: to.Ptr[int32](2),
// },
// ScaleSettings: &armbatch.ScaleSettings{
// FixedScale: &armbatch.FixedScaleSettings{
// ResizeTimeout: to.Ptr("PT15M"),
// TargetDedicatedNodes: to.Ptr[int32](2),
// TargetLowPriorityNodes: to.Ptr[int32](0),
// },
// },
// TaskSchedulingPolicy: &armbatch.TaskSchedulingPolicy{
// NodeFillType: to.Ptr(armbatch.ComputeNodeFillTypeSpread),
// },
// TaskSlotsPerNode: to.Ptr[int32](1),
// UpgradePolicy: &armbatch.UpgradePolicy{
// AutomaticOSUpgradePolicy: &armbatch.AutomaticOSUpgradePolicy{
// EnableAutomaticOSUpgrade: to.Ptr(true),
// },
// Mode: to.Ptr(armbatch.UpgradeModeAutomatic),
// },
// VMSize: to.Ptr("STANDARD_D4S_V3"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { BatchManagementClient } = require("@azure/arm-batch");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Creates a new pool inside the specified account.
*
* @summary Creates a new pool inside the specified account.
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_VirtualMachineConfiguration_ServiceArtifactReference.json
*/
async function createPoolVirtualMachineConfigurationServiceArtifactReference() {
const subscriptionId = process.env["BATCH_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["BATCH_RESOURCE_GROUP"] || "default-azurebatch-japaneast";
const accountName = "sampleacct";
const poolName = "testpool";
const parameters = {
deploymentConfiguration: {
virtualMachineConfiguration: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2019-datacenter-smalldisk",
version: "latest",
},
nodeAgentSkuId: "batch.node.windows amd64",
serviceArtifactReference: {
id: "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile",
},
windowsConfiguration: { enableAutomaticUpdates: false },
},
},
scaleSettings: {
fixedScale: { targetDedicatedNodes: 2, targetLowPriorityNodes: 0 },
},
upgradePolicy: {
automaticOSUpgradePolicy: { enableAutomaticOSUpgrade: true },
mode: "automatic",
},
vmSize: "Standard_d4s_v3",
};
const credential = new DefaultAzureCredential();
const client = new BatchManagementClient(credential, subscriptionId);
const result = await client.poolOperations.create(
resourceGroupName,
accountName,
poolName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.batch.models.ApplicationPackageReference;
import com.azure.resourcemanager.batch.models.AutoScaleSettings;
import com.azure.resourcemanager.batch.models.AutoUserScope;
import com.azure.resourcemanager.batch.models.AutoUserSpecification;
import com.azure.resourcemanager.batch.models.AutomaticOSUpgradePolicy;
import com.azure.resourcemanager.batch.models.BatchPoolIdentity;
import com.azure.resourcemanager.batch.models.CachingType;
import com.azure.resourcemanager.batch.models.CertificateReference;
import com.azure.resourcemanager.batch.models.CertificateStoreLocation;
import com.azure.resourcemanager.batch.models.CertificateVisibility;
import com.azure.resourcemanager.batch.models.CloudServiceConfiguration;
import com.azure.resourcemanager.batch.models.ComputeNodeDeallocationOption;
import com.azure.resourcemanager.batch.models.ComputeNodeFillType;
import com.azure.resourcemanager.batch.models.DataDisk;
import com.azure.resourcemanager.batch.models.DeploymentConfiguration;
import com.azure.resourcemanager.batch.models.DiffDiskPlacement;
import com.azure.resourcemanager.batch.models.DiffDiskSettings;
import com.azure.resourcemanager.batch.models.DiskEncryptionConfiguration;
import com.azure.resourcemanager.batch.models.DiskEncryptionTarget;
import com.azure.resourcemanager.batch.models.ElevationLevel;
import com.azure.resourcemanager.batch.models.EnvironmentSetting;
import com.azure.resourcemanager.batch.models.FixedScaleSettings;
import com.azure.resourcemanager.batch.models.ImageReference;
import com.azure.resourcemanager.batch.models.InboundEndpointProtocol;
import com.azure.resourcemanager.batch.models.InboundNatPool;
import com.azure.resourcemanager.batch.models.InterNodeCommunicationState;
import com.azure.resourcemanager.batch.models.IpAddressProvisioningType;
import com.azure.resourcemanager.batch.models.LinuxUserConfiguration;
import com.azure.resourcemanager.batch.models.ManagedDisk;
import com.azure.resourcemanager.batch.models.MetadataItem;
import com.azure.resourcemanager.batch.models.NetworkConfiguration;
import com.azure.resourcemanager.batch.models.NetworkSecurityGroupRule;
import com.azure.resourcemanager.batch.models.NetworkSecurityGroupRuleAccess;
import com.azure.resourcemanager.batch.models.NodeCommunicationMode;
import com.azure.resourcemanager.batch.models.NodePlacementConfiguration;
import com.azure.resourcemanager.batch.models.NodePlacementPolicyType;
import com.azure.resourcemanager.batch.models.OSDisk;
import com.azure.resourcemanager.batch.models.PoolEndpointConfiguration;
import com.azure.resourcemanager.batch.models.PoolIdentityType;
import com.azure.resourcemanager.batch.models.PublicIpAddressConfiguration;
import com.azure.resourcemanager.batch.models.ResourceFile;
import com.azure.resourcemanager.batch.models.RollingUpgradePolicy;
import com.azure.resourcemanager.batch.models.ScaleSettings;
import com.azure.resourcemanager.batch.models.ServiceArtifactReference;
import com.azure.resourcemanager.batch.models.StartTask;
import com.azure.resourcemanager.batch.models.StorageAccountType;
import com.azure.resourcemanager.batch.models.TaskSchedulingPolicy;
import com.azure.resourcemanager.batch.models.UpgradeMode;
import com.azure.resourcemanager.batch.models.UpgradePolicy;
import com.azure.resourcemanager.batch.models.UserAccount;
import com.azure.resourcemanager.batch.models.UserAssignedIdentities;
import com.azure.resourcemanager.batch.models.UserIdentity;
import com.azure.resourcemanager.batch.models.VMExtension;
import com.azure.resourcemanager.batch.models.VirtualMachineConfiguration;
import com.azure.resourcemanager.batch.models.WindowsConfiguration;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for Pool Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration_ServiceArtifactReference.json
*/
/**
* Sample code: CreatePool - VirtualMachineConfiguration ServiceArtifactReference.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolVirtualMachineConfigurationServiceArtifactReference(
com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-datacenter-smalldisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withWindowsConfiguration(new WindowsConfiguration().withEnableAutomaticUpdates(false))
.withServiceArtifactReference(new ServiceArtifactReference().withId(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(2).withTargetLowPriorityNodes(0)))
.withUpgradePolicy(new UpgradePolicy().withMode(UpgradeMode.AUTOMATIC)
.withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy().withEnableAutomaticOSUpgrade(true)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration_ManagedOSDisk.json
*/
/**
* Sample code: CreatePool - VirtualMachineConfiguration OSDisk.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolVirtualMachineConfigurationOSDisk(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d2s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("microsoftwindowsserver")
.withOffer("windowsserver").withSku("2022-datacenter-smalldisk"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withOsDisk(new OSDisk().withCaching(CachingType.READ_WRITE)
.withManagedDisk(new ManagedDisk().withStorageAccountType(StorageAccountType.STANDARD_SSD_LRS))
.withDiskSizeGB(100).withWriteAcceleratorEnabled(false))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_MinimalCloudServiceConfiguration.json
*/
/**
* Sample code: CreatePool - Minimal CloudServiceConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolMinimalCloudServiceConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration()
.withCloudServiceConfiguration(new CloudServiceConfiguration().withOsFamily("5")))
.withScaleSettings(new ScaleSettings().withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(3)))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_MinimalVirtualMachineConfiguration.json
*/
/**
* Sample code: CreatePool - Minimal VirtualMachineConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void
createPoolMinimalVirtualMachineConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(
new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration_Extensions.json
*/
/**
* Sample code: CreatePool - VirtualMachineConfiguration Extensions.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolVirtualMachineConfigurationExtensions(
com.azure.resourcemanager.batch.BatchManager manager) throws IOException {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("0001-com-ubuntu-server-focal").withSku("20_04-lts"))
.withNodeAgentSkuId("batch.node.ubuntu 20.04")
.withExtensions(Arrays.asList(new VMExtension().withName("batchextension1")
.withPublisher("Microsoft.Azure.KeyVault").withType("KeyVaultForLinux")
.withTypeHandlerVersion("2.0").withAutoUpgradeMinorVersion(true)
.withEnableAutomaticUpgrade(true)
.withSettings(SerializerFactory.createDefaultManagementSerializerAdapter().deserialize(
"{\"authenticationSettingsKey\":\"authenticationSettingsValue\",\"secretsManagementSettingsKey\":\"secretsManagementSettingsValue\"}",
Object.class, SerializerEncoding.JSON))))))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UserAssignedIdentities
* .json
*/
/**
* Sample code: CreatePool - UserAssignedIdentities.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolUserAssignedIdentities(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withIdentity(new BatchPoolIdentity().withType(PoolIdentityType.USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1",
new UserAssignedIdentities(),
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2",
new UserAssignedIdentities())))
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(
new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical")
.withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings().withAutoScale(new AutoScaleSettings()
.withFormula("$TargetDedicatedNodes=1").withEvaluationInterval(Duration.parse("PT5M"))))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_UpgradePolicy.json
*/
/**
* Sample code: CreatePool - UpgradePolicy.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolUpgradePolicy(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-datacenter-smalldisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withWindowsConfiguration(new WindowsConfiguration().withEnableAutomaticUpdates(false))
.withNodePlacementConfiguration(
new NodePlacementConfiguration().withPolicy(NodePlacementPolicyType.ZONAL))))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(2).withTargetLowPriorityNodes(0)))
.withUpgradePolicy(
new UpgradePolicy().withMode(UpgradeMode.AUTOMATIC)
.withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy().withDisableAutomaticRollback(true)
.withEnableAutomaticOSUpgrade(true).withUseRollingUpgradePolicy(true)
.withOsRollingUpgradeDeferral(true))
.withRollingUpgradePolicy(new RollingUpgradePolicy().withEnableCrossZoneUpgrade(true)
.withMaxBatchInstancePercent(20).withMaxUnhealthyInstancePercent(20)
.withMaxUnhealthyUpgradedInstancePercent(20).withPauseTimeBetweenBatches("PT0S")
.withPrioritizeUnhealthyInstances(false).withRollbackFailedInstancesOnPolicyBreach(false)))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_AcceleratedNetworking.
* json
*/
/**
* Sample code: CreatePool - accelerated networking.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolAcceleratedNetworking(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D1_V2")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-datacenter-smalldisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withEnableAcceleratedNetworking(true))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_VirtualMachineConfiguration.json
*/
/**
* Sample code: CreatePool - Full VirtualMachineConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolFullVirtualMachineConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(
new DeploymentConfiguration()
.withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter-SmallDisk").withVersion("latest"))
.withNodeAgentSkuId("batch.node.windows amd64")
.withWindowsConfiguration(new WindowsConfiguration().withEnableAutomaticUpdates(false))
.withDataDisks(Arrays.asList(
new DataDisk().withLun(0).withCaching(CachingType.READ_WRITE).withDiskSizeGB(30)
.withStorageAccountType(StorageAccountType.PREMIUM_LRS),
new DataDisk().withLun(1).withCaching(CachingType.NONE).withDiskSizeGB(200)
.withStorageAccountType(StorageAccountType.STANDARD_LRS)))
.withLicenseType("Windows_Server")
.withDiskEncryptionConfiguration(new DiskEncryptionConfiguration().withTargets(
Arrays.asList(DiskEncryptionTarget.OS_DISK, DiskEncryptionTarget.TEMPORARY_DISK)))
.withNodePlacementConfiguration(
new NodePlacementConfiguration().withPolicy(NodePlacementPolicyType.ZONAL))
.withOsDisk(new OSDisk().withEphemeralOSDiskSettings(
new DiffDiskSettings().withPlacement(DiffDiskPlacement.CACHE_DISK)))))
.withScaleSettings(
new ScaleSettings()
.withAutoScale(
new AutoScaleSettings().withFormula(
"$TargetDedicatedNodes=1").withEvaluationInterval(
Duration.parse("PT5M"))))
.withNetworkConfiguration(
new NetworkConfiguration()
.withEndpointConfiguration(new PoolEndpointConfiguration().withInboundNatPools(
Arrays.asList(new InboundNatPool().withName("testnat").withProtocol(InboundEndpointProtocol.TCP)
.withBackendPort(12001).withFrontendPortRangeStart(15000).withFrontendPortRangeEnd(15100)
.withNetworkSecurityGroupRules(Arrays.asList(new NetworkSecurityGroupRule()
.withPriority(150).withAccess(NetworkSecurityGroupRuleAccess.ALLOW)
.withSourceAddressPrefix("192.100.12.45").withSourcePortRanges(Arrays.asList("1", "2")),
new NetworkSecurityGroupRule().withPriority(3500)
.withAccess(NetworkSecurityGroupRuleAccess.DENY).withSourceAddressPrefix("*")
.withSourcePortRanges(Arrays.asList("*"))))))))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_SharedImageGallery.
* json
*/
/**
* Sample code: CreatePool - Custom Image.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolCustomImage(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.create();
}
/*
* x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/
* PoolCreate_CloudServiceConfiguration.json
*/
/**
* Sample code: CreatePool - Full CloudServiceConfiguration.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolFullCloudServiceConfiguration(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withDisplayName("my-pool-name").withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withCloudServiceConfiguration(
new CloudServiceConfiguration().withOsFamily("4").withOsVersion("WA-GUEST-OS-4.45_201708-01")))
.withScaleSettings(new ScaleSettings().withFixedScale(new FixedScaleSettings()
.withResizeTimeout(Duration.parse("PT8M")).withTargetDedicatedNodes(6).withTargetLowPriorityNodes(28)
.withNodeDeallocationOption(ComputeNodeDeallocationOption.TASK_COMPLETION)))
.withInterNodeCommunication(InterNodeCommunicationState.ENABLED)
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(new PublicIpAddressConfiguration()
.withProvision(IpAddressProvisioningType.USER_MANAGED)
.withIpAddressIds(Arrays.asList(
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135",
"/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268"))))
.withTaskSlotsPerNode(13)
.withTaskSchedulingPolicy(new TaskSchedulingPolicy().withNodeFillType(ComputeNodeFillType.PACK))
.withUserAccounts(Arrays.asList(new UserAccount().withName("username1").withPassword("fakeTokenPlaceholder")
.withElevationLevel(ElevationLevel.ADMIN)
.withLinuxUserConfiguration(new LinuxUserConfiguration().withUid(1234).withGid(4567)
.withSshPrivateKey("fakeTokenPlaceholder"))))
.withMetadata(Arrays.asList(new MetadataItem().withName("metadata-1").withValue("value-1"),
new MetadataItem().withName("metadata-2").withValue("value-2")))
.withStartTask(new StartTask().withCommandLine("cmd /c SET")
.withResourceFiles(Arrays.asList(
new ResourceFile().withHttpUrl("https://testaccount.blob.core.windows.net/example-blob-file")
.withFilePath("c:\\temp\\gohere").withFileMode("777")))
.withEnvironmentSettings(Arrays.asList(new EnvironmentSetting().withName("MYSET").withValue("1234")))
.withUserIdentity(new UserIdentity().withAutoUser(
new AutoUserSpecification().withScope(AutoUserScope.POOL).withElevationLevel(ElevationLevel.ADMIN)))
.withMaxTaskRetryCount(6).withWaitForSuccess(true))
.withCertificates(Arrays.asList(new CertificateReference().withId(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567")
.withStoreLocation(CertificateStoreLocation.LOCAL_MACHINE).withStoreName("MY")
.withVisibility(Arrays.asList(CertificateVisibility.REMOTE_USER))))
.withApplicationPackages(Arrays.asList(new ApplicationPackageReference().withId(
"/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234")
.withVersion("asdf")))
.withApplicationLicenses(Arrays.asList("app-license0", "app-license1")).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_NoPublicIPAddresses.
* json
*/
/**
* Sample code: CreatePool - No public IP.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolNoPublicIP(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(
new PublicIpAddressConfiguration().withProvision(IpAddressProvisioningType.NO_PUBLIC_IPADDRESSES)))
.create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_ResourceTags.json
*/
/**
* Sample code: CreatePool - ResourceTags.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolResourceTags(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("Standard_d4s_v3")
.withDeploymentConfiguration(
new DeploymentConfiguration().withVirtualMachineConfiguration(new VirtualMachineConfiguration()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("18_04-lts-gen2").withVersion("latest"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withScaleSettings(new ScaleSettings()
.withFixedScale(new FixedScaleSettings().withTargetDedicatedNodes(1).withTargetLowPriorityNodes(0)))
.withResourceTags(mapOf("TagName1", "TagValue1", "TagName2", "TagValue2")).create();
}
/*
* x-ms-original-file:
* specification/batch/resource-manager/Microsoft.Batch/stable/2024-02-01/examples/PoolCreate_PublicIPs.json
*/
/**
* Sample code: CreatePool - Public IPs.
*
* @param manager Entry point to BatchManager.
*/
public static void createPoolPublicIPs(com.azure.resourcemanager.batch.BatchManager manager) {
manager.pools().define("testpool").withExistingBatchAccount("default-azurebatch-japaneast", "sampleacct")
.withVmSize("STANDARD_D4")
.withDeploymentConfiguration(new DeploymentConfiguration().withVirtualMachineConfiguration(
new VirtualMachineConfiguration().withImageReference(new ImageReference().withId(
"/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1"))
.withNodeAgentSkuId("batch.node.ubuntu 18.04")))
.withNetworkConfiguration(new NetworkConfiguration().withSubnetId(
"/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123")
.withPublicIpAddressConfiguration(new PublicIpAddressConfiguration()
.withProvision(IpAddressProvisioningType.USER_MANAGED)
.withIpAddressIds(Arrays.asList(
"/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135"))))
.create();
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
ETag: W/"0x8DB51F14DC1A8AD"
{
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool",
"name": "mypool41",
"type": "Microsoft.Batch/batchAccounts/pools",
"etag": "W/\"0x8DB51F396992B8D\"",
"properties": {
"lastModified": "2023-05-11T07:44:44.8580493Z",
"creationTime": "2023-05-11T07:44:44.8580493Z",
"provisioningState": "Succeeded",
"provisioningStateTransitionTime": "2023-05-11T07:44:44.8580493Z",
"allocationState": "Resizing",
"allocationStateTransitionTime": "2023-05-11T07:44:44.8580493Z",
"vmSize": "STANDARD_D4S_V3",
"interNodeCommunication": "Disabled",
"taskSlotsPerNode": 1,
"taskSchedulingPolicy": {
"nodeFillType": "Spread"
},
"deploymentConfiguration": {
"virtualMachineConfiguration": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-datacenter-smalldisk",
"version": "latest"
},
"nodeAgentSkuId": "batch.node.windows amd64",
"windowsConfiguration": {
"enableAutomaticUpdates": false
},
"serviceArtifactReference": {
"id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Compute/galleries/myGallery/serviceArtifacts/myServiceArtifact/vmArtifactsProfiles/vmArtifactsProfile"
}
}
},
"scaleSettings": {
"fixedScale": {
"targetDedicatedNodes": 2,
"targetLowPriorityNodes": 0,
"resizeTimeout": "PT15M"
}
},
"resizeOperationStatus": {
"targetDedicatedNodes": 2,
"nodeDeallocationOption": "Requeue",
"resizeTimeout": "PT15M",
"startTime": "2023-05-11T07:44:44.8580493Z"
},
"currentDedicatedNodes": 0,
"currentLowPriorityNodes": 0,
"upgradePolicy": {
"mode": "automatic",
"automaticOSUpgradePolicy": {
"enableAutomaticOSUpgrade": true
}
}
}
}
Definições
Nome |
Description |
AllocationState
|
Se o pool está redimensionando.
|
ApplicationPackageReference
|
Vincular a um pacote de aplicativos dentro da conta do lote
|
AutomaticOSUpgradePolicy
|
Os parâmetros de configuração usados para executar a atualização automática do sistema operacional.
|
AutoScaleRun
|
Os resultados e erros de uma execução de uma fórmula de dimensionamento automático do pool.
|
AutoScaleRunError
|
Um erro que ocorreu ao dimensionar automaticamente um pool.
|
AutoScaleSettings
|
Configurações de Dimensionamento Automático para o pool.
|
AutoUserScope
|
O escopo do usuário automático
|
AutoUserSpecification
|
Especifica os parâmetros para o usuário automático que executa uma tarefa no serviço do Lote.
|
AzureBlobFileSystemConfiguration
|
Informações usadas para se conectar a um Contêiner de Armazenamento do Azure usando o Blobfuse.
|
AzureFileShareConfiguration
|
Informações usadas para se conectar a um compartilhamento de arquivos do Azure.
|
BatchPoolIdentity
|
A identidade do pool do Lote, se configurada. Se a identidade do pool for atualizada durante a atualização de um pool existente, somente as novas VMs criadas após a redução do pool para 0 terão as identidades atualizadas
|
CachingType
|
O tipo de cache a ser habilitado para o disco.
|
CertificateReference
|
Uma referência a um certificado a ser instalado em nós de computação em um pool. Isso deve existir dentro da mesma conta que o pool.
|
CertificateStoreLocation
|
O local do repositório de certificados no nó de computação no qual instalar o certificado.
|
CertificateVisibility
|
Quais contas de usuário no nó de computação devem ter acesso aos dados privados do certificado.
|
CIFSMountConfiguration
|
Informações usadas para se conectar a um sistema de arquivos CIFS.
|
CloudError
|
Uma resposta de erro do serviço do Lote.
|
CloudErrorBody
|
Uma resposta de erro do serviço do Lote.
|
CloudServiceConfiguration
|
A configuração para nós em um pool com base na plataforma Serviços de Nuvem do Azure.
|
ComputeNodeDeallocationOption
|
Determina o que fazer com um nó e suas tarefas em execução depois de ter sido selecionado para desalocação.
|
ComputeNodeFillType
|
Como as tarefas devem ser distribuídas entre nós de computação.
|
ComputeNodeIdentityReference
|
A referência a uma identidade atribuída pelo usuário associada ao pool do Lote que um nó de computação usará.
|
ContainerConfiguration
|
A configuração para pools habilitados para contêineres.
|
ContainerRegistry
|
Um registro de contêiner privado.
|
ContainerType
|
A tecnologia de contêiner a ser usada.
|
ContainerWorkingDirectory
|
Um sinalizador para indicar onde está o diretório de trabalho da tarefa de contêiner. O padrão é 'taskWorkingDirectory'.
|
DataDisk
|
Configurações que serão usadas pelos discos de dados associados aos Nós de Computação no Pool. Ao usar discos de dados anexados, você precisa montar e formatar os discos de dentro de uma VM para usá-los.
|
DeploymentConfiguration
|
Propriedades de configuração de implantação.
|
DiffDiskPlacement
|
Especifica o posicionamento de disco efêmero para o disco do sistema operacional para todas as VMs no pool.
|
DiffDiskSettings
|
Especifica as Configurações de Disco efêmero para o disco do sistema operacional usado pela máquina virtual.
|
DiskEncryptionConfiguration
|
A configuração de criptografia de disco aplicada em nós de computação no pool. Não há suporte para a configuração de criptografia de disco no pool do Linux criado com a Imagem da Máquina Virtual ou a Imagem da Galeria de Computação do Azure.
|
DiskEncryptionTarget
|
A lista de destinos de disco Serviço em Lote será criptografada no nó de computação
|
DynamicVNetAssignmentScope
|
O escopo da atribuição de vnet dinâmica.
|
ElevationLevel
|
O nível de elevação do usuário.
|
EnvironmentSetting
|
Uma variável de ambiente a ser definida em um processo de tarefa.
|
FixedScaleSettings
|
Correção das configurações de escala para o pool.
|
ImageReference
|
Uma referência a uma imagem do Azure Máquinas Virtuais Marketplace ou ao recurso imagem do Azure de uma Máquina Virtual personalizada. Para obter a lista de todas as imageReferences verificadas por Lote do Azure, consulte a operação 'Listar SKUs do agente de nó com suporte'.
|
InboundEndpointProtocol
|
O protocolo do ponto de extremidade.
|
InboundNatPool
|
Um pool NAT de entrada que pode ser usado para abordar portas específicas em nós de computação em um pool do Lote externamente.
|
InterNodeCommunicationState
|
Se o pool permite comunicação direta entre nós.
|
IPAddressProvisioningType
|
O tipo de provisionamento para endereços IP públicos para o Pool de Lotes.
|
LinuxUserConfiguration
|
Propriedades usadas para criar uma conta de usuário em um nó do Linux.
|
LoginMode
|
Modo de logon para usuário
|
ManagedDisk
|
|
MetadataItem
|
Um par nome-valor associado a um recurso de serviço do Lote.
|
MountConfiguration
|
O sistema de arquivos a ser montado em cada nó.
|
NetworkConfiguration
|
A configuração de rede de um pool.
|
NetworkSecurityGroupRule
|
Uma regra de grupo de segurança de rede a ser aplicada a um ponto de extremidade de entrada.
|
NetworkSecurityGroupRuleAccess
|
A ação que deve ser executada para um endereço IP especificado, intervalo de sub-rede ou marca.
|
NFSMountConfiguration
|
Informações usadas para se conectar a um sistema de arquivos NFS.
|
NodeCommunicationMode
|
Determina como um pool se comunica com o serviço do Lote.
|
NodePlacementConfiguration
|
Configuração de posicionamento de nó para pools de lote.
|
NodePlacementPolicyType
|
A política de posicionamento para alocar nós no pool.
|
OSDisk
|
Configurações para o disco do sistema operacional da máquina virtual.
|
Pool
|
Contém informações sobre um pool.
|
PoolEndpointConfiguration
|
A configuração do ponto de extremidade para um pool.
|
PoolIdentityType
|
O tipo de identidade usado para o Pool do Lote.
|
PoolProvisioningState
|
O estado atual do pool.
|
PublicIPAddressConfiguration
|
A configuração de endereço IP público da configuração de rede de um Pool.
|
ResizeError
|
Um erro que ocorreu ao redimensionar um pool.
|
ResizeOperationStatus
|
Detalhes sobre a operação de redimensionamento atual ou última concluída.
|
ResourceFile
|
Um único arquivo ou vários arquivos a serem baixados em um nó de computação.
|
RollingUpgradePolicy
|
Os parâmetros de configuração usados durante a execução de uma atualização sem interrupção.
|
ScaleSettings
|
Configurações de escala para o pool
|
SecurityProfile
|
Especifica as configurações de perfil de segurança para a máquina virtual ou o conjunto de dimensionamento de máquinas virtuais.
|
SecurityTypes
|
Especifica o SecurityType da máquina virtual. Ele precisa ser definido como qualquer valor especificado para habilitar UefiSettings.
|
ServiceArtifactReference
|
Especifica a ID de referência do artefato de serviço usada para definir a mesma versão de imagem para todas as máquinas virtuais no conjunto de dimensionamento ao usar a versão de imagem 'mais recente'.
|
StartTask
|
Uma tarefa que é executada quando um nó de computação ingressa em um pool no serviço Lote do Azure ou quando o nó de computação é reinicializado ou recriado.
|
StorageAccountType
|
O tipo de conta de armazenamento para uso na criação de discos de dados ou disco do sistema operacional.
|
TaskContainerSettings
|
As configurações de contêiner para uma tarefa.
|
TaskSchedulingPolicy
|
Especifica como as tarefas devem ser distribuídas entre nós de computação.
|
UefiSettings
|
Especifica as configurações de segurança, como inicialização segura e vTPM usadas durante a criação da máquina virtual.
|
UpgradeMode
|
Especifica o modo de uma atualização para máquinas virtuais no conjunto de dimensionamento.
Os valores possíveis são:
Manual – você controla a aplicação de atualizações para máquinas virtuais no conjunto de dimensionamento. Faça isso usando a ação manualUpgrade.
Automático – todas as máquinas virtuais no conjunto de dimensionamento são atualizadas automaticamente ao mesmo tempo.
Sem interrupção – o conjunto de dimensionamento executa atualizações em lotes com um tempo de pausa opcional entre eles.
|
UpgradePolicy
|
Descreve uma política de atualização – automática, manual ou sem interrupção.
|
UserAccount
|
Propriedades usadas para criar um usuário em um nó Lote do Azure.
|
UserAssignedIdentities
|
A lista de identidades de usuário associadas.
|
UserIdentity
|
A definição da identidade do usuário sob a qual a tarefa é executada.
|
VirtualMachineConfiguration
|
A configuração para nós de computação em um pool com base na infraestrutura de Máquinas Virtuais do Azure.
|
VMExtension
|
A configuração para extensões de máquina virtual.
|
WindowsConfiguration
|
Configurações do sistema operacional Windows a serem aplicadas à máquina virtual.
|
WindowsUserConfiguration
|
Propriedades usadas para criar uma conta de usuário em um nó do Windows.
|
AllocationState
Se o pool está redimensionando.
Nome |
Tipo |
Description |
Resizing
|
string
|
O pool está redimensionando; ou seja, nós de computação estão sendo adicionados ou removidos do pool.
|
Steady
|
string
|
O pool não está redimensionando. Não há alterações no número de nós no pool em andamento. Um pool entra nesse estado quando é criado e quando nenhuma operação está sendo executada no pool para alterar o número de nós.
|
Stopping
|
string
|
O pool estava redimensionando, mas o usuário solicitou que o redimensionamento fosse interrompido, mas a solicitação de parada ainda não foi concluída.
|
ApplicationPackageReference
Vincular a um pacote de aplicativos dentro da conta do lote
Nome |
Tipo |
Description |
id
|
string
|
A ID do pacote de aplicativos a ser instalado. Isso deve estar dentro da mesma conta de lote que o pool. Isso pode ser uma referência a uma versão específica ou à versão padrão, se houver.
|
version
|
string
|
A versão do aplicativo a ser implantado. Se omitida, a versão padrão será implantada.
Se isso for omitido e nenhuma versão padrão for especificada para este aplicativo, a solicitação falhará com o código de erro InvalidApplicationPackageReferences. Se você estiver chamando a API REST diretamente, o código de status HTTP será 409.
|
AutomaticOSUpgradePolicy
Os parâmetros de configuração usados para executar a atualização automática do sistema operacional.
Nome |
Tipo |
Description |
disableAutomaticRollback
|
boolean
|
Se o recurso de reversão de imagem do sistema operacional deve ser desabilitado.
|
enableAutomaticOSUpgrade
|
boolean
|
Indica se as atualizações do sistema operacional devem ser aplicadas automaticamente às instâncias do conjunto de dimensionamento de maneira sem interrupção quando uma versão mais recente da imagem do sistema operacional estiver disponível.
Se isso for definido como true para pools baseados no Windows, WindowsConfiguration.enableAutomaticUpdates não poderá ser definido como true.
|
osRollingUpgradeDeferral
|
boolean
|
Adie as atualizações do sistema operacional nas TVMs se elas estiverem executando tarefas.
|
useRollingUpgradePolicy
|
boolean
|
Indica se a política de atualização sem interrupção deve ser usada durante a atualização automática do sistema operacional. A atualização automática do sistema operacional fará fallback para a política padrão se nenhuma política for definida no VMSS.
|
AutoScaleRun
Os resultados e erros de uma execução de uma fórmula de dimensionamento automático do pool.
Nome |
Tipo |
Description |
error
|
AutoScaleRunError
|
Detalhes do erro encontrado avaliando a fórmula de dimensionamento automático no pool, se a avaliação não foi bem-sucedida.
|
evaluationTime
|
string
|
A hora em que a fórmula de dimensionamento automático foi avaliada pela última vez.
|
results
|
string
|
Os valores finais de todas as variáveis usadas na avaliação da fórmula de dimensionamento automático.
Cada valor de variável é retornado no formato $variable=value e as variáveis são separadas por ponto e vírgula.
|
AutoScaleRunError
Um erro que ocorreu ao dimensionar automaticamente um pool.
Nome |
Tipo |
Description |
code
|
string
|
Um identificador para o erro. Os códigos são invariáveis e devem ser consumidos programaticamente.
|
details
|
AutoScaleRunError[]
|
Detalhes adicionais sobre o erro.
|
message
|
string
|
Uma mensagem que descreve o erro, destinada a ser adequada para exibição em uma interface do usuário.
|
AutoScaleSettings
Configurações de Dimensionamento Automático para o pool.
Nome |
Tipo |
Description |
evaluationInterval
|
string
|
O intervalo de tempo no qual ajustar automaticamente o tamanho do pool de acordo com a fórmula de dimensionamento automático.
Se omitido, o valor padrão será 15 minutos (PT15M).
|
formula
|
string
|
Uma fórmula para o número desejado de nós de computação no pool.
|
AutoUserScope
O escopo do usuário automático
Nome |
Tipo |
Description |
Pool
|
string
|
Especifica que a tarefa é executada como a conta de usuário automático comum que é criada em cada nó em um pool.
|
Task
|
string
|
Especifica que o serviço deve criar um novo usuário para a tarefa.
|
AutoUserSpecification
Especifica os parâmetros para o usuário automático que executa uma tarefa no serviço do Lote.
Nome |
Tipo |
Description |
elevationLevel
|
ElevationLevel
|
O nível de elevação do usuário automático.
O valor padrão é nonAdmin.
|
scope
|
AutoUserScope
|
O escopo do usuário automático
O valor padrão é Pool. Se o pool estiver executando o Windows, um valor de Task deverá ser especificado se for necessário um isolamento mais rigoroso entre as tarefas. Por exemplo, se a tarefa alterar o registro de uma maneira que possa afetar outras tarefas ou se os certificados tiverem sido especificados no pool, que não devem ser acessíveis por tarefas normais, mas devem ser acessíveis por tarefas iniciais.
|
AzureBlobFileSystemConfiguration
Informações usadas para se conectar a um Contêiner de Armazenamento do Azure usando o Blobfuse.
Nome |
Tipo |
Description |
accountKey
|
string
|
A chave da Conta de Armazenamento do Azure.
Essa propriedade é mutuamente exclusiva com sasKey e identidade; exatamente um deve ser especificado.
|
accountName
|
string
|
O nome da Conta de Armazenamento do Azure.
|
blobfuseOptions
|
string
|
Opções de linha de comando adicionais a serem passadas para o comando de montagem.
Essas são opções de 'net use' no Windows e opções de 'montagem' no Linux.
|
containerName
|
string
|
O nome do contêiner Armazenamento de Blobs do Azure.
|
identityReference
|
ComputeNodeIdentityReference
|
A referência à identidade atribuída pelo usuário a ser usada para acessar containerName
Essa propriedade é mutuamente exclusiva com accountKey e sasKey; exatamente um deve ser especificado.
|
relativeMountPath
|
string
|
O caminho relativo no nó de computação em que o sistema de arquivos será montado
Todos os sistemas de arquivos são montados em relação ao diretório montagens do Lote, acessível por meio da variável de ambiente AZ_BATCH_NODE_MOUNTS_DIR.
|
sasKey
|
string
|
O token SAS do Armazenamento do Azure.
Essa propriedade é mutuamente exclusiva com accountKey e identity; exatamente um deve ser especificado.
|
AzureFileShareConfiguration
Informações usadas para se conectar a um compartilhamento de arquivos do Azure.
Nome |
Tipo |
Description |
accountKey
|
string
|
A chave de conta de Armazenamento do Microsoft Azure.
|
accountName
|
string
|
O nome da conta do Armazenamento do Azure.
|
azureFileUrl
|
string
|
A URL do Arquivos do Azure.
Este é do formato 'https://{account}.file.core.windows.net/'.
|
mountOptions
|
string
|
Opções de linha de comando adicionais a serem passadas para o comando de montagem.
Essas são opções de 'net use' no Windows e opções de 'montagem' no Linux.
|
relativeMountPath
|
string
|
O caminho relativo no nó de computação em que o sistema de arquivos será montado
Todos os sistemas de arquivos são montados em relação ao diretório montagens do Lote, acessível por meio da variável de ambiente AZ_BATCH_NODE_MOUNTS_DIR.
|
BatchPoolIdentity
A identidade do pool do Lote, se configurada. Se a identidade do pool for atualizada durante a atualização de um pool existente, somente as novas VMs criadas após a redução do pool para 0 terão as identidades atualizadas
Nome |
Tipo |
Description |
type
|
PoolIdentityType
|
O tipo de identidade usado para o Pool do Lote.
|
userAssignedIdentities
|
object
|
A lista de identidades de usuário associadas ao pool do Lote.
|
CachingType
O tipo de cache a ser habilitado para o disco.
Nome |
Tipo |
Description |
None
|
string
|
O modo de cache do disco não está habilitado.
|
ReadOnly
|
string
|
O modo de cache do disco é somente leitura.
|
ReadWrite
|
string
|
O modo de cache do disco é leitura e gravação.
|
CertificateReference
Uma referência a um certificado a ser instalado em nós de computação em um pool. Isso deve existir dentro da mesma conta que o pool.
Nome |
Tipo |
Description |
id
|
string
|
A ID totalmente qualificada do certificado a ser instalado no pool. Isso deve estar dentro da mesma conta de lote que o pool.
|
storeLocation
|
CertificateStoreLocation
|
O local do repositório de certificados no nó de computação no qual instalar o certificado.
O valor padrão é currentUser. Essa propriedade é aplicável somente para pools configurados com nós do Windows (ou seja, criados com cloudServiceConfiguration ou com virtualMachineConfiguration usando uma referência de imagem do Windows). Para nós de computação do Linux, os certificados são armazenados em um diretório dentro do diretório de trabalho da tarefa e uma variável de ambiente AZ_BATCH_CERTIFICATES_DIR é fornecida à tarefa para consultar esse local. Para certificados com visibilidade de 'remoteUser', um diretório 'certs' é criado no diretório base do usuário (por exemplo, /home/{user-name}/certs) e os certificados são colocados nesse diretório.
|
storeName
|
string
|
O nome do repositório de certificados no nó de computação no qual instalar o certificado.
Essa propriedade é aplicável somente para pools configurados com nós do Windows (ou seja, criados com cloudServiceConfiguration ou com virtualMachineConfiguration usando uma referência de imagem do Windows). Os nomes comuns do repositório incluem: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, mas qualquer nome de repositório personalizado também pode ser usado. O valor padrão é 65536.
|
visibility
|
CertificateVisibility[]
|
Quais contas de usuário no nó de computação devem ter acesso aos dados privados do certificado.
|
CertificateStoreLocation
O local do repositório de certificados no nó de computação no qual instalar o certificado.
Nome |
Tipo |
Description |
CurrentUser
|
string
|
Os certificados devem ser instalados no repositório de certificados CurrentUser.
|
LocalMachine
|
string
|
Os certificados devem ser instalados no repositório de certificados LocalMachine.
|
CertificateVisibility
Quais contas de usuário no nó de computação devem ter acesso aos dados privados do certificado.
Nome |
Tipo |
Description |
RemoteUser
|
string
|
O certificado deve estar visível para as contas de usuário nas quais os usuários acessam remotamente o nó.
|
StartTask
|
string
|
O certificado deve estar visível para a conta de usuário na qual a tarefa de início é executada. Observe que, se o Escopo do AutoUser for Pool para StartTask e uma Tarefa, esse certificado também ficará visível para a Tarefa.
|
Task
|
string
|
O certificado deve estar visível para as contas de usuário nas quais as tarefas de trabalho são executadas.
|
CIFSMountConfiguration
Informações usadas para se conectar a um sistema de arquivos CIFS.
Nome |
Tipo |
Description |
mountOptions
|
string
|
Opções de linha de comando adicionais a serem passadas para o comando de montagem.
Essas são opções de 'net use' no Windows e opções de 'montagem' no Linux.
|
password
|
string
|
A senha a ser usada para autenticação no sistema de arquivos CIFS.
|
relativeMountPath
|
string
|
O caminho relativo no nó de computação em que o sistema de arquivos será montado
Todos os sistemas de arquivos são montados em relação ao diretório montagens do Lote, acessível por meio da variável de ambiente AZ_BATCH_NODE_MOUNTS_DIR.
|
source
|
string
|
O URI do sistema de arquivos a ser montado.
|
userName
|
string
|
O usuário a ser usado para autenticação no sistema de arquivos CIFS.
|
CloudError
Uma resposta de erro do serviço do Lote.
Nome |
Tipo |
Description |
error
|
CloudErrorBody
|
O corpo da resposta de erro.
|
CloudErrorBody
Uma resposta de erro do serviço do Lote.
Nome |
Tipo |
Description |
code
|
string
|
Um identificador para o erro. Os códigos são invariáveis e devem ser consumidos programaticamente.
|
details
|
CloudErrorBody[]
|
Uma lista de detalhes adicionais sobre o erro.
|
message
|
string
|
Uma mensagem que descreve o erro, destinada a ser adequada para exibição em uma interface do usuário.
|
target
|
string
|
O destino do erro específico. Por exemplo, o nome da propriedade em erro.
|
CloudServiceConfiguration
A configuração para nós em um pool com base na plataforma Serviços de Nuvem do Azure.
Nome |
Tipo |
Description |
osFamily
|
string
|
A família do SO convidado do Azure a ser instalada nas máquinas virtuais no pool.
Os valores possíveis são: 2 – Família do sistema operacional 2, equivalente ao Windows Server 2008 R2 SP1. 3 – Família do sistema operacional 3, equivalente a Windows Server 2012. 4 – Família do sistema operacional 4, equivalente a Windows Server 2012 R2. 5 – Família do sistema operacional 5, equivalente a Windows Server 2016. 6 – Família do sistema operacional 6, equivalente ao Windows Server 2019. Para obter mais informações, consulte Versões do sistema operacional convidado do Azure (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases).
|
osVersion
|
string
|
A versão do SO convidado do Azure a ser instalada nas máquinas virtuais no pool.
O valor padrão é * que especifica a versão mais recente do sistema operacional para a família de sistemas operacionais especificada.
|
ComputeNodeDeallocationOption
Determina o que fazer com um nó e suas tarefas em execução depois de ter sido selecionado para desalocação.
Nome |
Tipo |
Description |
Requeue
|
string
|
Encerre a execução de processos de tarefas e requeira as tarefas. As tarefas serão executadas novamente quando um nó estiver disponível. Remova nós assim que tarefas forem terminadas.
|
RetainedData
|
string
|
Permita que as tarefas em execução sejam concluídas e aguarde até que todos os períodos de retenção de dados da tarefa expirem. Não agende novas tarefas enquanto aguarda. Remova nós quando todos os períodos de retenção de tarefa expirem.
|
TaskCompletion
|
string
|
Permitir que as tarefas em execução sejam concluídas no momento. Não agende novas tarefas enquanto aguarda. Remova nós quando todas as tarefas forem concluídas.
|
Terminate
|
string
|
Encerrar tarefas em execução. As tarefas serão concluídas com failureInfo indicando que foram encerradas e não serão executadas novamente. Remova nós assim que tarefas forem terminadas.
|
ComputeNodeFillType
Como as tarefas devem ser distribuídas entre nós de computação.
Nome |
Tipo |
Description |
Pack
|
string
|
O maior número possível de tarefas (taskSlotsPerNode) deve ser atribuída a cada nó no pool antes que qualquer tarefa seja atribuída ao próximo nó no pool.
|
Spread
|
string
|
As tarefas devem ser atribuídas uniformemente em todos os nós no pool.
|
ComputeNodeIdentityReference
A referência a uma identidade atribuída pelo usuário associada ao pool do Lote que um nó de computação usará.
Nome |
Tipo |
Description |
resourceId
|
string
|
A ID de recurso do ARM da identidade atribuída pelo usuário.
|
ContainerConfiguration
A configuração para pools habilitados para contêineres.
Nome |
Tipo |
Description |
containerImageNames
|
string[]
|
A coleção de nomes de imagem de contêiner.
Essa é a referência de imagem completa, como seria especificado para "docker pull". Uma imagem será originada do registro padrão do Docker, a menos que a imagem seja totalmente qualificada com um registro alternativo.
|
containerRegistries
|
ContainerRegistry[]
|
Registros privados adicionais dos quais os contêineres podem ser extraídos.
Se alguma imagem precisar ser baixada de um registro privado que exija credenciais, essas credenciais deverão ser fornecidas aqui.
|
type
|
ContainerType
|
A tecnologia de contêiner a ser usada.
|
ContainerRegistry
Um registro de contêiner privado.
Nome |
Tipo |
Description |
identityReference
|
ComputeNodeIdentityReference
|
A referência à identidade atribuída pelo usuário a ser usada para acessar um Registro de Contêiner do Azure em vez de nome de usuário e senha.
A referência a uma identidade atribuída pelo usuário associada ao pool do Lote que um nó de computação usará.
|
password
|
string
|
A senha para fazer logon no servidor do Registro.
|
registryServer
|
string
|
A URL do registro.
Se omitido, o padrão será "docker.io".
|
username
|
string
|
O nome de usuário para fazer logon no servidor do Registro.
|
ContainerType
A tecnologia de contêiner a ser usada.
Nome |
Tipo |
Description |
CriCompatible
|
string
|
Uma tecnologia baseada em CRI será usada para iniciar os contêineres.
|
DockerCompatible
|
string
|
Uma tecnologia de contêiner compatível com Docker será usada para iniciar os contêineres.
|
ContainerWorkingDirectory
Um sinalizador para indicar onde está o diretório de trabalho da tarefa de contêiner. O padrão é 'taskWorkingDirectory'.
Nome |
Tipo |
Description |
ContainerImageDefault
|
string
|
Usando o diretório de trabalho definido pela imagem de contêiner. Cuidado para que esse diretório não contenha os arquivos de recurso baixados pelo Lote.
|
TaskWorkingDirectory
|
string
|
Use o diretório de trabalho da tarefa de serviço do Lote padrão, que conterá os arquivos de recurso de tarefa preenchidos pelo Lote.
|
DataDisk
Configurações que serão usadas pelos discos de dados associados aos Nós de Computação no Pool. Ao usar discos de dados anexados, você precisa montar e formatar os discos de dentro de uma VM para usá-los.
Nome |
Tipo |
Description |
caching
|
CachingType
|
O tipo de cache a ser habilitado para os discos de dados.
Os valores são:
none – o modo de cache do disco não está habilitado.
readOnly - O modo de cache do disco é somente leitura.
readWrite – o modo de cache do disco é leitura e gravação.
O valor padrão para cache é nenhum. Para obter informações sobre as opções de cache, consulte: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/.
|
diskSizeGB
|
integer
|
O tamanho inicial do disco em GB ao criar um novo disco de dados.
|
lun
|
integer
|
O número da unidade lógica.
O lun é usado para identificar exclusivamente cada disco de dados. Se estiver anexando vários discos, cada um deverá ter um lun distinto. O valor deve estar entre 0 e 63, inclusive.
|
storageAccountType
|
StorageAccountType
|
O tipo de conta de armazenamento a ser usado para o disco de dados.
Se omitido, o padrão será "Standard_LRS". Os valores são:
Standard_LRS – o disco de dados deve usar o armazenamento padrão com redundância local.
Premium_LRS – o disco de dados deve usar o armazenamento premium com redundância local.
|
DeploymentConfiguration
Propriedades de configuração de implantação.
Nome |
Tipo |
Description |
cloudServiceConfiguration
|
CloudServiceConfiguration
|
A configuração do serviço de nuvem para o pool.
Essa propriedade e virtualMachineConfiguration são mutuamente exclusivas e uma das propriedades deve ser especificada. Essa propriedade não poderá ser especificada se a conta do Lote foi criada com sua propriedade poolAllocationMode definida como 'UserSubscription'.
|
virtualMachineConfiguration
|
VirtualMachineConfiguration
|
A configuração da máquina virtual para o pool.
Essa propriedade e cloudServiceConfiguration são mutuamente exclusivas e uma das propriedades deve ser especificada.
|
DiffDiskPlacement
Especifica o posicionamento de disco efêmero para o disco do sistema operacional para todas as VMs no pool.
Nome |
Tipo |
Description |
CacheDisk
|
string
|
O Disco do SISTEMA Operacional Efêmero é armazenado no cache da VM.
|
DiffDiskSettings
Especifica as Configurações de Disco efêmero para o disco do sistema operacional usado pela máquina virtual.
DiskEncryptionConfiguration
A configuração de criptografia de disco aplicada em nós de computação no pool. Não há suporte para a configuração de criptografia de disco no pool do Linux criado com a Imagem da Máquina Virtual ou a Imagem da Galeria de Computação do Azure.
Nome |
Tipo |
Description |
targets
|
DiskEncryptionTarget[]
|
A lista de destinos de disco Serviço em Lote será criptografada no nó de computação
No pool do Linux, há suporte apenas para "TemporaryDisk"; no pool do Windows, "OsDisk" e "TemporaryDisk" devem ser especificados.
|
DiskEncryptionTarget
A lista de destinos de disco Serviço em Lote será criptografada no nó de computação
Nome |
Tipo |
Description |
OsDisk
|
string
|
O disco do sistema operacional no nó de computação é criptografado.
|
TemporaryDisk
|
string
|
O disco temporário no nó de computação é criptografado. No Linux, essa criptografia se aplica a outras partições (como aquelas em discos de dados montados) quando a criptografia ocorre no momento da inicialização.
|
DynamicVNetAssignmentScope
O escopo da atribuição de vnet dinâmica.
Nome |
Tipo |
Description |
job
|
string
|
A atribuição de VNet dinâmica é feita por trabalho. Se esse valor for definido, a ID da sub-rede de configuração de rede também deverá ser definida. Esse recurso requer aprovação antes do uso, entre em contato com o suporte
|
none
|
string
|
Nenhuma atribuição de VNet dinâmica está habilitada.
|
ElevationLevel
O nível de elevação do usuário.
Nome |
Tipo |
Description |
Admin
|
string
|
O usuário é um usuário com acesso elevado e opera com permissões de Administrador completas.
|
NonAdmin
|
string
|
O usuário é um usuário padrão sem acesso elevado.
|
EnvironmentSetting
Uma variável de ambiente a ser definida em um processo de tarefa.
Nome |
Tipo |
Description |
name
|
string
|
O nome da variável de ambiente.
|
value
|
string
|
O valor da variável de ambiente.
|
FixedScaleSettings
Correção das configurações de escala para o pool.
Nome |
Tipo |
Valor padrão |
Description |
nodeDeallocationOption
|
ComputeNodeDeallocationOption
|
|
Determina o que fazer com um nó e suas tarefas em execução se o tamanho do pool estiver diminuindo.
Se omitido, o valor padrão será Requeue.
|
resizeTimeout
|
string
|
PT15M
|
O tempo limite para alocação de nós de computação para o pool.
O valor padrão é 15 minutos. Os valores de tempo limite usam o formato ISO 8601. Por exemplo, use PT10M por 10 minutos. O valor mínimo é 5 minutos. Se você especificar um valor menor que 5 minutos, o serviço do Lote rejeitará a solicitação com um erro; se você estiver chamando a API REST diretamente, o código http status será 400 (solicitação incorreta).
|
targetDedicatedNodes
|
integer
|
|
O número desejado de nós de computação dedicados no pool.
Pelo menos um dos targetDedicatedNodes, targetLowPriorityNodes deve ser definido.
|
targetLowPriorityNodes
|
integer
|
|
O número desejado de nós de computação spot/de baixa prioridade no pool.
Pelo menos um dos targetDedicatedNodes, targetLowPriorityNodes deve ser definido.
|
ImageReference
Uma referência a uma imagem do Azure Máquinas Virtuais Marketplace ou ao recurso imagem do Azure de uma Máquina Virtual personalizada. Para obter a lista de todas as imageReferences verificadas por Lote do Azure, consulte a operação 'Listar SKUs do agente de nó com suporte'.
Nome |
Tipo |
Description |
id
|
string
|
O identificador de recurso do ARM da Imagem da Galeria de Computação do Azure. Nós de computação no pool serão criados usando essa ID de imagem. Isso é do formulário /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{versionId}.
Essa propriedade é mutuamente exclusiva com outras propriedades. A Imagem da Galeria de Computação do Azure deve ter réplicas na mesma região que a conta Lote do Azure. Para obter informações sobre as configurações de firewall do agente de nó do Lote para se comunicar com o serviço do Lote, consulte https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration.
|
offer
|
string
|
O tipo de oferta da imagem do Azure Máquinas Virtuais Marketplace.
Por exemplo, UbuntuServer ou WindowsServer.
|
publisher
|
string
|
O editor da imagem do Azure Máquinas Virtuais Marketplace.
Por exemplo, Canonical ou MicrosoftWindowsServer.
|
sku
|
string
|
O SKU da imagem do Azure Máquinas Virtuais Marketplace.
Por exemplo, 18.04-LTS ou 2022-datacenter.
|
version
|
string
|
A versão da imagem do Azure Máquinas Virtuais Marketplace.
Um valor "mais recente" pode ser especificado para selecionar a versão mais recente de uma imagem. Se omitido, o padrão será 'latest'.
|
InboundEndpointProtocol
O protocolo do ponto de extremidade.
Nome |
Tipo |
Description |
TCP
|
string
|
Use TCP para o ponto de extremidade.
|
UDP
|
string
|
Use UDP para o ponto de extremidade.
|
InboundNatPool
Um pool NAT de entrada que pode ser usado para abordar portas específicas em nós de computação em um pool do Lote externamente.
Nome |
Tipo |
Description |
backendPort
|
integer
|
O número da porta no nó de computação.
Isso deve ser exclusivo em um pool do Lote. Os valores aceitáveis estão entre 1 e 65535, exceto 22, 3389, 29876 e 29877, pois são reservados. Se quaisquer valores reservados forem fornecidos, a solicitação falhará com HTTP status código 400.
|
frontendPortRangeEnd
|
integer
|
O último número de porta no intervalo de portas externas que serão usadas para fornecer acesso de entrada ao backendPort em nós de computação individuais.
Os valores aceitáveis variam entre 1 e 65534, exceto as portas de 50000 a 55000 que são reservadas pelo serviço do Lote. Todos os intervalos dentro de um pool devem ser distintos e não podem se sobrepor. Se algum valor reservado ou sobreposto for fornecido, a solicitação falhará com HTTP status código 400.
|
frontendPortRangeStart
|
integer
|
O primeiro número de porta no intervalo de portas externas que serão usadas para fornecer acesso de entrada ao backendPort em nós de computação individuais.
Os valores aceitáveis variam entre 1 e 65534, exceto as portas de 50000 a 55000 que são reservadas. Todos os intervalos dentro de um pool devem ser distintos e não podem se sobrepor. Se algum valor reservado ou sobreposto for fornecido, a solicitação falhará com HTTP status código 400.
|
name
|
string
|
O nome do ponto de extremidade.
O nome deve ser exclusivo em um pool do Lote, pode conter letras, números, sublinhados, períodos e hifens. Os nomes devem começar com uma letra ou número, devem terminar com uma letra, número ou sublinhado e não podem exceder 77 caracteres. Se algum valor inválido for fornecido, a solicitação falhará com HTTP status código 400.
|
networkSecurityGroupRules
|
NetworkSecurityGroupRule[]
|
Uma lista de regras de grupo de segurança de rede que serão aplicadas ao ponto de extremidade.
O número máximo de regras que podem ser especificadas em todos os pontos de extremidade em um pool do Lote é 25. Se nenhuma regra de grupo de segurança de rede for especificada, uma regra padrão será criada para permitir o acesso de entrada ao back-endPort especificado. Se o número máximo de regras de grupo de segurança de rede for excedido, a solicitação falhará com HTTP status código 400.
|
protocol
|
InboundEndpointProtocol
|
O protocolo do ponto de extremidade.
|
InterNodeCommunicationState
Se o pool permite comunicação direta entre nós.
Nome |
Tipo |
Description |
Disabled
|
string
|
Desabilite a comunicação de rede entre máquinas virtuais.
|
Enabled
|
string
|
Habilite a comunicação de rede entre máquinas virtuais.
|
IPAddressProvisioningType
O tipo de provisionamento para endereços IP públicos para o Pool de Lotes.
Nome |
Tipo |
Description |
BatchManaged
|
string
|
Um IP público será criado e gerenciado pelo Lote. Pode haver vários IPs públicos dependendo do tamanho do Pool.
|
NoPublicIPAddresses
|
string
|
Nenhum endereço IP público será criado para os Nós de Computação no Pool.
|
UserManaged
|
string
|
Os IPs públicos são fornecidos pelo usuário e serão usados para provisionar os Nós de Computação.
|
LinuxUserConfiguration
Propriedades usadas para criar uma conta de usuário em um nó do Linux.
Nome |
Tipo |
Description |
gid
|
integer
|
A ID do grupo para a conta de usuário.
As propriedades uid e gid devem ser especificadas juntas ou não. Se não for especificado, o sistema operacional subjacente escolherá o gid.
|
sshPrivateKey
|
string
|
A chave privada SSH para a conta de usuário.
A chave privada não deve ser protegida por senha. A chave privada é usada para configurar automaticamente a autenticação baseada em chave assimétrica para SSH entre nós em um pool do Linux quando a propriedade enableInterNodeCommunication do pool for verdadeira (ela será ignorada se enableInterNodeCommunication for false). Ele faz isso colocando o par de chaves no diretório .ssh do usuário. Se não for especificado, o SSH sem senha não será configurado entre nós (nenhuma modificação do diretório .ssh do usuário é feita).
|
uid
|
integer
|
A ID de usuário da conta de usuário.
As propriedades uid e gid devem ser especificadas juntas ou não. Se não for especificado, o sistema operacional subjacente escolherá a uid.
|
LoginMode
Modo de logon para usuário
Nome |
Tipo |
Description |
Batch
|
string
|
O LOGON32_LOGON_BATCH modo de logon do Win32. O modo de logon em lote é recomendado para processos paralelos de execução prolongada.
|
Interactive
|
string
|
O LOGON32_LOGON_INTERACTIVE modo de logon do Win32. Alguns aplicativos exigem permissões associadas ao modo de logon interativo. Se esse for o caso de um aplicativo usado em sua tarefa, essa opção será recomendada.
|
ManagedDisk
Nome |
Tipo |
Description |
storageAccountType
|
StorageAccountType
|
O tipo de conta de armazenamento para disco gerenciado.
|
Um par nome-valor associado a um recurso de serviço do Lote.
Nome |
Tipo |
Description |
name
|
string
|
O nome do item de metadados.
|
value
|
string
|
O valor do item de metadados.
|
MountConfiguration
O sistema de arquivos a ser montado em cada nó.
Nome |
Tipo |
Description |
azureBlobFileSystemConfiguration
|
AzureBlobFileSystemConfiguration
|
O Contêiner de Armazenamento do Azure a ser montado usando o FUSE de blob em cada nó.
Essa propriedade é mutuamente exclusiva com todas as outras propriedades.
|
azureFileShareConfiguration
|
AzureFileShareConfiguration
|
O Compartilhamento de Arquivos do Azure a ser montado em cada nó.
Essa propriedade é mutuamente exclusiva com todas as outras propriedades.
|
cifsMountConfiguration
|
CIFSMountConfiguration
|
O sistema de arquivos CIFS/SMB a ser montado em cada nó.
Essa propriedade é mutuamente exclusiva com todas as outras propriedades.
|
nfsMountConfiguration
|
NFSMountConfiguration
|
O sistema de arquivos NFS a ser montado em cada nó.
Essa propriedade é mutuamente exclusiva com todas as outras propriedades.
|
NetworkConfiguration
A configuração de rede de um pool.
Nome |
Tipo |
Valor padrão |
Description |
dynamicVnetAssignmentScope
|
DynamicVNetAssignmentScope
|
none
|
O escopo da atribuição de vnet dinâmica.
|
enableAcceleratedNetworking
|
boolean
|
|
Se esse pool deve habilitar a rede acelerada.
A rede acelerada permite a SR-IOV (virtualização de E/S de raiz única) para uma VM, o que pode levar a um desempenho de rede aprimorado. Para obter mais informações, confira: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview.
|
endpointConfiguration
|
PoolEndpointConfiguration
|
|
A configuração para pontos de extremidade em nós de computação no pool do Lote.
A configuração do ponto de extremidade do pool só tem suporte em pools com a propriedade virtualMachineConfiguration.
|
publicIPAddressConfiguration
|
PublicIPAddressConfiguration
|
|
A configuração de IPAddress público para nós de computação no pool do Lote.
Essa propriedade só tem suporte em Pools com a propriedade virtualMachineConfiguration.
|
subnetId
|
string
|
|
O identificador de recurso arm da sub-rede de rede virtual à qual os nós de computação do pool ingressarão. Isso é do formato /subscriptions/{subscription}/resourceGroups/{group}/providers/{provider}/virtualNetworks/{network}/subnets/{subnet}.
A rede virtual deve estar na mesma região e assinatura que a conta Lote do Azure. A sub-rede especificada deve ter endereços IP gratuitos suficientes para acomodar o número de nós no pool. Se a sub-rede não tiver endereços IP gratuitos suficientes, o pool alocará parcialmente nós de computação e ocorrerá um erro de redimensionamento. A entidade de serviço 'MicrosoftAzureBatch' deve ter a função rbac (colaborador de máquina virtual clássica) Role-Based Controle de Acesso para a VNet especificada. A sub-rede especificada deve permitir a comunicação do serviço Lote do Azure para poder agendar tarefas nos nós de computação. Isso pode ser verificado verificando se a VNet especificada tem algum NSG (Grupos de Segurança de Rede) associado. Se a comunicação com os nós de computação na sub-rede especificada for negada por um NSG, o serviço do Lote definirá o estado dos nós de computação como inutilizável. Se a VNet especificada tiver grupos de segurança de rede (NSG) associados, algumas portas reservadas do sistema devem ser habilitadas para comunicação de entrada. Para pools criados com uma configuração de máquina virtual, habilite as portas 29876 e 29877, bem como a porta 22 para Linux e a porta 3389 para Windows. Para pools criados com uma configuração de serviço de nuvem, habilite as portas 10100, 20100 e 30100. Habilite também conexões de saída para o Armazenamento do Azure na porta 443. Para pools cloudServiceConfiguration, há suporte apenas para VNETs 'clássicos'. Para obter mais detalhes, confira: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration
|
NetworkSecurityGroupRule
Uma regra de grupo de segurança de rede a ser aplicada a um ponto de extremidade de entrada.
Nome |
Tipo |
Description |
access
|
NetworkSecurityGroupRuleAccess
|
A ação que deve ser executada para um endereço IP especificado, intervalo de sub-rede ou marca.
|
priority
|
integer
|
A prioridade para essa regra.
As prioridades em um pool devem ser exclusivas e são avaliadas em ordem de prioridade. Quanto menor o número, maior a prioridade. Por exemplo, as regras podem ser especificadas com números de pedidos de 150, 250 e 350. A regra com o número de ordem de 150 tem precedência sobre a regra que tem uma ordem de 250. As prioridades permitidas são de 150 a 4096. Se algum valor reservado ou duplicado for fornecido, a solicitação falhará com HTTP status código 400.
|
sourceAddressPrefix
|
string
|
O prefixo de endereço de origem ou a marca a ser correspondida para a regra.
Os valores válidos são um único endereço IP (ou seja, 10.10.10.10), sub-rede IP (ou seja, 192.168.1.0/24), marca padrão ou * (para todos os endereços). Se outros valores forem fornecidos, a solicitação falhará com HTTP status código 400.
|
sourcePortRanges
|
string[]
|
Os intervalos de porta de origem a serem correspondentes à regra.
Os valores válidos são '*' (para todas as portas 0 a 65535) ou matrizes de portas ou intervalos de portas (ou seja, 100-200). As portas devem estar no intervalo de 0 a 65535 e os intervalos de portas ou portas não podem se sobrepor. Se outros valores forem fornecidos, a solicitação falhará com HTTP status código 400. O valor padrão será *.
|
NetworkSecurityGroupRuleAccess
A ação que deve ser executada para um endereço IP especificado, intervalo de sub-rede ou marca.
Nome |
Tipo |
Description |
Allow
|
string
|
Permitir o acesso.
|
Deny
|
string
|
Nega o acesso.
|
NFSMountConfiguration
Informações usadas para se conectar a um sistema de arquivos NFS.
Nome |
Tipo |
Description |
mountOptions
|
string
|
Opções de linha de comando adicionais a serem passadas para o comando de montagem.
Essas são opções de 'net use' no Windows e opções de 'montagem' no Linux.
|
relativeMountPath
|
string
|
O caminho relativo no nó de computação em que o sistema de arquivos será montado
Todos os sistemas de arquivos são montados em relação ao diretório montagens do Lote, acessível por meio da variável de ambiente AZ_BATCH_NODE_MOUNTS_DIR.
|
source
|
string
|
O URI do sistema de arquivos a ser montado.
|
NodeCommunicationMode
Determina como um pool se comunica com o serviço do Lote.
Nome |
Tipo |
Description |
Classic
|
string
|
Os nós que usam o modo de comunicação Clássico exigem comunicação TCP de entrada nas portas 29876 e 29877 do "BatchNodeManagement. {region}" marca de serviço e comunicação TCP de saída na porta 443 para "Storage.region" e "BatchNodeManagement. Marcas de serviço {region}".
|
Default
|
string
|
O modo de comunicação do nó é definido automaticamente pelo serviço lote.
|
Simplified
|
string
|
Os nós que usam o modo de comunicação simplificado exigem comunicação TCP de saída na porta 443 para o "BatchNodeManagement. Marca de serviço {region}". Nenhuma porta de entrada aberta é necessária.
|
NodePlacementConfiguration
Configuração de posicionamento de nó para pools de lote.
Nome |
Tipo |
Description |
policy
|
NodePlacementPolicyType
|
Tipo de política de posicionamento de nó em Pools de Lote.
Política de alocação usada pelo Serviço de Lote para provisionar os nós. Se não for especificado, o Lote usará a política regional.
|
NodePlacementPolicyType
A política de posicionamento para alocar nós no pool.
Nome |
Tipo |
Description |
Regional
|
string
|
Todos os nós no pool serão alocados na mesma região.
|
Zonal
|
string
|
Os nós no pool serão distribuídos entre diferentes zonas com o melhor balanceamento de esforço.
|
OSDisk
Configurações para o disco do sistema operacional da máquina virtual.
Nome |
Tipo |
Description |
caching
|
CachingType
|
Especifica os requisitos de cache. Os valores possíveis são: None, ReadOnly, ReadWrite. Os valores padrão são: Nenhum para armazenamento Standard. ReadOnly para armazenamento Premium.
|
diskSizeGB
|
integer
|
O tamanho inicial do disco em GB ao criar um novo disco do sistema operacional.
|
ephemeralOSDiskSettings
|
DiffDiskSettings
|
Especifica as Configurações de Disco efêmero para o disco do sistema operacional usado pela máquina virtual.
|
managedDisk
|
ManagedDisk
|
Os parâmetros de disco gerenciado.
|
writeAcceleratorEnabled
|
boolean
|
Especifica se writeAccelerator deve ser habilitado ou desabilitado no disco.
|
Pool
Contém informações sobre um pool.
Nome |
Tipo |
Valor padrão |
Description |
etag
|
string
|
|
A ETag do recurso, usada para instruções de simultaneidade.
|
id
|
string
|
|
A ID do recurso.
|
identity
|
BatchPoolIdentity
|
|
O tipo de identidade usado para o Pool do Lote.
O tipo de identidade usado para o Pool do Lote.
|
name
|
string
|
|
O nome do recurso.
|
properties.allocationState
|
AllocationState
|
|
Se o pool está redimensionando.
|
properties.allocationStateTransitionTime
|
string
|
|
A hora em que o pool entrou no seu estado atual de alocação.
|
properties.applicationLicenses
|
string[]
|
|
A lista de licenças de aplicativo que o serviço do Lote disponibilizará em cada nó de computação no pool.
A lista de licenças de aplicativo deve ser um subconjunto de licenças de aplicativo de serviço do Lote disponíveis. Se uma licença for solicitada sem suporte, a criação do pool falhará.
|
properties.applicationPackages
|
ApplicationPackageReference[]
|
|
A lista de pacotes de aplicativos a serem instalados em cada nó de computação no pool.
As alterações nas referências do pacote de aplicativos afetam todos os novos nós de computação que ingressam no pool, mas não afetam os nós de computação que já estão no pool até que sejam reinicializados ou recriados. Há no máximo 10 referências de pacote de aplicativos em qualquer pool específico.
|
properties.autoScaleRun
|
AutoScaleRun
|
|
Os resultados e erros da última execução da fórmula de dimensionamento automático.
Essa propriedade será definida somente se o pool for dimensionado automaticamente, ou seja, autoScaleSettings serão usados.
|
properties.certificates
|
CertificateReference[]
|
|
A lista de certificados a serem instalados em cada nó de computação no pool.
Para nós de computação do Windows, o serviço lote instala os certificados no repositório de certificados e no local especificados. Para nós de computação do Linux, os certificados são armazenados em um diretório dentro do diretório de trabalho da tarefa e uma variável de ambiente AZ_BATCH_CERTIFICATES_DIR é fornecida à tarefa para consultar esse local. Para certificados com visibilidade de 'remoteUser', um diretório 'certs' é criado no diretório base do usuário (por exemplo, /home/{user-name}/certs) e os certificados são colocados nesse diretório.
Aviso: essa propriedade foi preterida e será removida após fevereiro de 2024. Em vez disso, use a Extensão do Azure KeyVault .
|
properties.creationTime
|
string
|
|
A hora de criação do pool.
|
properties.currentDedicatedNodes
|
integer
|
|
O número de nós de computação dedicados atualmente no pool.
|
properties.currentLowPriorityNodes
|
integer
|
|
O número de nós de computação spot/de baixa prioridade atualmente no pool.
|
properties.currentNodeCommunicationMode
|
NodeCommunicationMode
|
|
O estado atual do modo de comunicação do pool.
|
properties.deploymentConfiguration
|
DeploymentConfiguration
|
|
Essa propriedade descreve como os nós do pool serão implantados usando Serviços de Nuvem ou Máquinas Virtuais.
O uso de CloudServiceConfiguration especifica que os nós devem ser criados usando o Azure Serviços de Nuvem (PaaS), enquanto VirtualMachineConfiguration usa IaaS (Azure Máquinas Virtuais).
|
properties.displayName
|
string
|
|
O nome de exibição do pool.
O nome de exibição não precisa ser exclusivo e pode conter caracteres Unicode até um comprimento máximo de 1024.
|
properties.interNodeCommunication
|
InterNodeCommunicationState
|
|
Se o pool permite comunicação direta entre nós.
Isso impõe restrições sobre quais nós podem ser atribuídos ao pool. Habilitar esse valor pode reduzir a chance do número solicitado de nós ser alocado no pool. Se não for especificado, esse valor usará como padrão 'Desabilitado'.
|
properties.lastModified
|
string
|
|
A hora da última modificação do pool.
Esta é a última vez em que os dados no nível do pool, como targetDedicatedNodes ou autoScaleSettings, foram alterados. Ele não leva em conta alterações no nível do nó, como um estado de alteração de nó de computação.
|
properties.metadata
|
MetadataItem[]
|
|
Uma lista de pares nome-valor associados ao pool como metadados.
O serviço lote não atribui nenhum significado aos metadados; é exclusivamente para o uso do código do usuário.
|
properties.mountConfiguration
|
MountConfiguration[]
|
|
Uma lista de sistemas de arquivos a serem montados em cada nó no pool.
Isso dá suporte a Arquivos do Azure, NFS, CIFS/SMB e Blobfuse.
|
properties.networkConfiguration
|
NetworkConfiguration
|
|
A configuração de rede para o pool.
A configuração de rede de um pool.
|
properties.provisioningState
|
PoolProvisioningState
|
|
O estado atual do pool.
|
properties.provisioningStateTransitionTime
|
string
|
|
A hora em que o pool entrou no seu estado atual.
|
properties.resizeOperationStatus
|
ResizeOperationStatus
|
|
Contém detalhes sobre a operação de redimensionamento atual ou última concluída.
Descreve a operação atual (se o pool AllocationState estiver redimensionando) ou a operação concluída anteriormente (se AllocationState for Estável).
|
properties.resourceTags
|
object
|
|
As marcas especificadas pelo usuário associadas ao pool.
As marcas definidas pelo usuário a serem associadas ao pool de Lote do Azure. Quando especificadas, essas marcas são propagadas para os recursos do Azure de suporte associados ao pool. Essa propriedade só pode ser especificada quando a conta do Lote foi criada com a propriedade poolAllocationMode definida como 'UserSubscription'.
|
properties.scaleSettings
|
ScaleSettings
|
|
Configurações que definem o número de nós no pool.
Define o tamanho desejado do pool. Isso pode ser 'fixedScale' em que o targetDedicatedNodes solicitado é especificado ou 'autoScale' que define uma fórmula que é reavaliada periodicamente. Se essa propriedade não for especificada, o pool terá uma escala fixa com 0 targetDedicatedNodes.
|
properties.startTask
|
StartTask
|
|
Uma tarefa especificada para ser executada em cada nó de computação à medida que ele ingressa no pool.
Em uma operação PATCH (atualização), essa propriedade pode ser definida como um objeto vazio para remover a tarefa inicial do pool.
|
properties.targetNodeCommunicationMode
|
NodeCommunicationMode
|
|
O modo de comunicação de nó desejado para o pool.
Se omitido, o valor padrão será Default.
|
properties.taskSchedulingPolicy
|
TaskSchedulingPolicy
|
|
Como as tarefas são distribuídas entre nós de computação em um pool.
Se não for especificado, o padrão será spread.
|
properties.taskSlotsPerNode
|
integer
|
1
|
O número de slots de tarefas que podem ser usados para executar tarefas simultâneas em um único nó de computação no pool.
O valor padrão é 1. O valor máximo é o menor de 4 vezes o número de núcleos do vmSize do pool ou 256.
|
properties.upgradePolicy
|
UpgradePolicy
|
|
A política de atualização para o pool.
Descreve uma política de atualização – automática, manual ou sem interrupção.
|
properties.userAccounts
|
UserAccount[]
|
|
A lista de contas de usuário a serem criadas em cada nó no pool.
|
properties.vmSize
|
string
|
|
O tamanho das máquinas virtuais no pool. Todas as VMs em um pool têm o mesmo tamanho.
Para obter informações sobre os tamanhos disponíveis de máquinas virtuais para pools de Serviços de Nuvem (pools criados com cloudServiceConfiguration), consulte Tamanhos para Serviços de Nuvem (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). O Lote dá suporte a todos os tamanhos de VM Serviços de Nuvem, exceto ExtraSmall. Para obter informações sobre os tamanhos de VM disponíveis para pools usando imagens do Máquinas Virtuais Marketplace (pools criados com virtualMachineConfiguration), consulte Tamanhos para Máquinas Virtuais (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) ou Tamanhos para Máquinas Virtuais (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). O Lote dá suporte a todos os tamanhos de VM do Azure, exceto STANDARD_A0 e aqueles com armazenamento premium (STANDARD_GS, STANDARD_DS e séries STANDARD_DSV2).
|
type
|
string
|
|
Tipo do recurso.
|
PoolEndpointConfiguration
A configuração do ponto de extremidade para um pool.
Nome |
Tipo |
Description |
inboundNatPools
|
InboundNatPool[]
|
Uma lista de pools NAT de entrada que podem ser usados para abordar portas específicas em um nó de computação individual externamente.
O número máximo de pools NAT de entrada por pool do Lote é 5. Se o número máximo de pools NAT de entrada for excedido, a solicitação falhará com HTTP status código 400. Isso não poderá ser especificado se o IPAddressProvisioningType for NoPublicIPAddresses.
|
PoolIdentityType
O tipo de identidade usado para o Pool do Lote.
Nome |
Tipo |
Description |
None
|
string
|
O pool de lotes não tem nenhuma identidade associada a ele. A configuração None no pool de atualizações removerá as identidades existentes.
|
UserAssigned
|
string
|
O pool de lotes tem identidades atribuídas pelo usuário com ele.
|
PoolProvisioningState
O estado atual do pool.
Nome |
Tipo |
Description |
Deleting
|
string
|
O usuário solicitou que o pool fosse excluído, mas a operação de exclusão ainda não foi concluída.
|
Succeeded
|
string
|
O pool está disponível para executar tarefas sujeitas à disponibilidade de nós de computação.
|
PublicIPAddressConfiguration
A configuração de endereço IP público da configuração de rede de um Pool.
Nome |
Tipo |
Description |
ipAddressIds
|
string[]
|
A lista de IPs públicos que o serviço do Lote usará ao provisionar nós de computação.
O número de IPs especificados aqui limita o tamanho máximo do Pool – 100 nós dedicados ou 100 nós spot/de baixa prioridade podem ser alocados para cada IP público. Por exemplo, um pool que precisa de 250 VMs dedicadas precisaria de pelo menos três IPs públicos especificados. Cada elemento dessa coleção é do formulário: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}.
|
provision
|
IPAddressProvisioningType
|
O tipo de provisionamento para endereços IP públicos para o pool
O valor padrão é BatchManaged
|
ResizeError
Um erro que ocorreu ao redimensionar um pool.
Nome |
Tipo |
Description |
code
|
string
|
Um identificador para o erro. Os códigos são invariáveis e devem ser consumidos programaticamente.
|
details
|
ResizeError[]
|
Detalhes adicionais sobre o erro.
|
message
|
string
|
Uma mensagem que descreve o erro, destinada a ser adequada para exibição em uma interface do usuário.
|
ResizeOperationStatus
Detalhes sobre a operação de redimensionamento atual ou última concluída.
Nome |
Tipo |
Description |
errors
|
ResizeError[]
|
Detalhes dos erros encontrados ao executar o último redimensionamento no pool.
Essa propriedade será definida somente se ocorrer um erro durante o último redimensionamento do pool e somente quando o pool allocationState for Steady.
|
nodeDeallocationOption
|
ComputeNodeDeallocationOption
|
Determina o que fazer com um nó e suas tarefas em execução se o tamanho do pool estiver diminuindo.
O valor padrão é colocar novamente na fila.
|
resizeTimeout
|
string
|
O tempo limite para alocação de nós de computação para o pool ou a remoção de nós de computação do pool.
O valor padrão é 15 minutos. O valor mínimo é 5 minutos. Se você especificar um valor inferior a 5 minutos, o serviço lote retornará um erro; se você estiver chamando a API REST diretamente, o código de status HTTP será 400 (Solicitação Incorreta).
|
startTime
|
string
|
A hora em que essa operação de redimensionamento foi iniciada.
|
targetDedicatedNodes
|
integer
|
O número desejado de nós de computação dedicados no pool.
|
targetLowPriorityNodes
|
integer
|
O número desejado de nós de computação spot/de baixa prioridade no pool.
|
ResourceFile
Um único arquivo ou vários arquivos a serem baixados em um nó de computação.
Nome |
Tipo |
Description |
autoStorageContainerName
|
string
|
O nome do contêiner de armazenamento na conta de armazenamento automático.
As propriedades autoStorageContainerName, storageContainerUrl e httpUrl são mutuamente exclusivas e uma delas deve ser especificada.
|
blobPrefix
|
string
|
O prefixo de blob a ser usado ao baixar blobs de um contêiner do Armazenamento do Azure. Somente os blobs cujos nomes começam com o prefixo especificado serão baixados.
A propriedade é válida somente quando autoStorageContainerName ou storageContainerUrl é usado. Esse prefixo pode ser um nome de arquivo parcial ou um subdiretório. Se um prefixo não for especificado, todos os arquivos no contêiner serão baixados.
|
fileMode
|
string
|
O atributo de modo de permissão de arquivo no formato octal.
Essa propriedade se aplica somente aos arquivos que estão sendo baixados para nós de computação do Linux. Ele será ignorado se for especificado para um resourceFile que será baixado em um nó do Windows. Se essa propriedade não for especificada para um nó do Linux, um valor padrão de 0770 será aplicado ao arquivo.
|
filePath
|
string
|
O local no nó de computação para o qual baixar o arquivo, em relação ao diretório de trabalho da tarefa.
Se a propriedade httpUrl for especificada, o filePath será necessário e descreverá o caminho para o qual o arquivo será baixado, incluindo o nome do arquivo. Caso contrário, se a propriedade autoStorageContainerName ou storageContainerUrl for especificada, filePath será opcional e será o diretório para o qual baixar os arquivos. No caso em que filePath é usado como um diretório, qualquer estrutura de diretório já associada aos dados de entrada será mantida na íntegra e acrescentada ao diretório filePath especificado. O caminho relativo especificado não pode sair do diretório de trabalho da tarefa (por exemplo, usando '..').
|
httpUrl
|
string
|
A URL do arquivo para download.
As propriedades autoStorageContainerName, storageContainerUrl e httpUrl são mutuamente exclusivas e uma delas deve ser especificada. Se a URL apontar para Armazenamento de Blobs do Azure, ela deverá ser legível de nós de computação. Há três maneiras de obter essa URL para um blob no armazenamento do Azure: incluir uma SAS (Assinatura de Acesso Compartilhado) concedendo permissões de leitura no blob, usar uma identidade gerenciada com permissão de leitura ou definir a ACL para o blob ou seu contêiner para permitir acesso público.
|
identityReference
|
ComputeNodeIdentityReference
|
A referência à identidade atribuída pelo usuário a ser usada para acessar Armazenamento de Blobs do Azure especificada por storageContainerUrl ou httpUrl
A referência a uma identidade atribuída pelo usuário associada ao pool do Lote que um nó de computação usará.
|
storageContainerUrl
|
string
|
A URL do contêiner de blob no Armazenamento de Blobs do Azure.
As propriedades autoStorageContainerName, storageContainerUrl e httpUrl são mutuamente exclusivas e uma delas deve ser especificada. Essa URL deve ser legível e listável de nós de computação. Há três maneiras de obter essa URL para um contêiner no armazenamento do Azure: incluir uma SAS (Assinatura de Acesso Compartilhado) concedendo permissões de leitura e lista no contêiner, usar uma identidade gerenciada com permissões de leitura e lista ou definir a ACL para o contêiner para permitir acesso público.
|
RollingUpgradePolicy
Os parâmetros de configuração usados durante a execução de uma atualização sem interrupção.
Nome |
Tipo |
Description |
enableCrossZoneUpgrade
|
boolean
|
Permitir que o VMSS ignore os limites do AZ ao construir lotes de atualização. Leve em consideração o Domínio de Atualização e maxBatchInstancePercent para determinar o tamanho do lote. Se esse campo não estiver definido, o Azure Lote do Azure não definirá seu valor padrão. O valor de enableCrossZoneUpgrade no VirtualMachineScaleSet criado será decidido pelas configurações padrão em VirtualMachineScaleSet. Esse campo pode ser definido como true ou false somente ao usar NodePlacementConfiguration como Zonal.
|
maxBatchInstancePercent
|
integer
|
A porcentagem máxima do total de instâncias de máquina virtual que serão atualizadas simultaneamente pela atualização sem interrupção em um lote. Como isso é um máximo, instâncias não íntegras em lotes anteriores ou futuros podem fazer com que o percentual de instâncias em um lote diminua para garantir maior confiabilidade. O valor desse campo deve estar entre 5 e 100, inclusive. Se maxBatchInstancePercent e maxUnhealthyInstancePercent forem atribuídos com valor, o valor de maxBatchInstancePercent não deverá ser maior que maxUnhealthyInstancePercent.
|
maxUnhealthyInstancePercent
|
integer
|
O percentual máximo do total de instâncias de máquina virtual no conjunto de dimensionamento que pode ser simultaneamente não íntegro, seja como resultado da atualização ou por ser encontrado em um estado não íntegro pelas verificações de integridade da máquina virtual antes que a atualização sem interrupção seja anulada. Essa restrição será verificada antes de iniciar qualquer lote. O valor desse campo deve estar entre 5 e 100, inclusive. Se maxBatchInstancePercent e maxUnhealthyInstancePercent forem atribuídos com valor, o valor de maxBatchInstancePercent não deverá ser maior que maxUnhealthyInstancePercent.
|
maxUnhealthyUpgradedInstancePercent
|
integer
|
O percentual máximo de instâncias de máquina virtual atualizadas que podem ser encontradas em um estado não íntegro. Esse marcar ocorrerá depois que cada lote for atualizado. Se esse percentual for excedido, a atualização sem interrupção será anulada. O valor desse campo deve estar entre 0 e 100, inclusive.
|
pauseTimeBetweenBatches
|
string
|
O tempo de espera entre concluir a atualização de todas as máquinas virtuais em um lote e iniciar o próximo lote. A duração do tempo deve ser especificada no formato ISO 8601.
|
prioritizeUnhealthyInstances
|
boolean
|
Atualize todas as instâncias não íntegras em um conjunto de dimensionamento antes de qualquer instância íntegra.
|
rollbackFailedInstancesOnPolicyBreach
|
boolean
|
Reverter instâncias com falha para o modelo anterior se a política de Atualização Sem Interrupção for violada.
|
ScaleSettings
Configurações de escala para o pool
Nome |
Tipo |
Description |
autoScale
|
AutoScaleSettings
|
Configurações de Dimensionamento Automático para o pool.
Essa propriedade e fixedScale são mutuamente exclusivas e uma das propriedades deve ser especificada.
|
fixedScale
|
FixedScaleSettings
|
Correção das configurações de escala para o pool.
Essa propriedade e o dimensionamento automático são mutuamente exclusivos e uma das propriedades deve ser especificada.
|
SecurityProfile
Especifica as configurações de perfil de segurança para a máquina virtual ou o conjunto de dimensionamento de máquinas virtuais.
Nome |
Tipo |
Description |
encryptionAtHost
|
boolean
|
Essa propriedade pode ser usada pelo usuário na solicitação para habilitar ou desabilitar a Criptografia de Host para a máquina virtual ou conjunto de dimensionamento de máquinas virtuais. Isso habilitará a criptografia para todos os discos, incluindo o disco Resource/Temp no próprio host.
|
securityType
|
SecurityTypes
|
Especifica o SecurityType da máquina virtual. Ele precisa ser definido como qualquer valor especificado para habilitar UefiSettings.
|
uefiSettings
|
UefiSettings
|
Especifica as configurações de segurança, como inicialização segura e vTPM usadas durante a criação da máquina virtual.
Especifica as configurações de segurança, como inicialização segura e vTPM usadas durante a criação da máquina virtual.
|
SecurityTypes
Especifica o SecurityType da máquina virtual. Ele precisa ser definido como qualquer valor especificado para habilitar UefiSettings.
Nome |
Tipo |
Description |
trustedLaunch
|
string
|
O início confiável protege contra técnicas de ataque avançadas e persistentes.
|
ServiceArtifactReference
Especifica a ID de referência do artefato de serviço usada para definir a mesma versão de imagem para todas as máquinas virtuais no conjunto de dimensionamento ao usar a versão de imagem 'mais recente'.
Nome |
Tipo |
Description |
id
|
string
|
A ID de referência do artefato de serviço de ServiceArtifactReference
A ID de referência do artefato de serviço na forma de /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}
|
StartTask
Uma tarefa que é executada quando um nó de computação ingressa em um pool no serviço Lote do Azure ou quando o nó de computação é reinicializado ou recriado.
Nome |
Tipo |
Valor padrão |
Description |
commandLine
|
string
|
|
A linha de comando da tarefa inicial.
A linha de comando não é executada em um shell e, portanto, não pode aproveitar os recursos do shell, como expansão de variável de ambiente. Se você quiser aproveitar esses recursos, invoque o shell na linha de comando, por exemplo, usando "cmd /c MyCommand" no Windows ou "/bin/sh -c MyCommand" no Linux. Obrigatório se outras propriedades do startTask forem especificadas.
|
containerSettings
|
TaskContainerSettings
|
|
As configurações do contêiner no qual a tarefa inicial é executada.
Quando isso é especificado, todos os diretórios recursivamente abaixo do AZ_BATCH_NODE_ROOT_DIR (a raiz de Lote do Azure diretórios no nó) são mapeados para o contêiner, todas as variáveis de ambiente de tarefa são mapeadas para o contêiner e a linha de comando da tarefa é executada no contêiner.
|
environmentSettings
|
EnvironmentSetting[]
|
|
Uma lista de configurações de variável de ambiente para a tarefa inicial.
|
maxTaskRetryCount
|
integer
|
0
|
O número máximo de vezes que a tarefa pode ser repetida.
O serviço em lotes repetirá uma tarefa se seu código de saída for diferente de zero. Observe que esse valor controla especificamente o número de tentativas. O serviço em lotes tentará a tarefa uma vez e, em seguida, pode tentar novamente até esse limite. Por exemplo, se a contagem máxima de repetições for 3, o Lote tentará a tarefa até 4 vezes (uma tentativa inicial e três novas tentativas). Se a contagem máxima de repetições for 0, o serviço do Lote não repetirá a tarefa. Se a contagem máxima de repetições for -1, o serviço do Lote repetirá a tarefa sem limite. O padrão é 0
|
resourceFiles
|
ResourceFile[]
|
|
Uma lista de arquivos que o serviço do Lote baixará para o nó de computação antes de executar a linha de comando.
|
userIdentity
|
UserIdentity
|
|
A identidade do usuário sob a qual a tarefa inicial é executada.
Se omitida, a tarefa será executada como um usuário não administrativo exclusivo da tarefa.
|
waitForSuccess
|
boolean
|
|
Se o serviço do Lote deve aguardar a conclusão bem-sucedida da tarefa inicial (ou seja, sair com o código de saída 0) antes de agendar qualquer tarefa no nó de computação.
Se true e a tarefa inicial falharem em um nó de computação, o serviço do Lote tentará novamente a tarefa inicial até sua contagem máxima de repetição (maxTaskRetryCount). Se a tarefa ainda não tiver sido concluída com êxito após todas as novas tentativas, o serviço lote marcará o nó de computação inutilizável e não agendará tarefas para ela. Essa condição pode ser detectada por meio do estado do nó e dos detalhes do erro de agendamento. Se for false, o serviço do Lote não aguardará a conclusão da tarefa inicial. Nesse caso, outras tarefas podem começar a ser executadas no nó de computação enquanto a tarefa inicial ainda está em execução; e mesmo que a tarefa inicial falhe, novas tarefas continuarão a ser agendadas no nó. O padrão é true.
|
StorageAccountType
O tipo de conta de armazenamento para uso na criação de discos de dados ou disco do sistema operacional.
Nome |
Tipo |
Description |
Premium_LRS
|
string
|
O disco de dados/disco do sistema operacional deve usar o armazenamento premium com redundância local.
|
StandardSSD_LRS
|
string
|
O disco de dados/disco do sistema operacional deve usar o armazenamento com redundância local do SSD padrão.
|
Standard_LRS
|
string
|
O disco de dados/disco do sistema operacional deve usar o armazenamento padrão com redundância local.
|
TaskContainerSettings
As configurações de contêiner para uma tarefa.
Nome |
Tipo |
Description |
containerRunOptions
|
string
|
Opções adicionais para o comando de criação de contêiner.
Essas opções adicionais são fornecidas como argumentos para o comando "docker create", além daquelas controladas pelo Serviço de Lote.
|
imageName
|
string
|
A imagem a ser usada para criar o contêiner no qual a tarefa será executada.
Essa é a referência de imagem completa, como seria especificado para "docker pull". Se nenhuma marca for fornecida como parte do nome da imagem, a marca ":latest" será usada como padrão.
|
registry
|
ContainerRegistry
|
O registro privado que contém a imagem do contêiner.
Essa configuração poderá ser omitida se já tiver sido fornecida na criação do pool.
|
workingDirectory
|
ContainerWorkingDirectory
|
Um sinalizador para indicar onde está o diretório de trabalho da tarefa de contêiner. O padrão é 'taskWorkingDirectory'.
|
TaskSchedulingPolicy
Especifica como as tarefas devem ser distribuídas entre nós de computação.
Nome |
Tipo |
Valor padrão |
Description |
nodeFillType
|
ComputeNodeFillType
|
Spread
|
Como as tarefas devem ser distribuídas entre nós de computação.
|
UefiSettings
Especifica as configurações de segurança, como inicialização segura e vTPM usadas durante a criação da máquina virtual.
Nome |
Tipo |
Description |
secureBootEnabled
|
boolean
|
Especifica se a inicialização segura deve ser habilitada na máquina virtual.
|
vTpmEnabled
|
boolean
|
Especifica se o vTPM deve ser habilitado na máquina virtual.
|
UpgradeMode
Especifica o modo de uma atualização para máquinas virtuais no conjunto de dimensionamento.
Os valores possíveis são:
Manual – você controla a aplicação de atualizações para máquinas virtuais no conjunto de dimensionamento. Faça isso usando a ação manualUpgrade.
Automático – todas as máquinas virtuais no conjunto de dimensionamento são atualizadas automaticamente ao mesmo tempo.
Sem interrupção – o conjunto de dimensionamento executa atualizações em lotes com um tempo de pausa opcional entre eles.
Nome |
Tipo |
Description |
automatic
|
string
|
Todas as máquinas virtuais no conjunto de dimensionamento são atualizadas automaticamente ao mesmo tempo.
|
manual
|
string
|
Você controla a aplicação de atualizações para máquinas virtuais no conjunto de dimensionamento. Faça isso usando a ação manualUpgrade.
|
rolling
|
string
|
As instâncias existentes em um conjunto de dimensionamento são derrubadas em lotes a serem atualizados. Depois que o lote atualizado for concluído, as instâncias começarão a usar o tráfego novamente e o próximo lote será iniciado. Isso continuará até que todas as instâncias sejam atualizadas.
|
UpgradePolicy
Descreve uma política de atualização – automática, manual ou sem interrupção.
Nome |
Tipo |
Description |
automaticOSUpgradePolicy
|
AutomaticOSUpgradePolicy
|
Parâmetros de configuração usados para executar a atualização automática do sistema operacional.
Os parâmetros de configuração usados para executar a atualização automática do sistema operacional.
|
mode
|
UpgradeMode
|
Especifica o modo de uma atualização para máquinas virtuais no conjunto de dimensionamento.
Os valores possíveis são:
Manual – você controla a aplicação de atualizações para máquinas virtuais no conjunto de dimensionamento. Faça isso usando a ação manualUpgrade.
Automático – todas as máquinas virtuais no conjunto de dimensionamento são atualizadas automaticamente ao mesmo tempo.
Sem interrupção – o conjunto de dimensionamento executa atualizações em lotes com um tempo de pausa opcional entre eles.
|
rollingUpgradePolicy
|
RollingUpgradePolicy
|
Os parâmetros de configuração usados durante a execução de uma atualização sem interrupção.
Essa propriedade só tem suporte em Pools com a propriedade virtualMachineConfiguration.
|
UserAccount
Propriedades usadas para criar um usuário em um nó Lote do Azure.
Nome |
Tipo |
Description |
elevationLevel
|
ElevationLevel
|
O nível de elevação da conta de usuário.
nonAdmin – o usuário automático é um usuário padrão sem acesso elevado. admin – o usuário automático é um usuário com acesso elevado e opera com permissões completas de Administrador. O valor padrão é nonAdmin.
|
linuxUserConfiguration
|
LinuxUserConfiguration
|
A configuração de usuário específica do Linux para a conta de usuário.
Essa propriedade será ignorada se especificada em um pool do Windows. Se não for especificado, o usuário será criado com as opções padrão.
|
name
|
string
|
O nome da conta de usuário. Os nomes podem conter caracteres Unicode até um comprimento máximo de 20.
|
password
|
string
|
A senha para a conta de usuário.
|
windowsUserConfiguration
|
WindowsUserConfiguration
|
A configuração de usuário específica do Windows para a conta de usuário.
Essa propriedade só poderá ser especificada se o usuário estiver em um pool do Windows. Se não for especificado e em um pool do Windows, o usuário será criado com as opções padrão.
|
UserAssignedIdentities
A lista de identidades de usuário associadas.
Nome |
Tipo |
Description |
clientId
|
string
|
A ID do cliente da identidade atribuída pelo usuário.
|
principalId
|
string
|
A ID principal da identidade atribuída pelo usuário.
|
UserIdentity
A definição da identidade do usuário sob a qual a tarefa é executada.
Nome |
Tipo |
Description |
autoUser
|
AutoUserSpecification
|
O usuário automático sob o qual a tarefa é executada.
As propriedades userName e autoUser são mutuamente exclusivas; você deve especificar um, mas não ambos.
|
userName
|
string
|
O nome da identidade do usuário sob a qual a tarefa é executada.
As propriedades userName e autoUser são mutuamente exclusivas; você deve especificar um, mas não ambos.
|
VirtualMachineConfiguration
A configuração para nós de computação em um pool com base na infraestrutura de Máquinas Virtuais do Azure.
Nome |
Tipo |
Description |
containerConfiguration
|
ContainerConfiguration
|
A configuração do contêiner para o pool.
Se especificado, a instalação é executada em cada nó no pool para permitir que as tarefas sejam executadas em contêineres. Todas as tarefas regulares e tarefas do gerenciador de trabalho executadas nesse pool devem especificar a propriedade containerSettings e todas as outras tarefas podem especificá-la.
|
dataDisks
|
DataDisk[]
|
A configuração para discos de dados anexados aos nós de computação no pool.
Essa propriedade deve ser especificada se os nós de computação no pool precisarem ter discos de dados vazios anexados a eles.
|
diskEncryptionConfiguration
|
DiskEncryptionConfiguration
|
A configuração de criptografia de disco para o pool.
Se especificado, a criptografia é executada em cada nó no pool durante o provisionamento de nó.
|
extensions
|
VMExtension[]
|
A extensão da máquina virtual para o pool.
Se especificado, as extensões mencionadas nessa configuração serão instaladas em cada nó.
|
imageReference
|
ImageReference
|
Uma referência à imagem do Azure Máquinas Virtuais Marketplace ou à imagem de máquina virtual personalizada a ser usada.
|
licenseType
|
string
|
O tipo de licença local a ser usada ao implantar o sistema operacional.
Isso só se aplica a imagens que contêm o sistema operacional Windows e só deve ser usado quando você mantém licenças locais válidas para os nós que serão implantados. Se omitido, nenhum desconto de licenciamento local será aplicado. Os valores são:
Windows_Server – a licença local é para o Windows Server.
Windows_Client – a licença local é para o Cliente Windows.
|
nodeAgentSkuId
|
string
|
O SKU do agente de nó do Lote a ser provisionado em nós de computação no pool.
O agente de nó do Lote é um programa executado em cada nó no pool e fornece a interface de comando e controle entre o nó e o serviço do Lote. Há diferentes implementações do agente do nó, conhecido como SKUs, para diferentes sistemas operacionais. Você deve especificar um SKU do agente de nó que corresponda à referência de imagem selecionada. Para obter a lista de SKUs do agente de nó com suporte junto com a lista de referências de imagem verificadas, consulte a operação 'Listar SKUs do agente de nó com suporte'.
|
nodePlacementConfiguration
|
NodePlacementConfiguration
|
A configuração de posicionamento do nó para o pool.
Essa configuração especificará regras sobre como os nós no pool serão fisicamente alocados.
|
osDisk
|
OSDisk
|
Configurações para o disco do sistema operacional da Máquina Virtual.
Contém a configuração para configurações do OSDisk efêmero.
|
securityProfile
|
SecurityProfile
|
Especifica as configurações de perfil de segurança para a máquina virtual ou o conjunto de dimensionamento de máquinas virtuais.
Especifica as configurações de perfil de segurança para a máquina virtual ou o conjunto de dimensionamento de máquinas virtuais.
|
serviceArtifactReference
|
ServiceArtifactReference
|
Especifica a ID de referência do artefato de serviço usada para definir a mesma versão de imagem para todas as máquinas virtuais no conjunto de dimensionamento ao usar a versão de imagem 'mais recente'.
A ID de referência do artefato de serviço na forma de /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}
|
windowsConfiguration
|
WindowsConfiguration
|
Configurações do sistema operacional Windows na máquina virtual.
Essa propriedade não deve ser especificada se imageReference especificar uma imagem do sistema operacional Linux.
|
VMExtension
A configuração para extensões de máquina virtual.
Nome |
Tipo |
Description |
autoUpgradeMinorVersion
|
boolean
|
Indica se a extensão deve usar uma versão secundária mais recente se uma estiver disponível no momento da implantação. Após a implantação, no entanto, a extensão não atualizará as versões secundárias, a menos que seja reimplantada, mesmo com essa propriedade definida como verdadeira.
|
enableAutomaticUpgrade
|
boolean
|
Indica se a extensão deve ser atualizada automaticamente pela plataforma se houver uma versão mais recente da extensão disponível.
|
name
|
string
|
O nome da extensão da máquina virtual.
|
protectedSettings
|
object
|
A extensão pode conter protectedSettings ou protectedSettingsFromKeyVault ou nenhuma configuração protegida.
|
provisionAfterExtensions
|
string[]
|
A coleção de nomes de extensão.
Coleção de nomes de extensão após os quais essa extensão precisa ser provisionada.
|
publisher
|
string
|
O nome do editor do manipulador de extensão.
|
settings
|
object
|
Configurações públicas formatadas em JSON para a extensão.
|
type
|
string
|
O tipo das extensões.
|
typeHandlerVersion
|
string
|
A versão do manipulador de script.
|
WindowsConfiguration
Configurações do sistema operacional Windows a serem aplicadas à máquina virtual.
Nome |
Tipo |
Description |
enableAutomaticUpdates
|
boolean
|
Se as atualizações automáticas estão habilitadas na máquina virtual.
Se omitido, o valor padrão será true.
|
WindowsUserConfiguration
Propriedades usadas para criar uma conta de usuário em um nó do Windows.
Nome |
Tipo |
Description |
loginMode
|
LoginMode
|
Modo de logon para usuário
Especifica o modo de logon para o usuário. O valor padrão para pools VirtualMachineConfiguration é o modo interativo e para pools CloudServiceConfiguration é o modo de lote.
|