Поддержка cloud-init для виртуальных машин в Azure
Применимо к: ✔️ виртуальные машины Linux ✔️ гибкие масштабируемые наборы
Из этой статьи можно узнать об имеющейся поддержке cloud-init для настройки виртуальной машины или масштабируемых наборов виртуальных машин во время подготовки в Azure. Эти настройки конфигурации cloud-init выполняются при первой загрузке, если в Azure подготовлены все нужные ресурсы.
Подготовка виртуальной машины — это процесс, при котором Azure передает значения параметров создания виртуальной машины, такие как имя узла, имя пользователя, пароль и т. д., и делает их доступными для виртуальной машины при загрузке. «Агент подготовки» принимает эти значения, настраивает виртуальную машину, а, закончив, передает отчет.
Azure поддерживает два агента подготовки — cloud-init и агент Linux для Azure (WALA).
Общие сведения о cloud-Init
Cloud-init — широко используемое средство для настройки виртуальной машины Linux при ее первой загрузке. Вы можете использовать cloud-init для установки пакетов, записи файлов или настройки пользователей и параметров безопасности. Так как cloud-init вызывается при начальной загрузке, к вашей конфигурации не нужно применять какие-либо дополнительные действия или агентов. Дополнительные сведения о том, как правильно отформатировать файлы, #cloud-config или другие входные данные, см. на сайте документации по cloud-init. Файлы #cloud-config — это текстовые файлы, закодированные в формате base64.
Кроме того, cloud-init работает с разными дистрибутивами. Например, для установки пакета не используется apt-get install или yum install. Вместо этого можно определить список пакетов для установки. Cloud-init автоматически использует собственный инструмент управления пакетами из выбранного дистрибутива.
Мы активно взаимодействуем с утвержденными партнерами, создающими дистрибутивы Linux, чтобы в Azure Marketplace присутствовали образы с поддержкой cloud-init. Эти образы обеспечивают бесперебойную работу развертываний и конфигураций cloud-init с виртуальными машинами и масштабируемыми наборами виртуальных машин. Сначала мы активно сотрудничаем с нашими утвержденными партнерами, работающими над дистрибутивами Linux, и вышестоящими источниками, чтобы обеспечить работу функций cloud-init с ОС в Azure, а затем пакеты обновляются и переводятся в открытый доступ через репозитории пакетов дистрибутивов.
Доступ к cloud-init доверенной ОС с дистрибутивом Linux в Azure предоставляется в два этапа — поддержка пакета и поддержка образа:
Canonical
| Издатель/версия | ПРЕДЛОЖЕНИЕ | номер SKU | Версия | Образ готов для cloud-init | Поддержка пакетов cloud-init в Azure |
|---|---|---|---|---|---|
| Canonical 20.04 | UbuntuServer | 20.04-LTS | последняя | да | да |
| Canonical 18.04 | UbuntuServer | 18.04-LTS | последняя | да | да |
CentOS
OpenLogic теперь носит название Rogue Wave Software.
Oracle;
SUSE SLES
Debian
| Издатель/версия | ПРЕДЛОЖЕНИЕ | номер SKU | Версия | Образ готов для cloud-init | Поддержка пакетов cloud-init в Azure |
|---|---|---|---|---|---|
| debian (поколение 1) | debian-10 | 10-cloudinit | 10:0.20201013.422 | да | да — поддержка из пакета версии: 20.2-2 |
deb10u1
В настоящее время Azure Stack поддерживает подготовку образов с поддержкой cloud-init.
Разница между cloud-init и агентом Linux (WALA)
WALA — это уникальный агент платформы Azure, использующийся для подготовки и настройки виртуальных машин и обработки расширений Azure.
Мы улучшили задачу настройки виртуальных машин для использования cloud-init вместо агента Linux таким образом, чтобы имеющиеся пользователи cloud-init смогли применять свои текущие скрипты cloud-init, а новые клиенты могли использовать преимущества функциональных возможностей cloud-init. Если у вас уже есть скрипты cloud-init для настройки систем Linux, то для включения их обработки с использованием cloud-init дополнительные параметры не требуются.
Cloud-init не может обрабатывать расширения Azure, поэтому для обработки расширений в образе должен присутствовать WALA, однако его код подготовки необходимо отключить, чтобы конвертируемые поддерживаемые дистрибутивы Linux могли подготовить cloud-init, а затем установить и правильно настроить WALA.
Конфигурация cloud-init применяется к виртуальным машинам без временных ограничений, которые не приведут к сбою развертывания по времени. К WALA это не относится. Если изменить значения WALA по умолчанию на пользовательские данные обработки, он не сможет превысить общую квоту времени подготовки виртуальной машины в 40 минут, и тогда операция создания виртуальной машины завершится ошибкой.
Подготовка виртуальной машины с помощью cloud-init без драйвера UDF
Начиная с cloud-init 21.2, можно использовать cloud-init для подготовки виртуальной машины в Azure без драйвера UDF. Если драйвер UDF в образе недоступен, cloud-init использует для подготовки виртуальной машины метаданные, доступные в Службе метаданных экземпляров Azure. Обратите внимание, что этот вариант применим только для ключа SSH и данных пользователя. Чтобы передать виртуальной машине пароль или пользовательские данные во время подготовки, необходимо использовать драйвер UDF.
Развертывание виртуальной машины с поддержкой cloud-init
Развертывать виртуальную машину с включенным cloud-init так же просто, как и ссылаться на распределение с включенным cloud-init во время развертывания. Распространители дистрибутивов Linux должны включать и интегрировать cloud-init в свои базовые опубликование образы Azure. Убедившись, что в образе, который нужно развернуть, включен cloud-init, вы можете использовать Azure CLI для его развертывания.
Первым шагом при развертывании образа является создание группы ресурсов с использованием команды az group create. Группа ресурсов Azure является логическим контейнером, в котором происходит развертывание ресурсов Azure и управление ими.
В следующем примере создается группа ресурсов с именем myResourceGroup в расположении eastus.
Последним шагом является создание виртуальной машины с использованием команды az vm create.
Вы также можете развернуть виртуальную машину с поддержкой cloud-init, передав параметры в шаблоне ARM.
Устранение неполадок cloud-init
Дополнительные сведения о журнале cloud-init см. в документации по cloud-init
Дальнейшие действия
Примеры изменения конфигураций с помощью cloud-init см. в следующих документах:
Windows Cloud-Init solution
Windows Cloud-Init solution
Ten years ago the word Cloud was the buzz word in every IT conference. The Cloud promised to bring the modern IT business to a new level of opportunities. Back at that time I was an engineer with little IT experience, attracted by the big transformations ahead and wondering where is this going to end. Almost a decade later, we have three types of cloud solutions: on-premise private cloud, public cloud and the mix of both worlds called hybrid cloud. The competition between them and the increased number of business requirements, set the need for new kind of automation tools and products to bridge the gaps and offer seamless experience. With the recent announcement of VMware Cloud Services, VMware is heading strong in this direction. Behind the scenes, VMware Cloud Services is an extensible SaaS solution designed to help us operate, secure and monitor workloads across different cloud providers.
Now that we have the flexibility to choose, which workload goes where, we have to solve another common problem. We need to find out how to customize the guest instance to fit our software application(s).
Thanks to the Cloud-Init package developed by Canonical, this is an easy task for the most popular Linux and FreeBSD operating systems. However, Cloud-Init doesn’t support windows guest instances and this is a problem for all applications that require windows to run.
The good news is that a company called “Cloudbase Solutions” developed equivalent of Cloud-Init for windows. Cloudbase-init provides out of the box: user creation, password injection, static network configuration, hostname, SSH public keys and user-data scripts, such as PowerShell, Batch, Python, Cloud Config and others.
In this blog post tutorial, I will demonstrate how to prepare Azure windows image with cloudbase-init and then customize guest instance provisioned from that image. The procedure is identical for all supported cloud vendors and versions of windows. The tutorial is split in two parts, the image preparation and the guest instance customization.
There are multiple ways to create a custom Azure windows image. To keep things simple for the purpose of this demonstration, I will customize one of the windows 10 Azure marketplace images and then capture it as custom image.
Prepare Cloudbase-init Azure windows 10 image
The guest instance metadata is picked up by the so called cloudbase-init metadata services. Then they exposed the data to the cloudbase-init plugins, responsible for the guest instance customization.
For example, configure custom instance host name, network address, username, password and others.
Available cloudbase-init plug-ins (stable version):
Available cloudbase-init user-data interpretors (stable version):
The guest instance user-data is called with different names across the different cloud providers (Azure: custom data, AWS/Openstack/Ubuntuu MaaS/CloudStack: userdata). This is custom user content exposed to the guest instance by the currently deployed and running cloud infrastructure. Its purpose is to provide additional data for the instance to customize it as much as you need, if the cloud initialization service does support this feature.
Click Install and once the installation completes, configure the cloudbase-init config, before finalizing the installation.
TutorialВ¶
SyspreppingВ¶
The System Preparation (Sysprep) tool prepares an installation of Windows for duplication, auditing, and customer delivery. Duplication, also called imaging, enables you to capture a customized Windows image that you can reuse throughout an organization. The Sysprep phase uses the “Unattend.xml” which implies the service to run using the “cloudbase-init-unattend.conf” configuration file.
Configuration fileВ¶
In the chosen installation path, under the conf directory, are present two config files named “cloudbase-init.conf” and “cloudbase-init-unattend.conf”. These can hold various config options for picking up the desired available services and plugins ready for execution and also customizing user experience.
Explained example of configuration file:
The “cloudbase-init-unattend.conf” configuration file is similar to the default one and is used by the Sysprepping phase. It was designed for the scenario where the minimum user intervention is required and it only runs the MTU and host name plugins, leaving the image ready for further initialization cases.
File executionВ¶
Cloudbase-init has the ability to execute user provided scripts, usually found in the default path C:\Program Files (x86)\Cloudbase Solutions\Cloudbase-Init\LocalScripts, through a specific plugin for doing it. Depending on the platform used, the files should be valid PowerShell, Python, Batch or Bash scripts. The userdata can be also a PEM certificate, in a cloud-config format or a MIME content. The user data plugin is capable of executing various script types and exit code value handling.
Based on their exit codes, you can instruct the system to reboot or even re-execute the plugin on the next boot:
Windows guest initialization with Cloudbase-Init in vCenter
In a previous post we showed how to leverage Cloudbase-Init to customize Windows guest instances provisioned by VMware Cloud Assembly in an Azure Cloud Account. Now it is time to show the power of Cloudbase-Init in vCenter Cloud Accounts.
Cloudbase-Init is the Cloud-Init equivalent for Windows. It provides tools for Windows guest customization, like user creation, password injection, hostname, SSH public keys and user-data scripts.
In this post I am going show how to use cloud agnostic blueprints to deploy and customize a Windows instance in a vCenter Cloud Account in VMware Cloud Assembly. I have divided the post in two parts: first, I will show how to setup a Windows image in vCenter and tailor the image for customization. In this part, I won’t go step by step through the image creation process, instead, I will focus on how to configure Cloudbase-Init. And second, I will show how to create a blueprint in VMware Cloud Assembly with some guest customization, deploy it and check that the customization is applied successfully.
Setup Cloudbase-Init in a vCenter Windows image
After these steps, we have a Windows image ready to use in VMware Cloud Assembly, with Cloudbase-Init prepared to customize our deployments. To customize the guest instance user experience, the user can change the properties shown the configuration files. Most of the properties have default suggested values, except:
Deploy and customize Windows guest instance within VMware Cloud Assembly
Now I will show how to create a cloud agnostic blueprint to deploy and customize the Windows image from the previous step.
Summary
As you can see, Cloudbase-Init is the Cloud-Init solution for Windows. It gives a lot of flexibility for Windows guest customization, and provides seamless integration with VMware Cloud Assembly.
Visit the VMware Cloud Assembly page to learn more about it and give it a free try!
Русские Блоги
конфигурация cloudbase-init
Инсталляционный пакет можно скачать по ссылке ниже:
Пожалуйста, обратитесь к Openstack p_w_picpath делает windows server 2003 зеркалом Сделайте зеркальное отображение в одной статье.
Затем используйте следующую команду, чтобы начать в режиме касания, и вы можете общаться с внешним миром.
После подключения к VNC Viewer щелкните программу установки, чтобы установить.
Имя пользователя устанавливается здесь как Администратор, а пароль пользователя изменяется позже. Если это другое имя пользователя, сначала будет создано оно, а затем будет установлен пароль.
Переходите к следующему шагу, пока он не будет завершен
Проверьте каталог C: \ Program Files \ Cloudbase Solutions \ Cloudbase-init \ conf, вы увидите файл конфигурации, как показано на рисунке ниже.
Измените содержимое 2 файлов conf отдельно
Затем выключите систему и загрузите образ в систему.
Начните с 2 разных параметров ниже
1. Не загружайте в привод
Через vnc вы можете войти в систему с именем пользователя administrator и паролем 123456, и обнаруживается, что имя хоста было установлено на test123.
Доступ к сервису метаданных можно получить по ссылке http://169.254.169.254.
Продолжайте просматривать содержимое файла meta_data.json
Мы обнаружили, что можно увидеть имя хоста и пароль, переданные при запуске.
2. Загрузить в привод
После входа в систему проверьте мой компьютер, вы увидите, что оптический привод загружен
Таким образом, нет необходимости обращаться к службе метаданных через http, и метаданные были загружены в файл компакт-диска.
Вы можете увидеть, просмотрев диск
Продолжайте просматривать содержимое файла meta_data.json
Вы можете увидеть то же содержимое данных, что и http://169.254.169.254/openstack/latest/meta_data.json.



