fleet.yaml

O arquivo fleet.yaml adiciona opções a um bundle. Qualquer diretório com um arquivo fleet.yaml é automaticamente transformado em um bundle.

Para mais informações sobre como personalizar bundles usando fleet.yaml, veja Conteúdos do Repositório Git.

O conteúdo de fleet.yaml corresponde à estrutura FleetYAML em fleetyaml.go, que contém o BundleSpec.

Exemplo Completo

Details
fleet.yaml
# The default namespace to be applied to resources. This field is not used to
# enforce or lock down the deployment to a specific namespace, but instead
# provide the default value of the namespace field if one is not specified in
# the manifests.
#
# Default: default
defaultNamespace: default

# All resources will be assigned to this namespace and if any cluster scoped
# resource exists the deployment will fail.
#
# Default: ""
namespace: default

# namespaceLabels are labels that will be appended to the namespace created by
# Fleet.
namespaceLabels:
  key: value

# namespaceAnnotations are annotations that will be appended to the namespace
# created by Fleet.
namespaceAnnotations:
  key: value

# Name of the bundle. If not specified, the bundle name will be computed based
# on the GitRepo's name, and the path from which the bundle is created.
# Default: ""
name: my-great-bundle

# Optional map of labels, that are set at the bundle and can be used in a
# dependsOn.selector
labels:
  key: value

kustomize:
  # Use a custom folder for kustomize resources. This folder must contain a
  # kustomization.yaml file.
  dir: ./kustomize

helm:

  # These options control how "fleet apply" downloads the chart
  # (See `Helm Options` below for more details)
  #
  chart: ./chart

  # A https URL to a Helm repo to download the chart from, or an OCI registry
  # URL (oci://...). For OCI registries, repo is the canonical field and no
  # chart name is needed. For standard Helm repos, the value of `chart` is used
  # as the chart name to look up in the repository.
  repo: https://charts.rancher.io

  # The version of the chart or semver constraint of the chart to find. If a
  # constraint is specified, it is evaluated each time git changes.
  # (See `Helm Options` below for more details)
  version: 0.1.0

  # By default fleet downloads any dependency found in a helm chart.  Use
  # disableDependencyUpdate: true to disable this feature.
  disableDependencyUpdate: false

  ### These options only work for helm-type bundles.
  #
  # Any values that should be placed in the `values.yaml` and passed to helm
  # during install.
  values:

    any-custom: value

    # All labels on Rancher clusters are available using
    # global.fleet.clusterLabels.LABELNAME These can now be accessed directly as
    # variables The variable's value will be an empty string if the referenced
    # cluster label does not exist on the targeted cluster.
    variableName: global.fleet.clusterLabels.LABELNAME

    # See Templating notes below for more information on templating.
    templatedLabel: "${ .ClusterLabels.LABELNAME }-foo"

    valueFromEnv:
      "${ .ClusterLabels.ENV }": ${ .ClusterValues.someValue | upper | quote }

  # Path to any values files that need to be passed to helm during install.
  valuesFiles:
    - values1.yaml
    - values2.yaml

  # Allow to use values files from configmaps or secrets defined in the
  # downstream clusters.
  valuesFrom:
    - configMapKeyRef:
        name: configmap-values
        # default to namespace of bundle
        namespace: default
        key: values.yaml
    - secretKeyRef:
        name: secret-values
        namespace: default
        key: values.yaml

  ### These options control how fleet-agent deploys the bundle, they also apply
  ### for kustomize- and manifest-style bundles.
  #
  # A custom release name to deploy the chart as. If not specified a release name
  # will be generated by combining the invoking GitRepo.name + GitRepo.path.
  releaseName: my-release
  #
  # Makes helm skip the check for its own annotations
  takeOwnership: false
  #
  # Override immutable resources. This could be dangerous.
  force: false
  #
  # Set the Helm --atomic flag when upgrading
  atomic: false
  #
  # Disable go template pre-processing on the fleet values
  disablePreProcess: false
  #
  # Disable DNS resolution in Helm's template functions
  disableDNS: false
  #
  # Skip evaluation of the values.schema.json file
  skipSchemaValidation: false
  #
  # If set and timeoutSeconds provided, will wait until all Jobs have been
  # completed before marking the GitRepo as ready.  It will wait for as long as
  # timeoutSeconds.
  waitForJobs: true

