Compare languages | Модуль delivery: примеры конфигурации

Прежде чем начать

Before you begin

Раздел описывает особенности работы Argo CD в поставке с Deckhouse и предполагает наличие базовых знаний или предварительного знакомства с Argo CD.

This section describes how Argo CD works when bundled with Deckhouse and assumes you have basic understanding or prior knowledge of Argo CD.

Данные, которые используются в примерах ниже:

  • для доступа к веб-интерфейсу и API Argo CD выделен домен argocd в соответствии с шаблоном имен, определенным в параметре publicDomainTemplate. В примерах ниже используется адрес argocd.example.com;
  • myapp — название приложения;
  • mychart — название Helm-чарта и werf-бандла. В приведенной схеме они должны совпадать. Для большей ясности название Helm-чарта и werf-бандла выбрано отличным от названия приложения;
  • cr.example.com — хостнейм OCI-регистри;
  • cr.example.com/myproject — репозиторий бандла в OCI-регистри.

The following details are used in the examples below:

  • The argocd domain has been allocated according to the name template defined in the publicDomainTemplate parameter. It allows you to access the Argo CD web interface and the API. The examples below use argocd.example.com.
  • myapp is the name of the application.
  • mychart is the name of the Helm chart and werf bundle. They must match each other in the scheme below. For the sake of clarity, the name of the Helm chart and the werf bundle is different from the app name.
  • cr.example.com is the OCI registry’s hostname.
  • cr.example.com/myproject is the bundle repository in the OCI registry.

Концепция

The concept

Модуль предлагает способ развертывания приложений с помощью связки werf bundle и OCI-based registries.

The module implements a method of deploying applications using a combination of werf bundles and OCI-based registries.

Преимущество этого подхода заключается в том, что есть единое место доставки артефакта — container registry. Артефакт содержит в себе как образы контейнеров, так и Helm-чарт. Он используется как для первичного деплоя приложения, так и для автообновлений по pull-модели.

The advantage of this approach is that there is a single place to deliver the artifact — the container registry. The artifact contains both container images and the Helm chart. It is used both for the initial deployment of the application and for pull model auto-updates.

Используемые компоненты:

The following components are used:

  • Argo CD;
  • Argo CD Image Updater with OCI repository support patch;
  • werf-argocd-cmp-sidecar to keep werf annotations during manifest rendering.

Чтобы использовать OCI-registry как репозиторий, в параметрах репозитория Argo CD нужно использовать флаг enableOCI=true. Модуль delivery его устанавливает автоматически.

To use the OCI registry as a repository, you have to enable the enableOCI=true flag in the Argo CD repository settings. The delivery module does it automatically.

Чтобы автоматически обновлять приложения в кластере после доставки артефакта, используется Argo CD Image Updater. В Argo CD Image Updater внесены изменения, позволяющие ему работать с werf-бандлами.

Argo CD Image Updater automatically updates applications in the cluster once the artifact has been delivered. Argo CD Image Updater has been modified to work with werf bundles.

В примерах используется схема с шаблоном «Application of Applications», подразумевающая два git-репозитория — отдельный репозиторий для приложения и отдельный репозиторий для инфраструктуры: flow

The examples below use the «Application of Applications» pattern, which implies that there are two git repositories — a dedicated repository for the application, and a dedicated repository for the infrastructure: flow

Использование шаблона Application of Applications и отдельного репозитория для инфраструктуры не обязательно, если допускается создавать ресурсы Application вручную. Для простоты в примерах ниже мы будем придерживаться ручного управления ресурсами Application.

The use of the Application of Applications pattern and a separate infrastructure repository is not necessary if you are allowed to create Application resources manually. For the sake of simplicity, in the examples below we will manage Application resources manually.

Конфигурация с WerfSource CRD

WerfSource CRD-based configuration

Чтобы использовать Argo CD и Argo CD Image Updater, достаточно настроить объект Application и доступ к registry. Доступ к registry нужен в двух местах — в репозитории Argo CD и в конфигурации Argo CD Image Updater. Для этого нужно сконфигурировать:

