Criar máquinas virtuais em um conjunto de escala usando a CLI do Azure
Este artigo descreve como usar a CLI do Azure para criar um Conjunto de Dimensionamento de Máquina Virtual.
Certifique-se de que instalou a CLI do Azure mais recente e que iniciou sessão numa conta do Azure com az login.
Iniciar o Azure Cloud Shell
O Azure Cloud Shell é um shell interativo gratuito que pode utilizar para executar os passos neste artigo. Tem as ferramentas comuns do Azure pré-instaladas e configuradas para utilização com a sua conta.
Para abrir o Cloud Shell, selecione Open Cloud Shell no canto superior direito de um bloco de código. Também pode iniciar o Cloud Shell num separador do browser separado ao aceder a https://shell.azure.com/cli. Selecione Copiar para copiar os blocos de código, cole-o no Cloud Shell e prima Enter para executá-lo.
Definir variáveis de ambiente
Defina as variáveis de ambiente da seguinte forma.
export RANDOM_ID="$(openssl rand -hex 3)"
export MY_RESOURCE_GROUP_NAME="myVMSSResourceGroup$RANDOM_ID"
export REGION=EastUS
export MY_VMSS_NAME="myVMSS$RANDOM_ID"
export MY_USERNAME=azureuser
export MY_VM_IMAGE="Ubuntu2204"
export MY_VNET_NAME="myVNet$RANDOM_ID"
export NETWORK_PREFIX="$(($RANDOM % 254 + 1))"
export MY_VNET_PREFIX="10.$NETWORK_PREFIX.0.0/16"
export MY_VM_SN_NAME="myVMSN$RANDOM_ID"
export MY_VM_SN_PREFIX="10.$NETWORK_PREFIX.0.0/24"
export MY_APPGW_SN_NAME="myAPPGWSN$RANDOM_ID"
export MY_APPGW_SN_PREFIX="10.$NETWORK_PREFIX.1.0/24"
export MY_APPGW_NAME="myAPPGW$RANDOM_ID"
export MY_APPGW_PUBLIC_IP_NAME="myAPPGWPublicIP$RANDOM_ID"
Criar um grupo de recursos
Um grupo de recursos é um contentor lógico no qual os recursos do Azure são implementados e geridos. Todos os recursos devem ser colocados em um grupo de recursos. O comando a seguir cria um grupo de recursos com os parâmetros $MY_RESOURCE_GROUP_NAME e $REGION definidos anteriormente.
az group create --name $MY_RESOURCE_GROUP_NAME --location $REGION -o JSON
Resultados:
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx",
"location": "eastus",
"managedBy": null,
"name": "myVMSSResourceGroupxxxxxx",
"properties": {
"provisioningState": "Succeeded"
},
"tags": null,
"type": "Microsoft.Resources/resourceGroups"
}
Criar recursos de rede
Agora você criará recursos de rede. Nesta etapa, você criará uma rede virtual, uma sub-rede 1 para o Application Gateway e uma sub-rede para VMs. Você também precisa ter um IP público para anexar seu Application Gateway para acessar seu aplicativo Web da Internet.
Criar rede virtual e sub-rede
az network vnet create --name $MY_VNET_NAME --resource-group $MY_RESOURCE_GROUP_NAME --location $REGION --address-prefix $MY_VNET_PREFIX --subnet-name $MY_VM_SN_NAME --subnet-prefix $MY_VM_SN_PREFIX -o JSON
Resultados:
{
"newVNet": {
"addressSpace": {
"addressPrefixes": [
"10.X.0.0/16"
]
},
"enableDdosProtection": false,
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxxx",
"location": "eastus",
"name": "myVNetxxxxxx",
"provisioningState": "Succeeded",
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"resourceGuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"subnets": [
{
"addressPrefix": "10.X.0.0/24",
"delegations": [],
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxxx/subnets/myVMSNxxxxxx",
"name": "myVMSNxxxxxx",
"privateEndpointNetworkPolicies": "Disabled",
"privateLinkServiceNetworkPolicies": "Enabled",
"provisioningState": "Succeeded",
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/virtualNetworks/subnets"
}
],
"type": "Microsoft.Network/virtualNetworks",
"virtualNetworkPeerings": []
}
}
Criar recursos do Application Gateway
O Gateway de Aplicativo do Azure requer uma sub-rede dedicada em sua rede virtual. O comando a seguir cria uma sub-rede chamada $MY_APPGW_SN_NAME com um prefixo de endereço especificado chamado $MY_APPGW_SN_PREFIX em sua rede virtual $MY_VNET_NAME.
az network vnet subnet create --name $MY_APPGW_SN_NAME --resource-group $MY_RESOURCE_GROUP_NAME --vnet-name $MY_VNET_NAME --address-prefix $MY_APPGW_SN_PREFIX -o JSON
Resultados:
{
"addressPrefix": "10.66.1.0/24",
"delegations": [],
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxxx/subnets/myAPPGWSNxxxxxx",
"name": "myAPPGWSNxxxxxx",
"privateEndpointNetworkPolicies": "Disabled",
"privateLinkServiceNetworkPolicies": "Enabled",
"provisioningState": "Succeeded",
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/virtualNetworks/subnets"
}
O comando a seguir cria um IPv4 padrão, redundante de zona, estático e público em seu grupo de recursos.
az network public-ip create --resource-group $MY_RESOURCE_GROUP_NAME --name $MY_APPGW_PUBLIC_IP_NAME --sku Standard --location $REGION --allocation-method static --version IPv4 --zone 1 2 3 -o JSON
Resultados:
{
"publicIp": {
"ddosSettings": {
"protectionMode": "VirtualNetworkInherited"
},
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/publicIPAddresses//myAPPGWPublicIPxxxxxx",
"idleTimeoutInMinutes": 4,
"ipAddress": "X.X.X.X",
"ipTags": [],
"location": "eastus",
"name": "/myAPPGWPublicIPxxxxxx",
"provisioningState": "Succeeded",
"publicIPAddressVersion": "IPv4",
"publicIPAllocationMethod": "Static",
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"resourceGuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"sku": {
"name": "Standard",
"tier": "Regional"
},
"type": "Microsoft.Network/publicIPAddresses",
"zones": [
"1",
"2",
"3"
]
}
}
Nesta etapa, você cria um Gateway de Aplicativo que será integrado ao seu Conjunto de Dimensionamento de Máquina Virtual. Este exemplo cria um Application Gateway redundante de zona com Standard_v2 SKU e habilita a comunicação Http para o Application Gateway. O IP público $MY_APPGW_PUBLIC_IP_NAME criado na etapa anterior é anexado ao Application Gateway.
az network application-gateway create --name $MY_APPGW_NAME --location $REGION --resource-group $MY_RESOURCE_GROUP_NAME --vnet-name $MY_VNET_NAME --subnet $MY_APPGW_SN_NAME --capacity 2 --zones 1 2 3 --sku Standard_v2 --http-settings-cookie-based-affinity Disabled --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --public-ip-address $MY_APPGW_PUBLIC_IP_NAME --priority 1001 -o JSON
{
"applicationGateway": {
"backendAddressPools": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/backendAddressPools/appGatewayBackendPool",
"name": "appGatewayBackendPool",
"properties": {
"backendAddresses": [],
"provisioningState": "Succeeded",
"requestRoutingRules": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/requestRoutingRules/rule1",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
]
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/backendAddressPools"
}
],
"backendHttpSettingsCollection": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/backendHttpSettingsCollection/appGatewayBackendHttpSettings",
"name": "appGatewayBackendHttpSettings",
"properties": {
"connectionDraining": {
"drainTimeoutInSec": 1,
"enabled": false
},
"cookieBasedAffinity": "Disabled",
"pickHostNameFromBackendAddress": false,
"port": 80,
"protocol": "Http",
"provisioningState": "Succeeded",
"requestRoutingRules": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/requestRoutingRules/rule1",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"requestTimeout": 30
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/backendHttpSettingsCollection"
}
],
"backendSettingsCollection": [],
"frontendIPConfigurations": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/frontendIPConfigurations/appGatewayFrontendIP",
"name": "appGatewayFrontendIP",
"properties": {
"httpListeners": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/httpListeners/appGatewayHttpListener",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"privateIPAllocationMethod": "Dynamic",
"provisioningState": "Succeeded",
"publicIPAddress": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/publicIPAddresses/myAPPGWPublicIPxxxxxx",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/frontendIPConfigurations"
}
],
"frontendPorts": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/frontendPorts/appGatewayFrontendPort",
"name": "appGatewayFrontendPort",
"properties": {
"httpListeners": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/httpListeners/appGatewayHttpListener",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"port": 80,
"provisioningState": "Succeeded"
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/frontendPorts"
}
],
"gatewayIPConfigurations": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/gatewayIPConfigurations/appGatewayFrontendIP",
"name": "appGatewayFrontendIP",
"properties": {
"provisioningState": "Succeeded",
"subnet": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxxx/subnets/myAPPGWSNxxxxxx",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/gatewayIPConfigurations"
}
],
"httpListeners": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/httpListeners/appGatewayHttpListener",
"name": "appGatewayHttpListener",
"properties": {
"frontendIPConfiguration": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/frontendIPConfigurations/appGatewayFrontendIP",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
},
"frontendPort": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/frontendPorts/appGatewayFrontendPort",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
},
"hostNames": [],
"protocol": "Http",
"provisioningState": "Succeeded",
"requestRoutingRules": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/requestRoutingRules/rule1",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"requireServerNameIndication": false
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/httpListeners"
}
],
"listeners": [],
"loadDistributionPolicies": [],
"operationalState": "Running",
"privateEndpointConnections": [],
"privateLinkConfigurations": [],
"probes": [],
"provisioningState": "Succeeded",
"redirectConfigurations": [],
"requestRoutingRules": [
{
"etag": "W/\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/requestRoutingRules/rule1",
"name": "rule1",
"properties": {
"backendAddressPool": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/backendAddressPools/appGatewayBackendPool",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
},
"backendHttpSettings": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/backendHttpSettingsCollection/appGatewayBackendHttpSettings",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
},
"httpListener": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxxxx/httpListeners/appGatewayHttpListener",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
},
"priority": 1001,
"provisioningState": "Succeeded",
"ruleType": "Basic"
},
"resourceGroup": "myVMSSResourceGroupxxxxxx",
"type": "Microsoft.Network/applicationGateways/requestRoutingRules"
}
],
"resourceGuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"rewriteRuleSets": [],
"routingRules": [],
"sku": {
"capacity": 2,
"family": "Generation_1",
"name": "Standard_v2",
"tier": "Standard_v2"
},
"sslCertificates": [],
"sslProfiles": [],
"trustedClientCertificates": [],
"trustedRootCertificates": [],
"urlPathMaps": []
}
}
Criar um Conjunto de Dimensionamento de Máquinas Virtuais
Importante
A partir de novembro de 2023, os conjuntos de dimensionamento de VM criados usando o PowerShell e a CLI do Azure assumirão como padrão o Modo de Orquestração Flexível se nenhum modo de orquestração for especificado. Para obter mais informações sobre essa alteração e quais ações você deve tomar, vá para Breaking Change for VMSS PowerShell/CLI Customers - Microsoft Community Hub
Agora crie um conjunto de escala de máquina virtual com az vmss create. O exemplo a seguir cria um conjunto de escala redundante de zona com uma contagem de instâncias de 2 com IP público na sub-rede $MY_VM_SN_NAME dentro do seu grupo de recursos $MY_RESOURCE_GROUP_NAME, integra o Application Gateway e gera chaves SSH. Certifique-se de salvar as chaves SSH se precisar fazer login em suas VMs via ssh.
az vmss create --name $MY_VMSS_NAME --resource-group $MY_RESOURCE_GROUP_NAME --image $MY_VM_IMAGE --admin-username $MY_USERNAME --generate-ssh-keys --public-ip-per-vm --orchestration-mode Uniform --instance-count 2 --zones 1 2 3 --vnet-name $MY_VNET_NAME --subnet $MY_VM_SN_NAME --vm-sku Standard_DS2_v2 --upgrade-policy-mode Automatic --app-gateway $MY_APPGW_NAME --backend-pool-name appGatewayBackendPool -o JSON
Resultados:
{
"vmss": {
"doNotRunExtensionsOnOverprovisionedVMs": false,
"orchestrationMode": "Uniform",
"overprovision": true,
"platformFaultDomainCount": 1,
"provisioningState": "Succeeded",
"singlePlacementGroup": false,
"timeCreated": "20xx-xx-xxTxx:xx:xx.xxxxxx+00:00",
"uniqueId": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
"upgradePolicy": {
"mode": "Automatic",
"rollingUpgradePolicy": {
"maxBatchInstancePercent": 20,
"maxSurge": false,
"maxUnhealthyInstancePercent": 20,
"maxUnhealthyUpgradedInstancePercent": 20,
"pauseTimeBetweenBatches": "PT0S",
"rollbackFailedInstancesOnPolicyBreach": false
}
},
"virtualMachineProfile": {
"networkProfile": {
"networkInterfaceConfigurations": [
{
"name": "myvmsa53cNic",
"properties": {
"disableTcpStateTracking": false,
"dnsSettings": {
"dnsServers": []
},
"enableAcceleratedNetworking": false,
"enableIPForwarding": false,
"ipConfigurations": [
{
"name": "myvmsa53cIPConfig",
"properties": {
"applicationGatewayBackendAddressPools": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGW7xxxxx/backendAddressPools/appGatewayBackendPool",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"privateIPAddressVersion": "IPv4",
"publicIPAddressConfiguration": {
"name": "instancepublicip",
"properties": {
"idleTimeoutInMinutes": 10,
"ipTags": [],
"publicIPAddressVersion": "IPv4"
}
},
"subnet": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxx/subnets/myVMSN7xxxxx",
"resourceGroup": "myVMSSResourceGroupxxxxxxx"
}
}
}
],
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "azureuser",
"allowExtensionOperations": true,
"computerNamePrefix": "myvmsa53c",
"linuxConfiguration": {
"disablePasswordAuthentication": true,
"enableVMAgentPlatformUpdates": false,
"provisionVMAgent": true,
"ssh": {
"publicKeys": [
{
"keyData": "ssh-rsa xxxxxxxx",
"path": "/home/azureuser/.ssh/authorized_keys"
}
]
}
},
"requireGuestProvisionSignal": true,
"secrets": []
},
"storageProfile": {
"diskControllerType": "SCSI",
"imageReference": {
"offer": "0001-com-ubuntu-server-jammy",
"publisher": "Canonical",
"sku": "22_04-lts-gen2",
"version": "latest"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"osType": "Linux"
}
},
"timeCreated": "20xx-xx-xxTxx:xx:xx.xxxxxx+00:00"
},
"zoneBalance": false
}
}
Instalar ngnix com extensões de Conjuntos de Escala de Máquina Virtual
O comando a seguir usa a extensão Conjuntos de Escala de Máquina Virtual para executar um script personalizado que instala o ngnix e publica uma página que mostra o nome do host da Máquina Virtual que suas solicitações HTTP atingem.
az vmss extension set --publisher Microsoft.Azure.Extensions --version 2.0 --name CustomScript --resource-group $MY_RESOURCE_GROUP_NAME --vmss-name $MY_VMSS_NAME --settings '{ "fileUris": ["https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/automate_nginx.sh"], "commandToExecute": "./automate_nginx.sh" }' -o JSON
Resultados:
{
"additionalCapabilities": null,
"automaticRepairsPolicy": null,
"constrainedMaximumCapacity": null,
"doNotRunExtensionsOnOverprovisionedVMs": false,
"extendedLocation": null,
"hostGroup": null,
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSxxxxx",
"identity": null,
"location": "eastus",
"name": "myVMSSxxxx",
"orchestrationMode": "Uniform",
"overprovision": true,
"plan": null,
"platformFaultDomainCount": 1,
"priorityMixPolicy": null,
"provisioningState": "Succeeded",
"proximityPlacementGroup": null,
"resourceGroup": "myVMSSResourceGroupxxxxx",
"scaleInPolicy": null,
"singlePlacementGroup": false,
"sku": {
"capacity": 2,
"name": "Standard_DS2_v2",
"tier": "Standard"
},
"spotRestorePolicy": null,
"tags": {},
"timeCreated": "20xx-xx-xxTxx:xx:xx.xxxxxx+00:00",
"type": "Microsoft.Compute/virtualMachineScaleSets",
"uniqueId": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
"upgradePolicy": {
"automaticOsUpgradePolicy": null,
"mode": "Automatic",
"rollingUpgradePolicy": {
"enableCrossZoneUpgrade": null,
"maxBatchInstancePercent": 20,
"maxSurge": false,
"maxUnhealthyInstancePercent": 20,
"maxUnhealthyUpgradedInstancePercent": 20,
"pauseTimeBetweenBatches": "PT0S",
"prioritizeUnhealthyInstances": null,
"rollbackFailedInstancesOnPolicyBreach": false
}
},
"virtualMachineProfile": {
"applicationProfile": null,
"billingProfile": null,
"capacityReservation": null,
"diagnosticsProfile": null,
"evictionPolicy": null,
"extensionProfile": {
"extensions": [
{
"autoUpgradeMinorVersion": true,
"enableAutomaticUpgrade": null,
"forceUpdateTag": null,
"id": null,
"name": "CustomScript",
"protectedSettings": null,
"protectedSettingsFromKeyVault": null,
"provisionAfterExtensions": null,
"provisioningState": null,
"publisher": "Microsoft.Azure.Extensions",
"settings": {
"commandToExecute": "./automate_nginx.sh",
"fileUris": [
"https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/automate_nginx.sh"
]
},
"suppressFailures": null,
"type": null,
"typeHandlerVersion": "2.0",
"typePropertiesType": "CustomScript"
}
],
"extensionsTimeBudget": null
},
"hardwareProfile": null,
"licenseType": null,
"networkProfile": {
"healthProbe": null,
"networkApiVersion": null,
"networkInterfaceConfigurations": [
{
"deleteOption": null,
"disableTcpStateTracking": false,
"dnsSettings": {
"dnsServers": []
},
"enableAcceleratedNetworking": false,
"enableFpga": null,
"enableIpForwarding": false,
"ipConfigurations": [
{
"applicationGatewayBackendAddressPools": [
{
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/Microsoft.Network/applicationGateways/myAPPGWxxxx/backendAddressPools/appGatewayBackendPool",
"resourceGroup": "myVMSSResourceGroupxxxxxx"
}
],
"applicationSecurityGroups": null,
"loadBalancerBackendAddressPools": null,
"loadBalancerInboundNatPools": null,
"name": "myvmsdxxxIPConfig",
"primary": null,
"privateIpAddressVersion": "IPv4",
"publicIpAddressConfiguration": null,
"subnet": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/Microsoft.Network/virtualNetworks/myVNetxxxxx/subnets/myVMSNxxxxx",
"resourceGroup": "myVMSSResourceGroupaxxxxx"
}
}
],
"name": "myvmsxxxxxx",
"networkSecurityGroup": null,
"primary": true
}
]
},
"osProfile": {
"adminPassword": null,
"adminUsername": "azureuser",
"allowExtensionOperations": true,
"computerNamePrefix": "myvmsdxxx",
"customData": null,
"linuxConfiguration": {
"disablePasswordAuthentication": true,
"enableVmAgentPlatformUpdates": false,
"patchSettings": null,
"provisionVmAgent": true,
"ssh": {
"publicKeys": [
{
"keyData": "ssh-rsa xxxxxxxx",
"path": "/home/azureuser/.ssh/authorized_keys"
}
]
}
},
"requireGuestProvisionSignal": true,
"secrets": [],
"windowsConfiguration": null
},
"priority": null,
"scheduledEventsProfile": null,
"securityPostureReference": null,
"securityProfile": null,
"serviceArtifactReference": null,
"storageProfile": {
"dataDisks": null,
"diskControllerType": "SCSI",
"imageReference": {
"communityGalleryImageId": null,
"exactVersion": null,
"id": null,
"offer": "0001-com-ubuntu-server-jammy",
"publisher": "Canonical",
"sharedGalleryImageId": null,
"sku": "22_04-lts-gen2",
"version": "latest"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"deleteOption": null,
"diffDiskSettings": null,
"diskSizeGb": 30,
"image": null,
"managedDisk": {
"diskEncryptionSet": null,
"securityProfile": null,
"storageAccountType": "Premium_LRS"
},
"name": null,
"osType": "Linux",
"vhdContainers": null,
"writeAcceleratorEnabled": null
}
},
"userData": null
},
"zoneBalance": false,
"zones": [
"1",
"2",
"3"
]
}
Definir um perfil de dimensionamento automático
Para habilitar o dimensionamento automático em um conjunto de escalas, primeiro defina um perfil de dimensionamento automático. Este perfil define a capacidade predefinida, máxima e mínima do conjunto de dimensionamento. Esses limites permitem controlar o custo não criando continuamente instâncias de VM e equilibrar o desempenho aceitável com um número mínimo de instâncias que permanecem em um evento de expansão. O exemplo a seguir define o padrão, a capacidade mínima de duas instâncias de VM e uma capacidade máxima de 10:
az monitor autoscale create --resource-group $MY_RESOURCE_GROUP_NAME --resource $MY_VMSS_NAME --resource-type Microsoft.Compute/virtualMachineScaleSets --name autoscale --min-count 2 --max-count 10 --count 2
Resultados:
{
"enabled": true,
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxx/providers/microsoft.insights/autoscalesettings/autoscale",
"location": "eastus",
"name": "autoscale",
"namePropertiesName": "autoscale",
"notifications": [
{
"email": {
"customEmails": [],
"sendToSubscriptionAdministrator": false,
"sendToSubscriptionCoAdministrators": false
},
"webhooks": []
}
],
"predictiveAutoscalePolicy": {
"scaleLookAheadTime": null,
"scaleMode": "Disabled"
},
"profiles": [
{
"capacity": {
"default": "2",
"maximum": "10",
"minimum": "2"
},
"fixedDate": null,
"name": "default",
"recurrence": null,
"rules": []
}
],
"resourceGroup": "myVMSSResourceGroupxxxxx",
"systemData": null,
"tags": {},
"targetResourceLocation": null,
"targetResourceUri": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSxxxxxx",
"type": "Microsoft.Insights/autoscaleSettings"
}
Criar uma regra para dimensionamento automático para aumentar horizontalmente
O comando a seguir cria uma regra que aumenta o número de instâncias de VM em uma escala definida quando a carga média da CPU é maior que 70% durante um período de 5 minutos. Quando a regra é acionada, o número de instâncias de VM aumenta em três.
az monitor autoscale rule create --resource-group $MY_RESOURCE_GROUP_NAME --autoscale-name autoscale --condition "Percentage CPU > 70 avg 5m" --scale out 3
Resultados:
{
"metricTrigger": {
"dimensions": [],
"dividePerInstance": null,
"metricName": "Percentage CPU",
"metricNamespace": null,
"metricResourceLocation": null,
"metricResourceUri": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSxxxxxx",
"operator": "GreaterThan",
"statistic": "Average",
"threshold": "70",
"timeAggregation": "Average",
"timeGrain": "PT1M",
"timeWindow": "PT5M"
},
"scaleAction": {
"cooldown": "PT5M",
"direction": "Increase",
"type": "ChangeCount",
"value": "3"
}
}
Criar uma regra para dimensionamento automático, para reduzir horizontalmente
Crie outra regra com az monitor autoscale rule create
isso diminui o número de instâncias de VM em uma escala definida quando a carga média da CPU cai abaixo de 30% durante um período de 5 minutos. O exemplo seguinte define a regra para reduzir horizontalmente o número de instâncias de VM para um.
az monitor autoscale rule create --resource-group $MY_RESOURCE_GROUP_NAME --autoscale-name autoscale --condition "Percentage CPU < 30 avg 5m" --scale in 1
Resultados:
{
"metricTrigger": {
"dimensions": [],
"dividePerInstance": null,
"metricName": "Percentage CPU",
"metricNamespace": null,
"metricResourceLocation": null,
"metricResourceUri": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myVMSSResourceGroupxxxxxx/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSxxxxxx",
"operator": "LessThan",
"statistic": "Average",
"threshold": "30",
"timeAggregation": "Average",
"timeGrain": "PT1M",
"timeWindow": "PT5M"
},
"scaleAction": {
"cooldown": "PT5M",
"direction": "Decrease",
"type": "ChangeCount",
"value": "1"
}
}
Testar a página
O comando a seguir mostra o IP público do seu Application Gateway. Cole o endereço IP em uma página do navegador para teste.
az network public-ip show --resource-group $MY_RESOURCE_GROUP_NAME --name $MY_APPGW_PUBLIC_IP_NAME --query [ipAddress] --output tsv
Limpar recursos (opcional)
Para evitar cobranças do Azure, você deve limpar recursos desnecessários. Quando você não precisar mais do seu conjunto de escala e outros recursos, exclua o grupo de recursos e todos os seus recursos com az group delete. O parâmetro --no-wait
devolve o controlo à linha de comandos, sem aguardar a conclusão da operação. O --yes
parâmetro confirma que você deseja excluir os recursos sem outro prompt para fazê-lo. Este tutorial limpa recursos para você.