# A paused bundle will not update downstream clusters but instead mark the bundle
# as OutOfSync. One can then manually confirm that a bundle should be deployed to
# the downstream clusters.
#
# Default: false
paused: false

# If rolloutStrategy is not defined in the fleet.yaml file, Fleet uses default rollout values.
rolloutStrategy:

  # A number or percentage of clusters that can be unavailable during an update
  # of a bundle. This follows the same basic approach as a deployment rollout
  # strategy. Once the number of clusters meets unavailable state update will be
  # paused. Default value is 100% which doesn't take effect on update.
  #
  # default: 100%
  maxUnavailable: 15%

  # A number or percentage of cluster partitions that can be unavailable during
  # an update of a bundle.
  #
  # default: 0
  maxUnavailablePartitions: 20%

  # A number or percentage of how to automatically partition clusters if not
  # specific partitioning strategy is configured.
  # The default value is defined in rolloutStrategy.maxUnavailable
  autoPartitionSize: 10%

  # The minimum number of clusters that need to be present before
  # auto-partitioning is enabled. If the number of target clusters is less
  # than this value, all clusters will be placed in a single partition.
  #
  # default: 200
  autoPartitionThreshold: 100

  # The maximum number of new BundleDeployments that can be created in a
  # single reconciliation. This limits the rate at which new deployments are
  # staged when a bundle is first applied to many clusters.
  #
  # default: 50
  maxNew: 50

  # A list of definitions of partitions.  If any target clusters do not match
  # the configuration they are added to partitions at the end following the
  # autoPartitionSize.
  partitions:

    # A user friend name given to the partition used for Display (optional).
    # default: ""
    - name: canary

      # A number or percentage of clusters that can be unavailable in this
      # partition before this partition is treated as done.
      # default: 10%
      maxUnavailable: 10%

      # Selector matching cluster labels to include in this partition
      clusterSelector:
        matchLabels:
          env: prod

      # OR, if selecting by ClusterGroup labels:
      clusterGroupSelector:
        matchLabels:
          env: prod

      # A cluster group name to include in this partition
      clusterGroup: agroup


# Target customization are used to determine how resources should be modified
# per target Targets are evaluated in order and the first one to match a cluster
# is used for that cluster.
targetCustomizations:

  # The name of target. If not specified a default name of the format
  # "target000" will be used. This value is mostly for display
  - name: prod

    # Custom namespace value overriding the value at the root.
    namespace: newvalue

    # Custom defaultNamespace value overriding the value at the root.
    defaultNamespace: newdefaultvalue

    # Custom kustomize options overriding the options at the root.
    kustomize: {}

    # Custom Helm options override the options at the root.
    helm: {}

    # If using raw YAML these are names that map to overlays/{name} that will be
    # used to replace or patch a resource. If you wish to customize the file
    # ./subdir/resource.yaml then a file
    # ./overlays/myoverlay/subdir/resource.yaml will replace the base file.  A
    # file named ./overlays/myoverlay/subdir/resource_patch.yaml will patch the
    # base file.  A patch can in JSON Patch or JSON Merge format or a strategic
    # merge patch for builtin Kubernetes types. Refer to "Raw YAML Resource
    # Customization" below for more information.
    yaml:
      overlays:
        - custom2
        - custom3

    # A selector used to match clusters.  The structure is the standard
    # metav1.LabelSelector format. If clusterGroupSelector or clusterGroup is
    # specified, clusterSelector will be used only to further refine the
    # selection after clusterGroupSelector and clusterGroup is evaluated.
    clusterSelector:
      matchLabels:
        env: prod

    # A selector used to match a specific cluster by name. When using Fleet in
    # Rancher, make sure to put the name of the clusters.fleet.cattle.io
    # resource.
    clusterName: dev-cluster

    # A selector used to match cluster groups.
    clusterGroupSelector:
      matchLabels:
        region: us-east

    # A specific clusterGroup by name that will be selected.
    clusterGroup: group1

    # Resources will not be deployed in the matched clusters if doNotDeploy is
    # true.
    doNotDeploy: false

    # Drift correction removes any external change made to resources managed by
    # Fleet.  It performs a helm rollback, which uses a three-way merge strategy
    # by default.  It will try to update all resources by doing a PUT request if
    # force is enabled.  Three-way strategic merge might fail when updating an
    # item inside of an array as it will try to add a new item instead of
    # replacing the existing one.  This can be fixed by using force.  Keep in
    # mind that resources might be recreated if force is enabled.  Failed
    # rollback will be removed from the helm history unless keepFailHistory is
    # set to true.
    correctDrift:
      enabled: false
      force: false # Warning: it might recreate resources if set to true
      keepFailHistory: false

