Partilhar via


Guia de início rápido: criar um balanceador de carga interno para balancear a carga de VMs usando um modelo ARM

Neste início rápido, você aprende a usar um modelo do Azure Resource Manager (modelo ARM) para criar um balanceador de carga interno do Azure. O balanceador de carga interno distribui o tráfego para máquinas virtuais em uma rede virtual localizada no pool de back-end do balanceador de carga. Junto com o balanceador de carga interno, esse modelo cria uma rede virtual, interfaces de rede, um Gateway NAT e uma instância do Azure Bastion.

Diagrama de recursos implantados para um balanceador de carga público padrão.

O uso de um modelo ARM leva menos etapas em comparação com outros métodos de implantação.

Um modelo do Azure Resource Manager é um arquivo JSON (JavaScript Object Notation) que define a infraestrutura e a configuração do seu projeto. O modelo utiliza sintaxe declarativa. Você descreve a implantação pretendida sem escrever a sequência de comandos de programação para criar a implantação.

Se o seu ambiente cumpre os pré-requisitos e se está familiarizado com a utilização de modelos ARM, selecione o botão Implementar no Azure. O modelo é aberto no portal do Azure.

Botão para implantar o modelo do Gerenciador de Recursos no Azure.

Pré-requisitos

Se não tiver uma subscrição do Azure, crie uma conta gratuita antes de começar.

Rever o modelo

O modelo usado neste início rápido é dos Modelos de Início Rápido do Azure.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.27.1.19265",
      "templateHash": "14348520895393914284"
    }
  },
  "parameters": {
    "adminUsername": {
      "type": "string",
      "metadata": {
        "description": "Admin username"
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Admin password"
      }
    },
    "vmNamePrefix": {
      "type": "string",
      "defaultValue": "BackendVM",
      "metadata": {
        "description": "Prefix to use for VM names"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    },
    "vmSize": {
      "type": "string",
      "defaultValue": "Standard_D2s_v3",
      "metadata": {
        "description": "Size of VM"
      }
    },
    "vNetAddressPrefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/16",
      "metadata": {
        "description": "Virtual network address prefix"
      }
    },
    "vNetSubnetAddressPrefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/24",
      "metadata": {
        "description": "Backend subnet address prefix"
      }
    },
    "vNetBastionSubnetAddressPrefix": {
      "type": "string",
      "defaultValue": "10.0.2.0/24",
      "metadata": {
        "description": "Bastion subnet address prefix"
      }
    },
    "lbPublicIPAddress": {
      "type": "string",
      "defaultValue": "10.0.0.6",
      "metadata": {
        "description": "Public IP address of load balancer"
      }
    }
  },
  "variables": {
    "natGatewayName": "lb-nat-gateway",
    "natGatewayPublicIPAddressName": "lb-nat-gateway-ip",
    "vNetName": "lb-vnet",
    "vNetSubnetName": "backend-subnet",
    "storageAccountType": "Standard_LRS",
    "storageAccountName": "[uniqueString(resourceGroup().id)]",
    "loadBalancerName": "internal-lb",
    "networkInterfaceName": "lb-nic",
    "numberOfInstances": 2,
    "lbSkuName": "Standard",
    "bastionName": "lb-bastion",
    "bastionSubnetName": "AzureBastionSubnet",
    "bastionPublicIPAddressName": "lb-bastion-ip"
  },
  "resources": [
    {
      "type": "Microsoft.Network/natGateways",
      "apiVersion": "2023-09-01",
      "name": "[variables('natGatewayName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {
        "idleTimeoutInMinutes": 4,
        "publicIpAddresses": [
          {
            "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('natGatewayPublicIPAddressName'))]"
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('natGatewayPublicIPAddressName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2023-09-01",
      "name": "[variables('natGatewayPublicIPAddressName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static",
        "idleTimeoutInMinutes": 4
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "apiVersion": "2023-09-01",
      "name": "[variables('vNetName')]",
      "location": "[parameters('location')]",
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[parameters('vNetAddressPrefix')]"
          ]
        }
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks/subnets",
      "apiVersion": "2023-09-01",
      "name": "[format('{0}/{1}', variables('vNetName'), variables('bastionSubnetName'))]",
      "properties": {
        "addressPrefix": "[parameters('vNetBastionSubnetAddressPrefix')]"
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/virtualNetworks/subnets",
      "apiVersion": "2023-09-01",
      "name": "[format('{0}/{1}', variables('vNetName'), variables('vNetSubnetName'))]",
      "properties": {
        "addressPrefix": "[parameters('vNetSubnetAddressPrefix')]",
        "natGateway": {
          "id": "[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/bastionHosts",
      "apiVersion": "2023-09-01",
      "name": "[variables('bastionName')]",
      "location": "[parameters('location')]",
      "properties": {
        "ipConfigurations": [
          {
            "name": "IpConf",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('bastionPublicIPAddressName'))]"
              },
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('bastionSubnetName'))]"
              }
            }
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('bastionPublicIPAddressName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('bastionSubnetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2023-09-01",
      "name": "[variables('bastionPublicIPAddressName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('lbSkuName')]"
      },
      "properties": {
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static"
      }
    },
    {
      "copy": {
        "name": "networkInterface",
        "count": "[length(range(0, variables('numberOfInstances')))]"
      },
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2023-09-01",
      "name": "[format('{0}{1}', variables('networkInterfaceName'), range(0, variables('numberOfInstances'))[copyIndex()])]",
      "location": "[parameters('location')]",
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
              },
              "loadBalancerBackendAddressPools": [
                {
                  "id": "[resourceId('Microsoft.Network/loadBalancers/backendAddressPools', variables('loadBalancerName'), 'BackendPool1')]"
                }
              ]
            }
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/loadBalancers', variables('loadBalancerName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/loadBalancers",
      "apiVersion": "2023-09-01",
      "name": "[variables('loadBalancerName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {
        "frontendIPConfigurations": [
          {
            "properties": {
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
              },
              "privateIPAddress": "[parameters('lbPublicIPAddress')]",
              "privateIPAllocationMethod": "Static"
            },
            "name": "LoadBalancerFrontend"
          }
        ],
        "backendAddressPools": [
          {
            "name": "BackendPool1"
          }
        ],
        "loadBalancingRules": [
          {
            "properties": {
              "frontendIPConfiguration": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/frontendIpConfigurations', variables('loadBalancerName'), 'LoadBalancerFrontend')]"
              },
              "backendAddressPool": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/backendAddressPools', variables('loadBalancerName'), 'BackendPool1')]"
              },
              "probe": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/probes', variables('loadBalancerName'), 'lbprobe')]"
              },
              "protocol": "Tcp",
              "frontendPort": 80,
              "backendPort": 80,
              "idleTimeoutInMinutes": 15
            },
            "name": "lbrule"
          }
        ],
        "probes": [
          {
            "properties": {
              "protocol": "Tcp",
              "port": 80,
              "intervalInSeconds": 15,
              "numberOfProbes": 2
            },
            "name": "lbprobe"
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
      ]
    },
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('storageAccountType')]"
      },
      "kind": "StorageV2"
    },
    {
      "copy": {
        "name": "vm",
        "count": "[length(range(0, variables('numberOfInstances')))]"
      },
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2023-09-01",
      "name": "[format('{0}{1}', parameters('vmNamePrefix'), range(0, variables('numberOfInstances'))[copyIndex()])]",
      "location": "[parameters('location')]",
      "properties": {
        "hardwareProfile": {
          "vmSize": "[parameters('vmSize')]"
        },
        "osProfile": {
          "computerName": "[format('{0}{1}', parameters('vmNamePrefix'), range(0, variables('numberOfInstances'))[copyIndex()])]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]"
        },
        "storageProfile": {
          "imageReference": {
            "publisher": "MicrosoftWindowsServer",
            "offer": "WindowsServer",
            "sku": "2019-Datacenter",
            "version": "latest"
          },
          "osDisk": {
            "createOption": "FromImage"
          }
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', format('{0}{1}', variables('networkInterfaceName'), range(0, variables('numberOfInstances'))[range(0, variables('numberOfInstances'))[copyIndex()]]))]"
            }
          ]
        },
        "diagnosticsProfile": {
          "bootDiagnostics": {
            "enabled": true,
            "storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2023-01-01').primaryEndpoints.blob]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkInterfaces', format('{0}{1}', variables('networkInterfaceName'), range(0, variables('numberOfInstances'))[range(0, variables('numberOfInstances'))[copyIndex()]]))]",
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    }
  ],
  "outputs": {
    "location": {
      "type": "string",
      "value": "[parameters('location')]"
    },
    "name": {
      "type": "string",
      "value": "[variables('loadBalancerName')]"
    },
    "resourceGroupName": {
      "type": "string",
      "value": "[resourceGroup().name]"
    },
    "resourceId": {
      "type": "string",
      "value": "[resourceId('Microsoft.Network/loadBalancers', variables('loadBalancerName'))]"
    }
  }
}

Vários recursos do Azure foram definidos no modelo:

Para encontrar mais modelos relacionados ao Balanceador de Carga do Azure, consulte Modelos de início rápido do Azure.

Implementar o modelo

Nesta etapa, você implanta o modelo usando o Azure PowerShell com o [New-AzResourceGroupDeployment](/powershell/module/az.resources/new-azresourcegroupdeployment) comando.

  1. Selecione Experimente no bloco de código a seguir para abrir o Azure Cloud Shell e siga as instruções para entrar no Azure.

  2. Implante o arquivo Bicep usando a CLI do Azure ou o Azure PowerShell.

     echo "Enter a project name with 12 or less letters or numbers that is used to generate Azure resource names"
     read projectName
     echo "Enter the location (i.e. centralus)"
     read location
    
     resourceGroupName="${projectName}rg"
     templateUri="https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/internal-loadbalancer-create/azuredeploy.json"
    
     az group create --name $resourceGroupName --location $location
     az deployment group create --resource-group $resourceGroupName --template-uri $templateUri --name $projectName --parameters location=$location
    
     read -p "Press [ENTER] to continue."
    

    Você será solicitado a inserir os seguintes valores:

    • projectName: usado para gerar nomes de recursos.
    • adminUsername: nome de usuário do administrador da máquina virtual.
    • adminPassword: senha de administrador da máquina virtual.

Leva cerca de 10 minutos para implantar o modelo.

O Azure PowerShell ou a CLI do Azure é usada para implantar o modelo. Você também pode usar o portal do Azure e a API REST. Para aprender outros métodos de implantação, consulte Implantar modelos.

Rever os recursos implementados

Use a CLI do Azure ou o Azure PowerShell para listar os recursos implantados no grupo de recursos com os seguintes comandos:

az resource list --resource-group $resourceGroupName

Clean up resources (Limpar recursos)

Quando não for mais necessário, use a CLI do Azure ou o Azure PowerShell para excluir o grupo de recursos e seus recursos com os seguintes comandos:

Remove-AzResourceGroup -Name "${projectName}rg"

Próximos passos

Para obter um tutorial passo a passo que o orienta pelo processo de criação de um modelo, consulte: