如何使用 Azure Resource Manager 模板创建 Linux 虚拟机How to create a Linux virtual machine with Azure Resource Manager templates

了解如何使用 Azure 资源管理器模板以及 Azure 本地 Shell 中的 Azure CLI 来创建 Linux 虚拟机 (VM)。Learn how to create a Linux virtual machine (VM) by using an Azure Resource Manager template and the Azure CLI from the Azure local Shell. 若要创建 Windows 虚拟机,请参阅通过资源管理器模板创建 Windows 虚拟机To create a Windows virtual machine, see Create a Windows virtual machine from a Resource Manager template.

模板概述Templates overview

Azure Resource Manager 模板是 JSON 文件,其中定义了 Azure 解决方案的基础结构和配置。Azure Resource Manager templates are JSON files that define the infrastructure and configuration of your Azure solution. 使用模板可以在解决方案的整个生命周期内重复部署该解决方案,确保以一致的状态部署资源。By using a template, you can repeatedly deploy your solution throughout its lifecycle and have confidence your resources are deployed in a consistent state. 若要详细了解模板的格式以及如何构造模板,请参阅快速入门:使用 Azure 门户创建和部署 Azure 资源管理器模板To learn more about the format of the template and how you construct it, see Quickstart: Create and deploy Azure Resource Manager templates by using the Azure portal. 若要查看资源类型的 JSON 语法,请参阅定义 Azure Resource Manager 模板中的资源To view the JSON syntax for resources types, see Define resources in Azure Resource Manager templates.

创建虚拟机Create a virtual machine

创建 Azure 虚拟机通常包括两个步骤:Creating an Azure virtual machine usually includes two steps:

  1. 创建资源组。Create a resource group. Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container into which Azure resources are deployed and managed. 必须在创建虚拟机前创建资源组。A resource group must be created before a virtual machine.
  2. 创建虚拟机。Create a virtual machine.

以下示例通过 Azure 快速入门模板创建 VM。The following example creates a VM from an Azure Quickstart template. 此部署仅允许 SSH 身份验证。Only SSH authentication is allowed for this deployment. 出现提示时,提供自己的 SSH 公钥的值,例如 ~/.ssh/id_rsa.pub 的内容。When prompted, provide the value of your own SSH public key, such as the contents of ~/.ssh/id_rsa.pub. 如果需要创建 SSH 密钥对,请参阅如何为 Azure 中的 Linux VM 创建和使用 SSH 密钥对If you need to create an SSH key pair, see How to create and use an SSH key pair for Linux VMs in Azure. 下面是该模板的副本:Here is a copy of the template:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "projectName": {
      "type": "string",
      "metadata": {
        "description": "Specifies a name for generating resource names."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specifies the location for all resources."
      }
    },
    "adminUsername": {
      "type": "string",
      "metadata": {
        "description": "Specifies a username for the Virtual Machine."
      }
    },
    "adminPublicKey": {
      "type": "string",
      "metadata": {
        "description": "Specifies the SSH rsa public key file as a string. Use \"ssh-keygen -t rsa -b 2048\" to generate your SSH key pairs."
      }
    }
  },
  "variables": {
    "vNetName": "[concat(parameters('projectName'), '-vnet')]",
    "vNetAddressPrefixes": "10.0.0.0/16",
    "vNetSubnetName": "default",
    "vNetSubnetAddressPrefix": "10.0.0.0/24",
    "vmName": "[concat(parameters('projectName'), '-vm')]",
    "publicIPAddressName": "[concat(parameters('projectName'), '-ip')]",
    "networkInterfaceName": "[concat(parameters('projectName'), '-nic')]",
    "networkSecurityGroupName": "[concat(parameters('projectName'), '-nsg')]",
    "networkSecurityGroupName2": "[concat(variables('vNetSubnetName'), '-nsg')]"
  },
  "resources": [
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2018-11-01",
      "name": "[variables('networkSecurityGroupName')]",
      "location": "[parameters('location')]",
      "properties": {
        "securityRules": [
          {
            "name": "ssh_rule",
            "properties": {
              "description": "Locks inbound down to ssh default port 22.",
              "protocol": "Tcp",
              "sourcePortRange": "*",
              "destinationPortRange": "22",
              "sourceAddressPrefix": "*",
              "destinationAddressPrefix": "*",
              "access": "Allow",
              "priority": 123,
              "direction": "Inbound"
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2018-11-01",
      "name": "[variables('publicIPAddressName')]",
      "location": "[parameters('location')]",
      "properties": {
        "publicIPAllocationMethod": "Dynamic"
      },
      "sku": {
        "name": "Basic"
      }
    },
    {
      "comments": "Simple Network Security Group for subnet [variables('vNetSubnetName')]",
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2019-08-01",
      "name": "[variables('networkSecurityGroupName2')]",
      "location": "[parameters('location')]",
      "properties": {
        "securityRules": [
          {
            "name": "default-allow-22",
            "properties": {
              "priority": 1000,
              "access": "Allow",
              "direction": "Inbound",
              "destinationPortRange": "22",
              "protocol": "Tcp",
              "sourceAddressPrefix": "*",
              "sourcePortRange": "*",
              "destinationAddressPrefix": "*"
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "apiVersion": "2018-11-01",
      "name": "[variables('vNetName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName2'))]"
      ],
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[variables('vNetAddressPrefixes')]"
          ]
        },
        "subnets": [
          {
            "name": "[variables('vNetSubnetName')]",
            "properties": {
              "addressPrefix": "[variables('vNetSubnetAddressPrefix')]",
              "networkSecurityGroup": {
                "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName2'))]"
              }
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2018-11-01",
      "name": "[variables('networkInterfaceName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('publicIPAddressName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
      ],
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('publicIPAddressName'))]"
              },
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
              }
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2018-10-01",
      "name": "[variables('vmName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkInterfaces', variables('networkInterfaceName'))]"
      ],
      "properties": {
        "hardwareProfile": {
          "vmSize": "Standard_D2s_v3"
        },
        "osProfile": {
          "computerName": "[variables('vmName')]",
          "adminUsername": "[parameters('adminUsername')]",
          "linuxConfiguration": {
            "disablePasswordAuthentication": true,
            "ssh": {
              "publicKeys": [
                {
                  "path": "[concat('/home/', parameters('adminUsername'), '/.ssh/authorized_keys')]",
                  "keyData": "[parameters('adminPublicKey')]"
                }
              ]
            }
          }
        },
        "storageProfile": {
          "imageReference": {
            "publisher": "Canonical",
            "offer": "UbuntuServer",
            "sku": "18.04-LTS",
            "version": "latest"
          },
          "osDisk": {
            "createOption": "fromImage"
          }
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('networkInterfaceName'))]"
            }
          ]
        }
      }
    }
  ],
  "outputs": {
    "adminUsername": {
      "type": "string",
      "value": "[parameters('adminUsername')]"
    }
  }
}