All you need to do to use Argo CD and Argo CD Image Updater is to configure the Application object and access to the registry. Access to the registry is required for the Argo CD repository and Argo CD Image Updater. Thus, you have to configure:

  1. Secret для доступа к registry.
  2. Объект Application с конфигурацией приложения.
  3. Registry для Image Updater в его configMap, в нем будет ссылка на Secret (п. 1) для registry.
  4. Secret репозитория Argo CD, в нем будет копия параметров доступа из Secret’а (п. 1).
  1. Secret to access the registry.
  2. Application object containing the application configuration.
  3. Registry for Image Updater in its configMap (there will be a link to the registry Secret listed above as the first item).
  4. Secret for the Argo CD repository (it will contain a copy of the access credentials from the Secret listed as the first item).

Модуль delivery упрощает конфигурацию для использования werf bundle и Argo CD. Упрощение касается двух объектов: репозитория Argo CD и конфигурации registry для Image Updater. Эта конфигурация задается одним ресурсом — WerfBundle. Поэтому в рамках модуля нужно определить конфигурацию в трех местах:

The delivery module makes it easy to configure Deckhouse to work with werf bundles and Argo CD. Specifically, it streamlines the configuration of the Argo CD repository and the configuration of the Image Updater registry. All you have to do is define a single resource, the WerfBundle. Therefore, you have to configure three objects in the module:

  1. Secret для доступа к registry в формате dockerconfigjson.
  2. Объект Application с конфигурацией приложения.
  3. Объект WerfSource, содержащий информацию о registry и ссылку на Secret (п. 1) для доступа
  1. Secret in dockerconfigjson format to access the registry.
  2. Application object containing the application configuration.
  3. WerfSource object, which contains information about the registry and a link to the Secret (the one listed as the first item) used for access.

Таким образом, для деплоя из OCI-репозитория нужно создать три объекта. Все объекты, предполагающие область видимости namespace, должны быть созданы в namespace d8-delivery.

Thus, three objects need to be created for deploying from the OCI repository. Note that all namespaced objects must be created in the d8-delivery namespace.

Пример:

Example:

yaml

apiVersion: deckhouse.io/v1alpha1 kind: WerfSource metadata: name: example spec: imageRepo: cr.example.io/myproject # Репозиторий бандлов и образов. pullSecretName: example-registry # Secret с доступом. — apiVersion: v1 kind: Secret metadata: namespace: d8-delivery # Namespace модуля. name: example-registry type: kubernetes.io/dockerconfigjson # Поддерживается только этот тип Secret’ов. data: .dockerconfigjson: … — apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 0.0 name: myapp namespace: d8-delivery # Namespace модуля. spec: destination: namespace: myapp server: https://kubernetes.default.svc project: default source: chart: mychart # Бандл — cr.example.com/myproject/mychart. helm: {} repoURL: cr.example.com/myproject # Репозиторий Argo CD из WerfBundle. targetRevision: 1.0.0 syncPolicy: automated: prune: true selfHeal: true syncOptions:

  • CreateNamespace=true

yaml

apiVersion: deckhouse.io/v1alpha1 kind: WerfSource metadata: name: example spec: imageRepo: cr.example.io/myproject # bundle and image repository pullSecretName: example-registry # Secret with the credentials required for access — apiVersion: v1 kind: Secret metadata: namespace: d8-delivery # namespace of the module name: example-registry type: kubernetes.io/dockerconfigjson # only this Secret type is supported data: .dockerconfigjson: … — apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 0.0 name: myapp namespace: d8-delivery # namespace of the module spec: destination: namespace: myapp server: https://kubernetes.default.svc project: default source: chart: mychart # bundle — cr.example.com/myproject/mychart helm: {} repoURL: cr.example.com/myproject # Argo CD repository from WerfBundle targetRevision: 1.0.0 syncPolicy: automated: prune: true selfHeal: true syncOptions:

  • CreateNamespace=true

Публикация артефакта в registry

Publishing an artifact to the registry

OCI-чарт Helm требует, чтобы имя чарта в Chart.yaml совпадало с последним элементом пути в OCI-registry. Поэтому название чарта необходимо использовать в названии бандла:

The Helm OCI chart requires that the chart name in Chart.yaml be the same as the last element in the path to the OCI registry. This is why you have to include the chart name in the bundle name:

sh werf bundle publish –repo cr.example.com/myproject/mychart –tag 1.0.0

sh werf bundle publish –repo cr.example.com/myproject/mychart –tag 1.0.0

Подробнее о бандлах — в документации werf.

For more information about bundles, see the werf documentation.

Автообновление бандла

Bundle auto-updating

Argo CD Image Updater используется для автоматического обновления Application из опубликованного werf-бандла в pull-модели. Image Updater сканирует OCI-репозиторий с заданным интервалом и обновляет targetRevision в Application, посредством чего обновляется все приложение из обновленного артефакта. Мы используем измененный Image Updater, который умеет работать с OCI-registry и werf-бандлами.

As part of the pull model, Argo CD Image Updater automatically updates the Application using a published werf bundle. Image Updater scans the OCI repository at set intervals and updates targetRevision in the Application. This causes the entire application to be updated based on the updated artifact. We use a modified Image Updater that supports OCI registries and werf bundles.

Правила обновлений образов

The rules for updating images

В Application нужно добавить аннотацию с правилами обновления образа (подробнее — в документации werf).

You have to add an annotation to the Application object containing the rules governing image updates (see the werf documentation for details).

Пример правила, обновляющего патч-версии приложения (1.0.*):

Here is an example of a rule that updates a patch version of an application (1.0.*):

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0

Настройки доступа к registry

Access settings for the registry

У сервис-аккаунта argocd-image-updater есть права на работу с ресурсами только в namespace d8-delivery, поэтому именно в нем необходимо создать Secret с параметрами доступа к registry, на который ссылается поле credentials.

The argocd-image-updater service account can only work with resources in the d8-delivery namespace. Therefore, you must create a Secret in this exact namespace containing parameters to access the registry referenced by the credentials field.

Индивидуальная настройка для Application

Per-Application configuration

Сослаться на параметры доступа можно индивидуально в каждом Application с помощью аннотации argocd-image-updater.argoproj.io/pull-secret.

You can refer access credentials individually in each Application using the argocd-image-updater.argoproj.io/pull-secret annotation.

Пример:

Example:

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0 argocd-image-updater.argoproj.io/pull-secret: pullsecret:d8-delivery/example-registry

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0 argocd-image-updater.argoproj.io/pull-secret: pullsecret:d8-delivery/example-registry

Особенности аутентификации командной утилиты argocd

How to authenticate using the argocd CLI

Пользователь Argo CD

Argo CD user

Задайте username и password в конфигурации Argo CD или используйте пользователя admin. Пользователь admin по умолчанию выключен, поэтому его необходимо включить.

Set username and password in the Argo CD configuration or use the admin user. The admin user is disabled by default, so you have to enable it first.

Чтобы включить пользователя admin:

To do so:

  1. Откройте конфигурацию модуля delivery:
  1. Open the delivery module config:

sh kubectl edit mc delivery

sh kubectl edit mc delivery

  1. Установите параметр spec.settings.argocd.admin.enabled в true:
  1. Set spec.settings.argocd.admin.enabled to true:

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: delivery (…) spec: enabled: true settings: argocd: admin: enabled: true version: 1

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: delivery (…) spec: enabled: true settings: argocd: admin: enabled: true version: 1

kubectl

kubectl

Если настроен внешний доступ к Kubernetes API, argocd может использовать запросы к kube-apiserver:

If external access to Kubernetes API is configured, argocd can use requests to kube-apiserver:

sh argocd login argocd.example.com –core

sh argocd login argocd.example.com –core

Утилита argocd не позволяет указывать namespace во время вызова и рассчитывает на установленное значение в kubectl. Модуль delivery находится в namespace d8-delivery, поэтому на время работы с argocd нужно выбрать namespace d8-delivery для использования по умолчанию.

The argocd CLI does not allow namespace to be set at invocation time and relies on the value defined in kubectl. The delivery module is in the d8-delivery namespace, so you must set the d8-delivery namespace to be the default while working with argocd.

Выполните следующую команду для выбора namespace d8-delivery в качестве namespace по умолчанию:

Use the following command to set d8-delivery as the default namespace:

sh kubectl config set-context –current –namespace=d8-delivery

sh kubectl config set-context –current –namespace=d8-delivery

Dex

Dex

Авторизация через Dex не работает для CLI, но работает в веб-интерфейсе.

The Dex-based authorization does not work for the CLI, but it does in the web interface.

Вот так не работает, потому нет возможности зарегистрировать публичного клиента для DexClient, в роли которого выступает Argo CD:

That is, you cannot authorize via SSO because Dex Client in Deckhouse does not support public clients, in this case Argo CD:

sh argocd login argocd.example.com –sso

sh argocd login argocd.example.com –sso

Частичное использование WerfSource CRD

Partial WerfSource CRD usage scenarios

Без репозитория Argo CD

No Argo CD repository

WerfSource отвечает за создание репозитория в Argo CD и внесение registry в конфигурацию Image Updater. От создания репозитория можно отказаться в WerfSource, для этого нужно установить параметр spec.argocdRepoEnabled=false. Это пригодится, если используется тип репозитория, отличный от OCI, например Chart Museum или git:

WerfSource creates a repository on the Argo CD and adds registry information to the Image Updater configuration. However, it also allows you to skip the repository creation. To do so, set the spec.argocdRepoEnabled parameter to false (spec.argocdRepoEnabled=false). This comes in handy when using a repository type other than OCI, e.g., Chart Museum or git:

yaml

apiVersion: deckhouse.io/v1alpha1 kind: WerfSource metadata: name: example spec: … argocdRepoEnabled: false

yaml

apiVersion: deckhouse.io/v1alpha1 kind: WerfSource metadata: name: example spec: … argocdRepoEnabled: false

Как самостоятельно создать репозиторий Argo CD для OCI-registry

How to manually create an Argo CD repository for the OCI registry

Registry играет роль репозитория бандлов. Чтобы это работало, нужно в репозитории включить режим OCI. Однако веб-интерфейс не позволяет установить флаг enableOCI, поэтому его нужно добавить вне веб-интерфейса.

The registry acts as a repository for the bundles. To use it, you will have to enable OCI mode in the repository. Unfortunately, the web interface does not allow you to set the enableOCI flag, so you must add it by other means.

Argo CD CLI

Using the Argo CD CLI

Утилита argocd поддерживает флаг --enable-oci:

The argocd CLI tool supports the --enable-oci flag:

sh $ argocd repo add cr.example.com/myproject
–enable-oci
–type helm
–name REPO_NAME
–username USERNAME
–password PASSWORD

sh $ argocd repo add cr.example.com/myproject
–enable-oci
–type helm
–name REPO_NAME
–username USERNAME
–password PASSWORD

Веб-интерфейс и kubectl

Using the web interface and kubectl

В существующий репозиторий недостающий флаг можно добавить вручную:

The missing flag can be added manually to an existing repository:

sh kubectl -n d8-delivery edit secret repo-….

sh kubectl -n d8-delivery edit secret repo-….

yaml apiVersion: v1 kind: Secret stringData: # <—– Добавить enableOCI: “true” # <—– и сохранить. data: (…) metadata: (…) name: repo-…. namespace: d8-delivery type: Opaque

yaml apiVersion: v1 kind: Secret stringData: # <—– add enableOCI: “true” # <—– and save data: (…) metadata: (…) name: repo-…. namespace: d8-delivery type: Opaque

Без registry для Image Updater

No registry for Image Updater

Registry в configmap/argocd-image-updater-config могут быть настроены только через WerfSource, потому что deckhouse генерирует этот ConfigMap, используя объекты WerfSource. Если этот способ не подходит, конфигурацию Image Updater можно задать с помощью аннотаций в каждом Application индивидуально:

The registries in configmap/argocd-image-updater-config can only be configured via WerfSource because Deckhouse generates this ConfigMap using the WerfSource objects. If this approach is not suitable for some reason, Image Updater can be configured using annotations in each Application individually:

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0 argocd-image-updater.argoproj.io/pull-secret: pullsecret:d8-delivery/example-registry

yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: annotations: argocd-image-updater.argoproj.io/chart-version: ~ 1.0 argocd-image-updater.argoproj.io/pull-secret: pullsecret:d8-delivery/example-registry