- Virtual machine extensions and features for Linux
- Use cases and samples
- Prerequisites
- Azure VM agent
- Supported agent versions
- Supported OSes
- Network access
- Discover VM extensions
- Run VM extensions
- Azure CLI
- Azure portal
- Azure Resource Manager templates
- Secure VM extension data
- How do agents and extensions get updated?
- Agent updates
- Extension updates
- How to identify extension updates
- Identifying if the extension is set with autoUpgradeMinorVersion on a VM
- Identifying when an autoUpgradeMinorVersion occurred
- Agent permissions
- Troubleshoot VM extensions
- Common reasons for extension failures
- View extension status
- Rerun a VM extension
- Виртуальные машины Linux в Azure
- О чем следует подумать перед созданием виртуальной машины?
- Расположения
- Доступность
- Размер виртуальной машины
- Ограничения виртуальной машины
- Управляемые диски
- Дистрибутивы
- Cloud-init
- Память
- Местонахождение данных
Virtual machine extensions and features for Linux
Azure virtual machine (VM) extensions are small applications that provide post-deployment configuration and automation tasks on Azure VMs. For example, if a virtual machine requires software installation, anti-virus protection, or to run a script inside of it, a VM extension can be used. Azure VM extensions can be run with the Azure CLI, PowerShell, Azure Resource Manager templates, and the Azure portal. Extensions can be bundled with a new VM deployment, or run against any existing system.
This article provides an overview of VM extensions, prerequisites for using Azure VM extensions, and guidance on how to detect, manage, and remove VM extensions. This article provides generalized information because many VM extensions are available, each with a potentially unique configuration. Extension-specific details can be found in each document specific to the individual extension.
Use cases and samples
Several different Azure VM extensions are available, each with a specific use case. Some examples include:
- Apply PowerShell Desired State configurations to a VM with the DSC extension for Linux. For more information, see Azure Desired State configuration extension.
- Configure monitoring of a VM with the Microsoft Monitoring Agent VM extension. For more information, see How to monitor a Linux VM.
- Configure monitoring of your Azure infrastructure with the Chef or Datadog extension. For more information, see the Chef docs or Datadog blog.
In addition to process-specific extensions, a Custom Script extension is available for both Windows and Linux virtual machines. The Custom Script extension for Linux allows any Bash script to be run on a VM. Custom scripts are useful for designing Azure deployments that require configuration beyond what native Azure tooling can provide. For more information, see Linux VM Custom Script extension.
Prerequisites
To handle the extension on the VM, you need the Azure Linux Agent installed. Some individual extensions have prerequisites, such as access to resources or dependencies.
Azure VM agent
The Azure VM agent manages interactions between an Azure VM and the Azure fabric controller. The VM agent is responsible for many functional aspects of deploying and managing Azure VMs, including running VM extensions. The Azure VM agent is preinstalled on Azure Marketplace images, and can be installed manually on supported operating systems. The Azure VM Agent for Linux is known as the Linux agent.
For information on supported operating systems and installation instructions, see Azure virtual machine agent.
Supported agent versions
In order to provide the best possible experience, there are minimum versions of the agent. For more information, see this article.
Supported OSes
The Linux agent runs on multiple OSes, however the extensions framework has a limit for the OSes that extensions. For more information, see this article.
Some extensions are not supported across all OSes and may emit Error Code 51, ‘Unsupported OS’. Check the individual extension documentation for supportability.
Network access
Extension packages are downloaded from the Azure Storage extension repository, and extension status uploads are posted to Azure Storage. If you use supported version of the agents, you do not need to allow access to Azure Storage in the VM region, as can use the agent to redirect the communication to the Azure fabric controller for agent communications. If you are on a non-supported version of the agent, you need to allow outbound access to Azure storage in that region from the VM.
If you have blocked access to 168.63.129.16 using the guest firewall, then extensions fail irrespective of the above.
Agents can only be used to download extension packages and reporting status. For example, if an extension install needs to download a script from GitHub (Custom Script) or needs access to Azure Storage (Azure Backup), then additional firewall/Network Security Group ports need to be opened. Different extensions have different requirements, since they are applications in their own right. For extensions that require access to Azure Storage, you can allow access using Azure NSG Service Tags for Storage.
To redirect agent traffic requests, the Linux Agent has proxy server support. However, this proxy server support does not apply extensions. You must configure each individual extension to work with a proxy.
Discover VM extensions
Many different VM extensions are available for use with Azure VMs. To see a complete list, use az vm extension image list. The following example lists all available extensions in the westus location:
Run VM extensions
Azure VM extensions run on existing VMs, which is useful when you need to make configuration changes or recover connectivity on an already deployed VM. VM extensions can also be bundled with Azure Resource Manager template deployments. By using extensions with Resource Manager templates, Azure VMs can be deployed and configured without post-deployment intervention.
The following methods can be used to run an extension against an existing VM.
Azure CLI
Azure VM extensions can be run against an existing VM with the az vm extension set command. The following example runs the Custom Script extension against a VM named myVM in a resource group named myResourceGroup. Replace the example resource group name, VM name and script to run (https://raw.githubusercontent.com/me/project/hello.sh) with your own information.
When the extension runs correctly, the output is similar to the following example:
Azure portal
VM extensions can be applied to an existing VM through the Azure portal. Select the VM in the portal, choose Extensions, then select Add. Choose the extension you want from the list of available extensions and follow the instructions in the wizard.
The following image shows the installation of the Linux Custom Script extension from the Azure portal:
Azure Resource Manager templates
VM extensions can be added to an Azure Resource Manager template and executed with the deployment of the template. When you deploy an extension with a template, you can create fully configured Azure deployments. For example, the following JSON is taken from a Resource Manager template that deploys a set of load-balanced VMs and Azure SQL Database, then installs a .NET Core application on each VM. The VM extension takes care of the software installation.
For more information, see the full Resource Manager template.
For more information on creating Resource Manager templates, see Authoring Azure Resource Manager templates.
Secure VM extension data
When you run a VM extension, it may be necessary to include sensitive information such as credentials, storage account names, and storage account access keys. Many VM extensions include a protected configuration that encrypts data and only decrypts it inside the target VM. Each extension has a specific protected configuration schema, and each is detailed in extension-specific documentation.
The following example shows an instance of the Custom Script extension for Linux. The command to execute includes a set of credentials. In this example, the command to execute is not encrypted:
Moving the command to execute property to the protected configuration secures the execution string, as shown in the following example:
How do agents and extensions get updated?
The Agents and Extensions share the same update mechanism. Some updates do not require additional firewall rules.
When an update is available, it is only installed on the VM when there is a change to extensions, and other VM Model changes such as:
- Data disks
- Extensions
- Boot diagnostics container
- Guest OS secrets
- VM size
- Network profile
Publishers make updates available to regions at different times, so it is possible you can have VMs in different regions on different versions.
Agent updates
The Linux VM Agent contains Provisioning Agent Code and Extension Handling code in one package, which cannot be separated. You can disable the Provisioning Agent when you want to provision on Azure using cloud-init. To do this, see using cloud-init.
Supported versions of the Agents can use automatic updates. The only code that can be updated is the Extension Handling code, not the provisioning code. The Provisioning Agent code is run-once code.
The Extension Handling code is responsible for communicating with the Azure fabric, and handling the VM extensions operations such as installs, reporting status, updating the individual extensions, and removing them. Updates contain security fixes, bug fixes, and enhancements to the Extension Handling code.
When the agent is installed, a parent daemon is created. This parent then spawns a child process that is used to handle extensions. If an update is available for the agent, it is downloaded, the parent stops the child process, upgrades it, then restarts it. Should there be a problem with the update, the parent process rolls back to the previous child version.
The parent process cannot be auto updated. The parent can only be updated by a distro package update.
To check what version you are running, check the waagent as follows:
The output is similar to the following example:
In the preceding example output, the parent or ‘package deployed version’ is WALinuxAgent-2.2.17
The ‘Goal state agent’ is the auto update version.
It is highly recommended that you always have auto update for the agent, AutoUpdate.Enabled=y. Not having this enabled means you need to keep manually updating the agent, and not get bug and security fixes.
Extension updates
When an extension update is available, the Linux Agent downloads and upgrades the extension. Automatic extension updates are either Minor or Hotfix. You can opt in or opt out of extensions Minor updates when you provision the extension. The following example shows how to automatically upgrade minor versions in a Resource Manager template with autoUpgradeMinorVersion»: true,’:
To get the latest minor release bug fixes, it is highly recommended that you always select auto update in your extension deployments. Hotfix updates that carry security or key bug fixes cannot be opted out.
How to identify extension updates
Identifying if the extension is set with autoUpgradeMinorVersion on a VM
You can see from the VM model if the extension was provisioned with ‘autoUpgradeMinorVersion’. To check, use az vm show and provide the resource group and VM name as follows:
The following example output shows that autoUpgradeMinorVersion is set to true:
Identifying when an autoUpgradeMinorVersion occurred
To see when an update to the extension occurred, review the agent logs on the VM at /var/log/waagent.log.
In the example below, the VM had Microsoft.OSTCExtensions.LinuxDiagnostic-2.3.9025 installed. A hotfix was available to Microsoft.OSTCExtensions.LinuxDiagnostic-2.3.9027:
Agent permissions
To perform its tasks, the agent needs to run as root.
Troubleshoot VM extensions
Each VM extension may have troubleshooting steps specific to the extension. For example, when you use the Custom Script extension, script execution details can be found locally on the VM where the extension was run. Any extension-specific troubleshooting steps are detailed in extension-specific documentation.
The following troubleshooting steps apply to all VM extensions.
To check the Linux Agent Log, look at the activity when your extension was being provisioned in /var/log/waagent.log
Check the actual extension logs for more details in /var/log/azure/
Check extension-specific documentation troubleshooting sections for error codes, known issues etc.
Look at the system logs. Check for other operations that may have interfered with the extension, such as a long running installation of another application that required exclusive package manager access.
Common reasons for extension failures
Extensions have 20 mins to run (exceptions are the CustomScript extensions, Chef, and DSC that have 90 mins). If your deployment exceeds this time, it is marked as a timeout. The cause of this can be due to low resource VMs, other VM configurations/start up tasks consuming high amounts of resource whilst the extension is trying to provision.
Minimum prerequisites not met. Some extensions have dependencies on VM SKUs, such as HPC images. Extensions may require certain networking access requirements, such as communicating to Azure Storage or public services. Other examples could be access to package repositories, running out of disk space, or security restrictions.
Exclusive package manager access. In some cases, you may encounter a long running VM configuration and extension installation conflicting, where they both need exclusive access to the package manager.
View extension status
After a VM extension has been run against a VM, use az vm get-instance-view to return extension status as follows:
The output is similar to the following example output:
Extension execution status can also be found in the Azure portal. To view the status of an extension, select the VM, choose Extensions, then select the desired extension.
Rerun a VM extension
There may be cases in which a VM extension needs to be rerun. You can rerun an extension by removing it, and then rerunning the extension with an execution method of your choice. To remove an extension, use az vm extension delete as follows:
You can also remove an extension in the Azure portal as follows:
- Select a VM.
- Choose Extensions.
- Select the desired extension.
- Choose Uninstall.
Источник
Виртуальные машины Linux в Azure
Применимо к: ✔️ виртуальным машинам Linux ✔️ гибким масштабируемым наборам
Виртуальные машины Azure — один из нескольких типов запрашиваемых масштабируемых вычислительных ресурсов, которые предоставляет Azure. Обычно виртуальную машину выбирают, когда требуется более строгий контроль за вычислительной средой, чем в других вариантах. В этой статье содержатся сведения о том, что следует учитывать перед созданием виртуальной машины, а также инструкции по созданию виртуальной машины и управлению ею.
Виртуальная машина Azure предоставляет гибкие возможности виртуализации без необходимости приобретать и обслуживать физическое оборудование, на котором она выполняется. Однако вам по-прежнему приходится обслуживать виртуальную машину, выполняя разные задачи — настройка, установка исправлений и программного обеспечения, работающего на виртуальной машине.
Виртуальные машины Azure можно использовать разными способами. Некоторые примеры.
- Разработка и тестирование. Виртуальные машины Azure обеспечивают быстрый и простой способ создания компьютера с определенными конфигурациями, необходимыми для написания кода и тестирования приложения.
- Приложения в облаке. Так как уровень спроса на приложение может меняться, с экономической точки зрения разумно запускать его на виртуальной машине в Azure. Вы платите за дополнительные виртуальные машины, если они вам нужны, и отключаете их, если они не нужны.
- Расширенный центр обработки данных. Виртуальные машины в виртуальной сети Azure можно легко подключить к корпоративной сети.
Вы можете увеличить масштаб виртуальных машин, используемых приложением, а также развернуть дополнительные виртуальные машины в соответствии с требованиями.
О чем следует подумать перед созданием виртуальной машины?
При создании инфраструктуры приложения в Azure всегда нужно учитывать множество рекомендаций по проектированию. Перед началом работы следует подумать о следующих аспектах для виртуальной машины:
- имена ресурсов приложения;
- расположение, в котором хранятся ресурсы;
- размер виртуальной машины;
- максимальное число виртуальных машин, которые можно создать;
- операционная система, под управлением которой будет работать виртуальная машина;
- конфигурация виртуальной машины после ее запуска;
- связанные ресурсы, необходимые для виртуальной машины.
Расположения
Все ресурсы, созданные в Azure, распределяются по нескольким географическим регионам во всем мире. Как правило, при создании виртуальной машины регион называется расположением. Для виртуальной машины расположение указывает на место хранения виртуальных жестких дисков.
В этой таблице приведены некоторые способы, с помощью которых можно получить список доступных расположений.
Метод | Описание |
---|---|
Портал Azure | Выберите расположение из списка при создании виртуальной машины. |
Azure PowerShell | Используйте команду Get-AzLocation. |
REST API | Используйте операцию вывода списка расположений. |
Azure CLI | Используйте операцию az account list-locations. |
Доступность
В рамках отраслевого соглашения об уровне обслуживания Azure мы объявили о поддержке одного экземпляра виртуальной машины с гарантированной доступностью в течение 99,9 % времени при условии его развертывания с использованием хранилища класса Premium для всех дисков. Чтобы обеспечить соответствие соглашению об уровне обслуживания с гарантированной доступностью виртуальных машин в течение 99,95 % времени, вам так или иначе нужно развернуть две или несколько виртуальных машин для выполнения рабочих нагрузок в рамках группы доступности. В группе доступности виртуальные машины распределяются по несколькими доменам сбоя в центрах обработки данных Azure, а также развертываются на узлах с разными периодами обслуживания. В полном соглашении об уровне обслуживания Azure поясняется гарантированная доступность Azure в целом.
Размер виртуальной машины
Используемый размер виртуальной машины зависит от рабочей нагрузки, которую требуется выполнить. Позже выбранный размер определяет разные факторы, например вычислительную мощность, объем памяти и хранилища. Azure предлагает широкий спектр размеров для поддержки разных вариантов использования.
Azure взимает почасовую оплату, исходя из размера и операционной системы виртуальной машины. При частичном использовании Azure взимает плату только за использованные минуты. Плата за использование хранилища взимается отдельно.
Ограничения виртуальной машины
Для подписки Azure предусмотрена квота по умолчанию, от которой зависит возможность развертывания большого количества виртуальных машин для проекта. Текущее ограничение для каждой подписки составляет 20 виртуальных машин на регион. Чтобы увеличить квоту, следует отправить соответствующий запрос в службу поддержки.
Управляемые диски
Управляемые диски выполняют создание учетной записи хранения Azure и управление ею в фоновом режиме. При этом вам не нужно беспокоиться об ограничениях масштабируемости учетной записи хранения. Вам необходимо указать размер диска и уровень производительности («Стандартный» или «Премиум»), а создание и управление Azure берет на себя. При добавлении дисков или масштабировании виртуальной машины не нужно беспокоиться об используемом хранилище. Чтобы создать виртуальные машины с управляемыми дисками ОС и данных, используйте интерфейс командной строки Azure или портал Azure. Если у вас есть виртуальные машины с неуправляемыми дисками, можно преобразовать виртуальные машины для архивации с помощью Управляемых дисков.
Вы также можете управлять пользовательскими образами в одной учетной записи хранения на каждый регион Azure и использовать их для создания сотен виртуальных машин в одной подписке. Дополнительные сведения об управляемых дисках см. в этой статье.
Дистрибутивы
Microsoft Azure поддерживает различные дистрибутивы Linux, которые предоставляются и обслуживаются партнерами. Доступные дистрибутивы можно найти в Azure Marketplace. Майкрософт активно сотрудничает с разными сообществами Linux, чтобы расширить список рекомендованных дистрибутивов Linux для Azure.
Если в коллекции отсутствует необходимый дистрибутив Linux, вы всегда можете использовать свою виртуальную машину Linux, создав VHD-файл виртуальной машины Linux и передав его в Azure.
Корпорация Майкрософт тесно сотрудничает с партнерами, чтобы гарантировать обновление и оптимизацию доступных образов для среды выполнения Azure. Дополнительные сведения о предложениях партнеров Azure см. по следующим ссылкам:
Cloud-init
В соответствии с правильной культурой разработки и операций, всю инфраструктуру необходимо включить в код. Когда вся инфраструктура находится в коде, ее можно легко воссоздать. Azure работает со всеми основными средствами автоматизации, включая Ansible, SaltStack, Puppet и Chef. Кроме того, в Azure имеются собственные средства автоматизации:
Azure поддерживает пакет cloud-init для большинства дистрибутивов Linux, которые поддерживают его. Мы активно сотрудничаем с нашими утвержденными партнерами, работающими над дистрибутивами Linux, чтобы образы с поддержкой cloud-init стали доступными в Azure Marketplace. Эти образы обеспечивают бесперебойную работу развертываний и конфигураций cloud-init с виртуальными машинами и масштабируемыми наборами виртуальных машин.
Память
Местонахождение данных
В Azure функция хранения данных клиентов в одном регионе сейчас доступна только для регионов «Юго-Восточная Азия (Сингапур)» в Азиатско-Тихоокеанском географическом регионе и «Южная Бразилия» (штат Сан-Паулу) в географическом регионе «Бразилия». Для всех других регионов данные клиента хранятся в геообъектах. Дополнительные сведения см. на этой странице.
Источник