在本地电脑上运行以下 CLI 脚本。To run the following CLI script on your local PC.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

echo "Enter the Resource Group name:" &&
read resourceGroupName &&
echo "Enter the location (i.e. chinaeast):" &&
read location &&
echo "Enter the project name (used for generating resource names):" &&
read projectName &&
echo "Enter the administrator username:" &&
read username &&
echo "Enter the SSH public key:" &&
read key &&
az group create --name $resourceGroupName --location "$location" &&
az deployment group create --resource-group $resourceGroupName --template-uri https://raw.githubusercontent.com/azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json --parameters projectName=$projectName adminUsername=$username adminPublicKey="$key" &&
az vm show --resource-group $resourceGroupName --name "$projectName-vm" --show-details --query publicIps --output tsv

最后一个 Azure CLI 命令显示新创建 VM 的公共 IP 地址。The last Azure CLI command shows the public IP address of the newly created VM. 需要通过公共 IP 地址连接到虚拟机。You need the public IP address to connect to the virtual machine. 请参阅本文的下一部分。See the next section of this article.

在前面的示例中,指定了 GitHub 中存储的一个模板。In the previous example, you specified a template stored in GitHub. 还可以下载或创建模板并使用 --template-file 参数指定本地路径。You can also download or create a template and specify the local path with the --template-file parameter.

下面是一些其他资源:Here are some additional resources:

连接到虚拟机Connect to virtual machine

然后,可以通过 SSH 照常连接到 VM。You can then SSH to your VM as normal. 在上述命令中提供自己的公共 IP 地址:Provide you own public IP address from the preceding command:

ssh <adminUsername>@<ipAddress>

后续步骤Next steps

在此示例中,创建了一个基本的 Linux VM。In this example, you created a basic Linux VM. 如需更多包含应用程序框架(或者可以用来创建更复杂环境)的资源管理器模板,请浏览 Azure 快速入门模板For more Resource Manager templates that include application frameworks or create more complex environments, browse the Azure Quickstart templates.