Поделиться через


Use cloud-init to update and install packages in a Linux VM in Azure

Область применения: ✔️ Виртуальные машины Linux ✔️ Гибкие масштабируемые наборы

This article shows you how to use cloud-init to update packages on a Linux virtual machine (VM) or virtual machine scale sets at provisioning time in Azure. Эти скрипты cloud-init выполняются при первой загрузке, если в Azure подготовлены все нужные ресурсы. Дополнительные сведения о встроенной поддержке cloud-init в Azure и поддерживаемых дистрибутивах Linux см. в обзоре cloud-init.

Update a VM with cloud-init

For security purposes, you may want to configure a VM to apply the latest updates on first boot. As cloud-init works across different Linux distros, there's no need to specify apt, zypper or yum for the package manager. Instead, you define package_upgrade and let the cloud-init process determine the appropriate mechanism for the distro in use.

For this example, we use the Azure Cloud Shell. To see the upgrade process in action, create a file named cloud_init_upgrade.txt and paste the following configuration. Вы можете использовать любой редактор. Убедитесь, что весь файл cloud-init скопирован правильно, особенно первая строка.

Copy the text below and paste it into the cloud_init_upgrade.txt file. Убедитесь, что весь файл cloud-init скопирован правильно, особенно первая строка.

#cloud-config
package_upgrade: true
packages:
- httpd

Before deploying, you need to create a resource group with the az group create command. Группа ресурсов Azure является логическим контейнером, в котором происходит развертывание ресурсов Azure и управление ими. В следующем примере создается группа ресурсов с именем myResourceGroup в расположении eastus.

az group create --name myResourceGroup --location eastus

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

az vm create \
  --resource-group myResourceGroup \
  --name vmName \
  --image imageCIURN \
  --custom-data cloud_init_upgrade.txt \
  --admin-username azureuser \
  --generate-ssh-keys

Примечание.

Замените значения myResourceGroup, vmName и imageCIURN соответствующим образом. Make sure an image with Cloud-init is chosen.

Подключитесь по протоколу SSH к общедоступному IP-адресу виртуальной машины, который указан в выходных данных предыдущей команды. Введите собственный пользователь и publicIpAddress следующим образом:

ssh <user>@<publicIpAddress>

Run the package management tool and check for updates:

  • Execute the following command to confirm there are no pending updates
sudo yum check-update

As cloud-init checked for and installed updates on boot, there should be no additional updates to apply.

  • You can see the update process, number of altered packages, and the installation of httpd by running the following command and review the output.
sudo yum history
ID     | Command line                                | Date and time    | Action(s)      | Altered
--------------------------------------------------------------------------------------------------
     3 | -y install httpd                            | 2022-02-18 18:30 | Install        |    7
     2 | -y upgrade                                  | 2022-02-18 18:23 | I, O, U        |  321 EE
     1 |                                             | 2021-02-04 19:20 | Install        |  496 EE

Дальнейшие действия

Дополнительные примеры изменения конфигурации с помощью cloud-init см. в следующих статьях: