Dela via


Use cloud-init to set hostname for a Linux VM in Azure

Gäller för: ✔️ Flexibla skalningsuppsättningar för virtuella Linux-datorer ✔️

This article shows you how to use cloud-init to configure a specific hostname on a virtual machine (VM) or virtual machine scale sets (VMSS) at provisioning time in Azure. Dessa cloud-init-skript körs vid första uppstarten när resurserna har tillhandahållits av Azure. Mer information om hur cloud-init fungerar internt i Azure och vilka Linux-distributioner som stöds finns i översikten över cloud-init

Set the hostname with cloud-init

By default, the hostname is the same as the VM name when you create a new virtual machine in Azure. To run a cloud-init script to change this default hostname when you create a VM in Azure with az vm create, specify the cloud-init file with the --custom-data switch.

To see upgrade process in action, create a file in your current shell named cloud_init_hostname.txt and paste the following configuration. For this example, create the file in the Cloud Shell not on your local machine. You can use any editor you wish. Make sure that the whole cloud-init file is copied correctly, especially the first line.

#cloud-config
fqdn: myhostname

Before deploying this image, you need to create a resource group with the az group create command. En Azure-resursgrupp är en logisk container där Azure-resurser distribueras och hanteras. I följande exempel skapas en resursgrupp med namnet myResourceGroup i regionen eastus.

az group create --name myResourceGroup --location eastus

Now, create a VM with az vm create and specify the cloud-init file with --custom-data cloud_init_hostname.txt as follows:

az vm create \
  --resource-group myResourceGroup \
  --name vmName \
  --image imageCIURN \
  --custom-data cloud_init_hostname.txt \
  --generate-ssh-keys

Anmärkning

Replace myResourceGroup, vmName, and imageCIURN values accordingly. Make sure an image with Cloud-init is chosen.

Once created, the Azure CLI shows information about the VM. Use the publicIpAddress to SSH to your VM. Enter your own address as follows:

ssh <user>@<publicIpAddress>

To see the VM name, use the hostname command as follows:

sudo hostname

The VM should report the hostname as that value set in the cloud-init file, as shown in the following example output:

myhostname

Nästa steg

Ytterligare moln-init-exempel på konfigurationsändringar finns i följande: