Отправка и извлечение Helm диаграмм в реестр контейнеров AzurePush and pull Helm charts to an Azure container registry
Для быстрого развертывания приложений и управления ими в Kubernetes можно использовать диспетчер пакетов Helm с открытым исходным кодом.To quickly manage and deploy applications for Kubernetes, you can use the open-source Helm package manager. При использовании Helm пакеты приложений определяются как диаграммы, которые собираются и сохраняются в репозитории диаграммы Helm.With Helm, application packages are defined as charts, which are collected and stored in a Helm chart repository.
В этой статье показано, как разместить репозитории диаграмм Helm в реестре контейнеров Azure с помощью команд Helm 3.This article shows you how to host Helm charts repositories in an Azure container registry, using Helm 3 commands. Во многих случаях для разрабатываемых приложений можно создавать и передавать собственные диаграммы.In many scenarios, you would build and upload your own charts for the applications you develop. Дополнительные сведения о создании собственных диаграмм Helm см. в разделе Руководство разработчика шаблона диаграммы.For more information on how to build your own Helm charts, see the Chart Template Developer's Guide. Можно также сохранить существующую диаграмму Helm из другого репозитория Helm.You can also store an existing Helm chart from another Helm repo.
Важно!
Поддержка диаграмм Helm в реестре контейнеров Azure сейчас доступна в предварительной версии.Support for Helm charts in Azure Container Registry is currently in preview. Предварительные версии предоставляются при условии, что вы соглашаетесь с дополнительными условиями использования.Previews are made available to you on the condition that you agree to the supplemental terms of use. Некоторые аспекты этой функции могут быть изменены до выхода общедоступной версии.Some aspects of this feature may change prior to general availability (GA).
Helm 3 или Helm 2?Helm 3 or Helm 2?
Для хранения, управления и установки диаграмм Helm используется клиент Helm и интерфейс командной строки Helm.To store, manage, and install Helm charts, you use a Helm client and the Helm CLI. Основные выпуски клиента Helm включают Helm 3 и Helm 2.Major releases of the Helm client include Helm 3 and Helm 2. Дополнительные сведения о различиях версий см. в разделе часто задаваемые вопросы о версии.For details on the version differences, see the version FAQ.
Helm 3 следует использовать для размещения диаграмм Helm в реестре контейнеров Azure.Helm 3 should be used to host Helm charts in Azure Container Registry. С Helm 3 вы:With Helm 3, you:
- Может создать один или несколько репозиториев Helm в реестре контейнеров AzureCan create one or more Helm repositories in an Azure container registry
- Храните Helm 3 диаграммы в реестре как артефакты OCI.Store Helm 3 charts in a registry as OCI artifacts. В настоящее время Helm 3 поддержка OCI является экспериментальной.Currently, Helm 3 support for OCI is experimental.
- Проверьте подлинность в реестре с помощью
helm registry login
команды.Authenticate with your registry using thehelm registry login
command. - Использование
helm chart
команд в интерфейсе командной строки Helm для отправки, извлечения и управления диаграммами Helm в реестреUsehelm chart
commands in the Helm CLI to push, pull, and manage Helm charts in a registry - Используйте
helm install
для установки диаграмм в кластер Kubernetes из локального кэша репозитория.Usehelm install
to install charts to a Kubernetes cluster from a local repository cache.
Примечание
Начиная с Helm 3 команды AZ контроля доступа Helm для использования с клиентом Helm 2 являются устаревшими.As of Helm 3, az acr helm commands for use with the Helm 2 client are being deprecated. См. план развития продукта.See the product roadmap. Если вы ранее развернули Helm 2 диаграммы, см. статью Миграция Helm v2 на v3.If you've previously deployed Helm 2 charts, see Migrating Helm v2 to v3.
Предварительные требованияPrerequisites
Для сценария, описанного в этой статье, необходимы следующие ресурсы:The following resources are needed for the scenario in this article:
- Реестр контейнеров Azure в подписке Azure.An Azure container registry in your Azure subscription. При необходимости создайте реестр с помощью портал Azure или Azure CLI.If needed, create a registry using the Azure portal or the Azure CLI.
- Helm Client версии 3.1.0 или более поздней — выполните команду
helm version
, чтобы найти текущую версию.Helm client version 3.1.0 or later - Runhelm version
to find your current version. Дополнительные сведения о том, как установить и обновить Helm, см. здесь.For more information on how to install and upgrade Helm, see Installing Helm. - Кластер Kubernetes , в котором будет установлена диаграмма Helm.A Kubernetes cluster where you will install a Helm chart. При необходимости создайте кластер службы Azure Kubernetes.If needed, create an Azure Kubernetes Service cluster.
- Azure CLI версии 2.0.71 или более поздней — выполните команду,
az --version
чтобы найти версию.Azure CLI version 2.0.71 or later - Runaz --version
to find the version. Если вам необходимо выполнить установку или обновление, см. статью Установка Azure CLI 2.0.If you need to install or upgrade, see Install Azure CLI.
Включить поддержку OCIEnable OCI support
Используйте helm version
команду, чтобы убедиться, что установлен Helm 3:Use the helm version
command to verify that you have installed Helm 3:
helm version
Задайте следующую переменную среды, чтобы включить поддержку OCI в клиенте Helm 3.Set the following environment variable to enable OCI support in the Helm 3 client. В настоящее время эта поддержка экспериментальна.Currently, this support is experimental.
export HELM_EXPERIMENTAL_OCI=1
Создание образца диаграммыCreate a sample chart
Создайте тестовую диаграмму с помощью следующих команд:Create a test chart using the following commands:
mkdir helmtest
cd helmtest
helm create hello-world
В качестве базового примера измените каталог на templates
папку и сначала удалите содержимое:As a basic example, change directory to the templates
folder and first delete the contents there:
cd hello-world/templates
rm -rf *
В templates
папке создайте файл configmap.yaml
с именем, выполнив следующую команду:In the templates
folder, create a file called configmap.yaml
, by running the following command:
cat <<EOF > configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: hello-world-configmap
data:
myvalue: "Hello World"
EOF
Дополнительные сведения о создании и выполнении этого примера см. в разделе Начало работы в документах Helm.For more about creating and running this example, see Getting Started in the Helm Docs.
Сохранить диаграмму в локальном кэше реестраSave chart to local registry cache
Измените каталог на hello-world
подкаталог.Change directory to the hello-world
subdirectory. Затем выполните команду, helm chart save
чтобы сохранить копию диаграммы локально и создать псевдоним с полным именем реестра (все строчные), а также с целевым репозиторием и тегом.Then, run helm chart save
to save a copy of the chart locally and also create an alias with the fully qualified name of the registry (all lowercase) and the target repository and tag.
В следующем примере имя реестра — миконтаинеррегистри, целевой репозиторий — Hello-World, а целевой тег диаграммы — v1, но значения для вашей среды заменяются:In the following example, the registry name is mycontainerregistry, the target repo is hello-world, and the target chart tag is v1, but substitute values for your environment:
cd ..
helm chart save . hello-world:v1
helm chart save . mycontainerregistry.azurecr.io/helm/hello-world:v1
Выполните команду helm chart list
, чтобы убедиться, что диаграммы сохранены в локальном кэше реестра.Run helm chart list
to confirm you saved the charts in the local registry cache. Она выводит выходные данные следующего вида:Output is similar to:
REF NAME VERSION DIGEST SIZE CREATED
hello-world:v1 hello-world 0.1.0 5899db0 3.2 KiB 2 minutes
mycontainerregistry.azurecr.io/helm/hello-world:v1 hello-world 0.1.0 5899db0 3.2 KiB 2 minutes
Проверка подлинности в реестреAuthenticate with the registry
Выполните helm registry login
команду в CLI Helm 3, чтобы выполнить аутентификацию в реестре , используя учетные данные, подходящие для вашего сценария.Run the helm registry login
command in the Helm 3 CLI to authenticate with the registry using credentials appropriate for your scenario.
Например, создайте субъект-службу Azure Active Directory с разрешениями Pull и Push (роль акрпуш) в реестре.For example, create an Azure Active Directory service principal with pull and push permissions (AcrPush role) to the registry. Затем укажите учетные данные субъекта-службы в helm registry login
.Then supply the service principal credentials to helm registry login
. В следующем примере пароль предоставляется с помощью переменной среды:The following example supplies the password using an environment variable:
echo $spPassword | helm registry login mycontainerregistry.azurecr.io \
--username <service-principal-id> \
--password-stdin
Принудительная отправка диаграммы в реестрPush chart to registry
Выполните helm chart push
команду в CLI Helm 3, чтобы передать диаграмму в полный целевой репозиторий:Run the helm chart push
command in the Helm 3 CLI to push the chart to the fully qualified target repository:
helm chart push mycontainerregistry.azurecr.io/helm/hello-world:v1
После успешной принудительной отправки выходные данные выглядят примерно так:After a successful push, output is similar to:
The push refers to repository [mycontainerregistry.azurecr.io/helm/hello-world]
ref: mycontainerregistry.azurecr.io/helm/hello-world:v1
digest: 5899db028dcf96aeaabdadfa5899db025899db025899db025899db025899db02
size: 3.2 KiB
name: hello-world
version: 0.1.0
Вывод списка диаграмм в репозиторииList charts in the repository
Как и в случае с изображениями, хранящимися в реестре контейнеров Azure, можно использовать команды AZ контроля учетных записей, чтобы отобразить репозитории, в которых размещены диаграммы, а также теги и манифесты диаграммы.As with images stored in an Azure container registry, you can use az acr repository commands to show the repositories hosting your charts, and chart tags and manifests.
Например, выполните команду AZ контроля доступа к репозиторию , чтобы просмотреть свойства репозитория, созданного на предыдущем шаге.For example, run az acr repository show to see the properties of the repo you created in the previous step:
az acr repository show \
--name mycontainerregistry \
--repository helm/hello-world
Она выводит выходные данные следующего вида:Output is similar to:
{
"changeableAttributes": {
"deleteEnabled": true,
"listEnabled": true,
"readEnabled": true,
"writeEnabled": true
},
"createdTime": "2020-03-20T18:11:37.6701689Z",
"imageName": "helm/hello-world",
"lastUpdateTime": "2020-03-20T18:11:37.7637082Z",
"manifestCount": 1,
"registry": "mycontainerregistry.azurecr.io",
"tagCount": 1
}
Чтобы просмотреть сведения о диаграмме, хранящейся в репозитории, выполните команду AZ запись в репозитории: Показать-манифесты .Run the az acr repository show-manifests command to see details of the chart stored in the repository. Пример.For example:
az acr repository show-manifests \
--name mycontainerregistry \
--repository helm/hello-world --detail
Выходные данные, сокращенные в этом примере, показывают configMediaType
application/vnd.cncf.helm.config.v1+json
:Output, abbreviated in this example, shows a configMediaType
of application/vnd.cncf.helm.config.v1+json
:
[
{
[...]
"configMediaType": "application/vnd.cncf.helm.config.v1+json",
"createdTime": "2020-03-20T18:11:37.7167893Z",
"digest": "sha256:0c03b71c225c3ddff53660258ea16ca7412b53b1f6811bf769d8c85a1f0663ee",
"imageSize": 3301,
"lastUpdateTime": "2020-03-20T18:11:37.7167893Z",
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"tags": [
"v1"
]
Извлечь диаграмму в локальный кэшPull chart to local cache
Чтобы установить Helm диаграмму в Kubernetes, эта диаграмма должна находиться в локальном кэше.To install a Helm chart to Kubernetes, the chart must be in the local cache. В этом примере сначала выполните команду, helm chart remove
чтобы удалить существующую локальную диаграмму с именем mycontainerregistry.azurecr.io/helm/hello-world:v1
:In this example, first run helm chart remove
to remove the existing local chart named mycontainerregistry.azurecr.io/helm/hello-world:v1
:
helm chart remove mycontainerregistry.azurecr.io/helm/hello-world:v1
Выполните команду helm chart pull
, чтобы скачать диаграмму из реестра контейнеров Azure в локальный кэш:Run helm chart pull
to download the chart from the Azure container registry to your local cache:
helm chart pull mycontainerregistry.azurecr.io/helm/hello-world:v1
Экспортировать Helm диаграммуExport Helm chart
Для дальнейшей работы с диаграммой экспортируйте ее в локальный каталог с помощью helm chart export
.To work further with the chart, export it to a local directory using helm chart export
. Например, экспортируйте диаграмму, которая была извлечена в install
Каталог:For example, export the chart you pulled to the install
directory:
helm chart export mycontainerregistry.azurecr.io/helm/hello-world:v1 \
--destination ./install
Чтобы просмотреть сведения о экспортированной диаграмме в репозитории, выполните helm show chart
команду в каталоге, в котором была экспортирована диаграмма.To view information for the exported chart in the repo, run the helm show chart
command in the directory where you exported the chart.
cd install
helm show chart hello-world
Helm возвращает подробные сведения о последней версии диаграммы, как показано в следующем примере выходных данных:Helm returns detailed information about the latest version of your chart, as shown in the following sample output:
apiVersion: v2
appVersion: 1.16.0
description: A Helm chart for Kubernetes
name: hello-world
type: application
version: 0.1.0
Установить Helm диаграммуInstall Helm chart
Выполните команду helm install
, чтобы установить диаграмму Helm, которая была извлечена в локальный кэш и экспортирована.Run helm install
to install the Helm chart you pulled to the local cache and exported. Укажите имя выпуска, например михелмтест, или передайте --generate-name
параметр.Specify a release name such as myhelmtest, or pass the --generate-name
parameter. Пример.For example:
helm install myhelmtest ./hello-world
Выходные данные после успешной установки диаграммы похожи на следующие:Output after successful chart installation is similar to:
NAME: myhelmtest
LAST DEPLOYED: Fri Mar 20 14:14:42 2020
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
Чтобы проверить установку, выполните helm get manifest
команду.To verify the installation, run the helm get manifest
command.
helm get manifest myhelmtest
Команда возвращает данные YAML в configmap.yaml
файле шаблона.The command returns the YAML data in your configmap.yaml
template file.
Выполните команду helm uninstall
, чтобы удалить выпуск диаграммы в кластере:Run helm uninstall
to uninstall the chart release on your cluster:
helm uninstall myhelmtest
Удалить диаграмму из реестраDelete chart from the registry
Чтобы удалить диаграмму из реестра контейнеров, используйте команду AZ запись репозитория Delete .To delete a chart from the container registry, use the az acr repository delete command. Выполните следующую команду и подтвердите операцию при появлении запроса:Run the following command and confirm the operation when prompted:
az acr repository delete --name mycontainerregistry --image helm/hello-world:v1
Дальнейшие действияNext steps
- Дополнительные сведения о создании и развертывании собственных диаграмм Helm см. в разделе документации, посвященном разработке диаграмм Helm.For more information on how to create and deploy Helm charts, see Developing Helm charts.
- Дополнительные сведения об установке приложений с помощью Helm в службе Kubernetes Azure (AKS).Learn more about installing applications with Helm in Azure Kubernetes Service (AKS).
- Диаграммы Helm можно использовать в процессе создания контейнеров.Helm charts can be used as part of the container build process. Дополнительные сведения см. в статье Использование задач реестра контейнеров Azure.For more information, see Use Azure Container Registry Tasks.