Skip to content

Commit

Permalink
Merge pull request #6121 from werf/docs-new-werf-io-deploy-dependency…
Browse files Browse the repository at this point in the history
…-annotation

docs(deploy): new `werf.io/deploy-dependency-<name>` annotation
  • Loading branch information
ilya-lesikov committed May 22, 2024
2 parents a71ab9e + 5e171fd commit d82e496
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 8 deletions.
21 changes: 21 additions & 0 deletions docs/pages_en/reference/deploy_annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ toc: false
This article contains description of annotations which control werf resource operations and tracking of resources during deploy process. Annotations should be configured in the chart templates.

- [`werf.io/weight`](#resource-weight) — defines the weight of the resource, which will affect the order in which the resources are deployed.
- [`werf.io/deploy-dependency-ANY_NAME`](#resource-dependencies) — define a dependency for the resource, which will affect the order in which the resources are deployed.
- [`<any-name>.external-dependency.werf.io/resource`](#external-dependency-resource) — wait for specified external dependency to be up and running, and only then proceed to deploy the annotated resource.
- [`<any-name>.external-dependency.werf.io/namespace`](#external-dependency-namespace) — specify the namespace for the external dependency.
- [`werf.io/replicas-on-creation`](#replicas-on-creation) — defines number of replicas that should be set only when creating resource initially (useful for HPA).
Expand Down Expand Up @@ -41,6 +42,26 @@ This parameter sets the weight of the resources, defining the order in which the

More info: [deployment order]({{ "/usage/deploy/deployment_order.html" | true_relative_url }})

## Resource dependencies

`werf.io/deploy-dependency-ANY_NAME: [state=STATE] [name=NAME] [namespace=NAMESPACE] [kind=KIND] [group=GROUP] [version=VERSION]`

Example: \
`werf.io/deploy-dependency-db: state=ready kind=StatefulSet name=postgres` \
`werf.io/deploy-dependency-app: state=present kind=Deployment group=apps version=v1 name=app namespace=app`

Required parameters:
- "state": `ready` or `present`. If `present`, then wait until resource is created/updated, if `ready`, then wait until resource is created/updated and ready.

At least one of these parameters must be specified:
- "name": name of a resource to depend on.
- "namespace": namespace of a resource to depend on.
- "kind": kind of a resource to depend on.
- "group": api group of a resource to depend on.
- "version": api version of a resource to depend on.

More info: [deployment order]({{ "/usage/deploy/deployment_order.html" | true_relative_url }})

## External dependency resource

`<any-name>.external-dependency.werf.io/resource: type[.version.group]/name`
Expand Down
51 changes: 47 additions & 4 deletions docs/pages_en/usage/deploy/deployment_order.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ Kubernetes resources are deployed in the following stages:

1. Deploying `CustomResourceDefinitions` from the `crds` directories of the included charts.

2. Deploying `pre-install`, `pre-upgrade` or `pre-rollback` hooks one hook at a time, starting with hooks with less weight to greater weight. If a hook is dependent on an external resource, it will only be deployed once that resource is ready.
2. Deploying `pre-install`, `pre-upgrade` or `pre-rollback` hooks, starting with hooks with less weight to greater weight.

3. Deploying basic resources: the resources with the same weight are combined into groups (resources without a specified weight are assigned a weight of 0) and deployed one group at a time, starting with groups with lower-weight resources to groups with higher-weight resources. If a resource in a group depends on an external resource, the group will be deployed only after that resource is ready.
3. Deploying basic resources: the resources with the same weight are combined into groups (resources without a specified weight are assigned a weight of 0) and deployed one group at a time, starting with groups with lower-weight resources to groups with higher-weight resources.

4. Deploying `post-install`, `post-upgrade` or `post-rollback` hooks one hook at a time, starting with hooks with less weight to ones with greater weight. If a hook is dependent on an external resource, it will be deployed only after that resource is ready.
4. Deploying `post-install`, `post-upgrade` or `post-rollback` hooks, starting with hooks with less weight to ones with greater weight.

Resources with `werf.io/deploy-dependency-<name>` annotation do not belong to any stage and are deployed as soon as their dependencies satisfied.

## Deploying CustomResourceDefinitions

Expand Down Expand Up @@ -44,7 +46,7 @@ werf converge

In this case, the CRD for the CronTab resource will be deployed first, followed by the CronTab resource.

## Changing the order in which resources are deployed (werf only)
## Resource deployments ordering via weight groups (werf only)

By default, werf combines all the main resources ("main" means those are not hooks or CRDs from `crds/*.yaml`) into one group, creates resources for that group and tracks their readiness.

Expand Down Expand Up @@ -89,6 +91,47 @@ werf converge

In this case, the `database` resource was deployed first, followed by `database-migrations`, and then `app1` and `app2` were deployed in parallel.

## Resource deployments ordering via direct dependencies (werf only)

Annotation `werf.io/deploy-dependency-<name>` can be used to set resources ordering during deployment. These resources will not belong to any particular resource group or stage and are deployed as soon as their dependencies are satisfied, for example:

```
# .helm/templates/example.yaml:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
# ...
---
apiVersion: batch/v1
kind: Job
metadata:
name: database-migrations
annotations:
werf.io/deploy-dependency-db: kind=StatefulSet name=database state=ready
# ...
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: app1
annotations:
werf.io/deploy-dependency-migrations: kind=Job name=database-migrations state=ready
# ...
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: app2
annotations:
werf.io/deploy-dependency-migrations: kind=Job name=database-migrations state=ready
# ...
```

In this case, the `database` resource was deployed first, followed by `database-migrations`, and then `app1` and `app2` were deployed in parallel.

This is a more flexible and effective way to set the order of resource deployments in comparison to `werf.io/weight` and other methods, as it allows you to deploy resources in a graph-like order.

## Running tasks before/after installing, upgrading, rolling back or deleting a release

To deploy certain resources before or after installing, upgrading, rolling back or deleting a release, convert the resource to a *hook* by adding the `helm.sh/hook` annotation to it, for example:
Expand Down
21 changes: 21 additions & 0 deletions docs/pages_ru/reference/deploy_annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ toc: false
Данная статья содержит описание аннотаций, которые меняют поведение механизма отслеживания ресурсов в процессе выката с помощью werf. Все аннотации должны быть объявлены в шаблонах чарта.

- [`werf.io/weight`](#resource-weight) — задает вес ресурса, который определяет порядок развертывания ресурсов.
- [`werf.io/deploy-dependency-ANY_NAME`](#resource-dependencies) — задать зависимость от другого ресурса, что повлияет на порядок развертывания ресурсов.
- [`<any-name>.external-dependency.werf.io/resource`](#external-dependency-resource) — дождаться, пока указанная внешняя зависимость будет запущена, и только после этого приступить к развертыванию аннотированного ресурса.
- [`<any-name>.external-dependency.werf.io/namespace`](#external-dependency-namespace) — задать пространство имен для внешней зависимости.
- [`werf.io/replicas-on-creation`](#replicas-on-creation) — задаёт количество реплик, которое должно быть установлено при первичном создании ресурса (полезно при использовании HPA).
Expand Down Expand Up @@ -38,6 +39,26 @@ toc: false

Дополнительная информация доступна в разделе [Порядок развертывания]({{ "/usage/deploy/deployment_order.html" | true_relative_url }}).

## Resource dependencies

`werf.io/deploy-dependency-ANY_NAME: [state=STATE] [name=NAME] [namespace=NAMESPACE] [kind=KIND] [group=GROUP] [version=VERSION]`

Пример: \
`werf.io/deploy-dependency-db: state=ready kind=StatefulSet name=postgres` \
`werf.io/deploy-dependency-app: state=present kind=Deployment group=apps version=v1 name=app namespace=app`

Обязательные параметры:
- "state": `ready` или `present`. Если `present`, то дождаться, пока ресурс не будет создан/обновлен, если `ready`, то дождаться, пока ресурс не будет создан/обновлен и приведен в готовность.

Как минимум один из этих параметров требуется указать:
- "name": имя ресурса, от которого будет зависеть текущий ресурс.
- "namespace": namespace ресурса, от которого будет зависеть текущий ресурс.
- "kind": kind ресурса, от которого будет зависеть текущий ресурс.
- "group": api group ресурса, от которого будет зависеть текущий ресурс.
- "version": api version ресурса, от которого будет зависеть текущий ресурс.

Больше информации: [порядок развертывания]({{ "/usage/deploy/deployment_order.html" | true_relative_url }})

## External dependency resource

`<any-name>.external-dependency.werf.io/resource: type[.version.group]/name`
Expand Down
51 changes: 47 additions & 4 deletions docs/pages_ru/usage/deploy/deployment_order.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ permalink: usage/deploy/deployment_order.html

1. Развертывание `CustomResourceDefinitions` из директорий `crds` подключенных чартов.

2. Развертывание хуков `pre-install`, `pre-upgrade` или `pre-rollback` по одному хуку за раз, от хуков с меньшим весом к большему. Если хук имеет зависимость от внешнего ресурса, то он развернётся только после его готовности.
2. Развертывание хуков `pre-install`, `pre-upgrade` или `pre-rollback`, от хуков с меньшим весом к большему.

3. Развертывание основных ресурсов: объединение ресурсов с одинаковым весом в группы (ресурсы без указанного веса имеют вес 0) и развертывание по одной группе за раз, от групп с ресурсами меньшего веса к группам с ресурсами большего веса. Если ресурс в группе имеет зависимость от внешнего ресурса, то она начнёт развертывание только после его готовности.
3. Развертывание основных ресурсов: объединение ресурсов с одинаковым весом в группы (ресурсы без указанного веса имеют вес 0) и развертывание по одной группе за раз, от групп с ресурсами меньшего веса к группам с ресурсами большего веса.

4. Развертывание хуков `post-install`, `post-upgrade` или `post-rollback` по одному хуку за раз, от хуков с меньшим весом к большему. Если хук имеет зависимость от внешнего ресурса, то он развернётся только после его готовности.
4. Развертывание хуков `post-install`, `post-upgrade` или `post-rollback`, от хуков с меньшим весом к большему.

Ресурсы с аннотацией `werf.io/deploy-dependency-<name>` не принадлежат ни к одной стадии и развертываются сразу после того, как их зависимости удовлетворены.

## Развертывание CustomResourceDefinitions

Expand Down Expand Up @@ -44,7 +46,7 @@ werf converge

Результат: сначала развернут CRD для CronTab-ресурса, а затем развернут сам CronTab-ресурс.

## Изменение порядка развертывания ресурсов (только в werf)
## Изменение порядка развертывания ресурсов с помощью группировки по весу (только в werf)

По умолчанию werf объединяет все основные ресурсы (основные — не являющиеся хуками или CRDs из `crds/*.yaml`) в одну группу, создаёт ресурсы этой группы, а затем отслеживает их готовность.

Expand Down Expand Up @@ -89,6 +91,47 @@ werf converge

Результат: сначала был развернут ресурс `database`, затем — `database-migrations`, а затем параллельно развернулись `app1` и `app2`.

## Изменение порядка развертывания ресурсов с помощью прямых зависимостей (только в werf)

Аннотация `werf.io/deploy-dependency-<name>` позволяет задать порядок развертывания ресурсов. Такие ресурсы не будут принадлежать ни к одной группе ресурсов по весу или стадии и будут развернуты сразу после того, как их зависимости удовлетворены, например:

```
# .helm/templates/example.yaml:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
# ...
---
apiVersion: batch/v1
kind: Job
metadata:
name: database-migrations
annotations:
werf.io/deploy-dependency-db: kind=StatefulSet name=database state=ready
# ...
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: app1
annotations:
werf.io/deploy-dependency-migrations: kind=Job name=database-migrations state=ready
# ...
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: app2
annotations:
werf.io/deploy-dependency-migrations: kind=Job name=database-migrations state=ready
# ...
```

Результат: сначала был развернут ресурс `database`, затем — `database-migrations`, а затем параллельно развернулись `app1` и `app2`.

Это более гибкий и эффективный способ задания порядка развертывания ресурсов по сравнению с использованием `werf.io/weight` и других методов, т. к. позволяет развертывать ресурсы в порядке графа.

## Запуск задач перед/после установки, обновления, отката или удаления релиза

Для развертывания определенных ресурсов только перед или после установки, обновления, отката или удаления релиза преобразуйте ресурс в *хук* аннотацией `helm.sh/hook`, например:
Expand Down

0 comments on commit d82e496

Please sign in to comment.