# dependsOn allows you to configure dependencies to other bundles. The current
# bundle will only be deployed, after all dependencies are deployed an
# accepted state. The default accepted state is the Ready state.
dependsOn:

  # Format:
  #     <GITREPO-NAME>-<BUNDLE_PATH> with all path separators replaced by "-"
  #
  # Example:
  #
  #      GitRepo name "one", Bundle path "/multi-cluster/hello-world"
  #      results in "one-multi-cluster-hello-world".
  #
  # Note:
  #
  #   Bundle names are limited to 53 characters long. If longer they will be
  #   shortened:
  #
  #     opni-fleet-examples-fleets-opni-ui-plugin-operator-crd becomes
  #     opni-fleet-examples-fleets-opni-ui-plugin-opera-021f7
  - name: one-multi-cluster-hello-world
      acceptedStates:
        - Ready
        - Modified
  # Select bundles to depend on based on their label.
  - selector:
      matchLabels:
        app: weak-monkey
    acceptedStates:
      - Ready
      - Modified

# Ignore fields when monitoring a Bundle. This can be used when Fleet thinks
# some conditions in Custom Resources makes the Bundle to be in an error state
# when it shouldn't.
ignore:

  # Conditions to be ignored
  conditions:

    # In this example a condition will be ignored if it contains
    # {"type": "Active", "status", "False"}
    - type: Active
      status: "False"

# Override targets defined in the GitRepo. The Bundle will not have any targets
# from the GitRepo if overrideTargets is provided.
overrideTargets:
  - clusterSelector:
      matchLabels:
        env: dev

Configuração Geral do Bundle

Essas opções definem as propriedades e o comportamento fundamentais do bundle em si e se aplicam a todos os tipos de bundle.

Opção Descrição Aplica-se a

paused

Se verdadeiro, o bundle não será atualizado em clusters downstream. Em vez disso, será marcado como Fora de Sincronização. Você pode então aprovar manualmente a implantação.

Todos

labels

Um mapa de pares chave-valor definidos no nível do bundle. Esses podem ser usados em um dependsOn.selector para definir dependências.

Todos

dependsOn

Uma lista de bundles dos quais este bundle depende. O bundle atual é implantado somente após todas as dependências estarem em um estado aceito. Estados aceitos correspondem a qualquer estado de bundle válido.

Todos

ignore

Especifica campos a serem ignorados ao monitorar o status do bundle. Útil para evitar estados de erro falsos de Recursos Personalizados.

Todos

overrideTargets

Uma lista de personalizações de destino que substituem quaisquer alvos definidos no GitRepo.

Todos

Configuração de Namespace

Essas opções controlam o namespace do Kubernetes onde os recursos serão implantados.

Opção Descrição Aplica-se a

defaultNamespace

Namespace padrão para recursos que não especificam um.

Todos

namespace

Atribui todos os recursos no bundle a este namespace. Falha se existirem recursos com escopo de cluster.

Todos

namespaceLabels

Rótulos a serem adicionados ao namespace criado por SUSE® Rancher Prime Continuous Delivery.

Todos

namespaceAnnotations

Anotações a serem adicionadas ao namespace criado por SUSE® Rancher Prime Continuous Delivery.

Todos

Configuração do Bundle Helm

Todos os bundles são implantados usando o Helm, mas essas opções são específicas para bundles no estilo Helm (aqueles com um arquivo Chart.yaml).

As configurações helm.chart, helm.repo e helm.version definidas na raiz de fleet.yaml determinam qual gráfico Helm o Fleet baixa.

O Fleet baixa o gráfico durante a fase inicial de criação do Bundle. Isso ocorre antes que targetCustomizations sejam processados. Como resultado, targetCustomizations não pode ser usado para selecionar uma fonte de gráfico diferente para clusters individuais, como:

  • um diretório de gráfico local diferente

  • um repositório Helm separado

  • um registro OCI diferente

Se um cluster específico deve usar um registro ou fonte de gráfico diferente (por exemplo, devido a restrições de rede ou gateway de segurança), configure-o usando um recurso GitRepo separado ou um caminho de bundle diferente.

Fonte do Gráfico

Essas opções especificam como baixar o gráfico. A referência pode ser um caminho local, URL do go-getter, repositório Helm ou repositório OCI do Helm.

Opção Descrição Aplica-se a

helm.chart

A localização do gráfico Helm (caminho local ou URL do go-getter). Para registros OCI, use helm.repo em vez disso (veja abaixo).

Helm

helm.repo

URL de um repositório Helm ou registro OCI (oci://…​).

Helm

helm.version

Versão do gráfico ou restrição semver. Reavaliado em cada alteração do git.

Helm

helm.disableDependencyUpdate

Se verdadeiro, desabilita downloads automáticos de dependências.

Helm

A referência do gráfico pode ser uma das seguintes:

  • Caminho local (chart)

  • go-getter URL (chart)

  • URL do gráfico OCI (repo: oci://…​)

  • Repositório Helm (repo + chart + version opcional)

  • Repositório OCI Helm (repo: oci://…​ + version opcional)

helm.repo

Para registros OCI, helm.repo é o campo canônico para a URL OCI. Use assim:

helm:
  repo: "oci://ghcr.io/fleetrepoci/guestbook"
  version: "0.1.0"  # optional

Isso é consistente com a forma como os registros OCI são referenciados em recursos HelmOp.

helm.chart

Especifica um caminho local ou URL do go-getter para o gráfico Helm. Quando helm.repo é definido como uma URL de repositório Helm padrão (não OCI), helm.chart contém o nome do gráfico dentro desse repositório.

Se um segredo para a chave SSH foi definido via helmSecretName, ele é injetado automaticamente.

Se o arquivo fleet.yaml estiver localizado fora do diretório do gráfico incorporado, ele deve referenciar explicitamente o gráfico usando helm.chart. Caso contrário, SUSE® Rancher Prime Continuous Delivery não instalará o gráfico, e campos específicos do Helm como valuesFiles ou valuesFrom não terão efeito.

Limitação: Baixar gráficos do Helm do Git com pacotes CA personalizados não funciona. Se um pacote CA estiver configurado em um segredo referenciado em helmSecretName, ele será ignorado. Veja fleet#3646 para mais detalhes.

Descontinuado: Colocar uma URL OCI (por exemplo, oci://…​) em helm.chart está descontinuado. Use helm.repo para URLs OCI em vez disso.

# Deprecated - still works, but produces a warning in Fleet logs:
helm:
  chart: "oci://ghcr.io/fleetrepoci/guestbook"

# Preferred:
helm:
  repo: "oci://ghcr.io/fleetrepoci/guestbook"

helm.version

Determina qual gráfico baixar dos registros OCI.

Registros OCI não suportam o caractere ` em tags semver. O Helm substitui ` por _ automaticamente ao enviar gráficos. Use a versão + em fleet.yaml; SUSE® Rancher Prime Continuous Delivery realiza a mesma substituição internamente.

Valores

Opções para personalizar os valores do gráfico Helm.

Opção Descrição Aplica-se a

helm.values

Pares chave-valor passados para o Helm como valores personalizados. Suporta templates.

Helm

helm.valuesFiles

Caminhos para arquivos de valores passados para o Helm.

Helm

helm.valuesFrom

Carregar valores de ConfigMaps ou Segredos em clusters downstream.

Helm

Não é necessário especificar o próprio values.yaml de um gráfico. É sempre usado por padrão.

Veja Usando Valores do Helm para mais informações.

Para estágios de processamento de valores, consulte Ciclo de vida do bundle.

Templates de Valores

O SUSE® Rancher Prime Continuous Delivery suporta expressões de template Go para necessidades avançadas de templates. Veja as funções de template Sprig para funções disponíveis.

Evite funções que produzem saída aleatória (por exemplo, uuidv4), pois elas acionam reimplantação.

Você pode testar valores de template com a CLI, consulte fleet-target.

Chaves de contexto do template:

  • .ClusterValues

  • .ClusterLabels

  • .ClusterAnnotations

  • .ClusterName

  • .ClusterNamespace

Exemplo:

${ get .ClusterLabels "management.cattle.io/cluster-display-name" }

O SUSE® Rancher Prime Continuous Delivery utiliza delimitadores ${ } (não os {{ }} do Helm). Escape-os usando crases:

foo-bar-${`${PWD}`}

Saídas:

foo-bar-${PWD}

Ao usar template, proteja-se contra valores nulos.

Exemplo:

${ if hasKey .ClusterLabels "LABELNAME" }${ .ClusterLabels.LABELNAME }${ else }missing${ end}

Implantação do Helm

Essas opções controlam como o agente do Fleet implanta recursos. Elas também se aplicam a kustomize- e pacotes de estilo manifest.

Opção Descrição Aplica-se a

helm.releaseName

Nome de lançamento personalizado. Padrão para um nome gerado.

Todos

helm.takeOwnership

Ignorar verificações de anotação.

Todos

helm.force

Substituir recursos imutáveis.

Todos

helm.atomic

Usar a flag --atomic do Helm.

Todos

helm.waitForJobs

Aguarde todos os Jobs antes de marcar o GitRepo como pronto.

Todos

helm.disablePreProcess

Desativar pré-processamento de template Go.

Todos

helm.disableDNS

Desativar resolução de DNS em templates.

Todos

helm.skipSchemaValidation

Pule a validação values.schema.json.

Todos

Configuração do Kustomize

Usado ao implantar a partir de um diretório contendo um arquivo kustomization.yaml.

Opção

Descrição

Aplica-se a

kustomize.dir

Pasta personalizada para recursos do Kustomize. Deve conter um arquivo kustomization.yaml.

Kustomize

Estratégia de Implantação (Rollout)

Essas opções controlam como as atualizações são distribuídas nos clusters.

Opção Descrição Aplica-se a

rolloutStrategy.maxUnavailable

Máximo de clusters indisponíveis durante a atualização.

Todos

rolloutStrategy.maxUnavailablePartitions

Máximo de partições indisponíveis durante a atualização.

Todos

rolloutStrategy.autoPartitionSize

Tamanho automático da partição para clusters.

Todos

rolloutStrategy.autoPartitionThreshold

O número mínimo de clusters exigido antes que a auto-partição seja ativada. Abaixo desse limite, todos os clusters são colocados em uma única partição.

Todos

rolloutStrategy.maxNew

Número máximo de novos BundleDeployments que podem ser preparados por reconciliação. O padrão é 50.

Todos

rolloutStrategy.partitions

Define partições de cluster para implantações em fases.

Todos

Para mais informações, veja Estratégia de Rollout.

Direcionamento e Personalização

Essas opções permitem personalizar implantações para clusters ou grupos de clusters específicos.

Opção Descrição Aplica-se a

targetCustomizations

Lista de regras para modificar recursos por alvo.

Todos

targetCustomizations.name

Nome de exibição para personalização.

Todos

targetCustomizations.clusterSelector

Selecionador de rótulos do Kubernetes para clusters.

Todos

targetCustomizations.clusterGroup

Nome do grupo de clusters a ser direcionado.

Todos

targetCustomizations.clusterGroupSelector

Selecionador de rótulos para grupos de clusters.

Todos

targetCustomizations.clusterName

Nome específico do cluster a ser direcionado.

Todos

targetCustomizations.doNotDeploy

Impedir a implantação em clusters correspondentes.

Todos

targetCustomizations.namespace

Substitui o namespace de nível raiz.

Todos

targetCustomizations.defaultNamespace

Substitui o namespace padrão de nível raiz.

Todos

targetCustomizations.helm

Substitui a configuração do Helm de nível raiz.

Todos

targetCustomizations.kustomize

Substitui a configuração do Kustomize de nível raiz.

Kustomize

targetCustomizations.yaml.overlays

Nomes de sobreposição para substituir ou patch recursos YAML.

YAML bruto

targetCustomizations.correctDrift

Habilita a correção de desvio para recursos gerenciados.

Todos

Personalizações suportadas

Substituir versões do gráfico Helm nas personalizações de destino pode aumentar o tamanho dos bundles. Como SUSE® Rancher Prime Continuous Delivery armazena bundles no etcd, isso pode exceder o limite de tamanho de blob do etcd. Consulte fleet#1650 para mais detalhes.