argocd ApplicationSet is able to use To activate this feature add to your ApplicationSet manifest is available in addition to the default Go Text Template functions The except for and Go Template Introduction

Answer:
# Go Template

## Introduction

ApplicationSet is able to use [Go Text Template](https://pkg.go.dev/text/template). To activate this feature, add
`goTemplate: true` to your ApplicationSet manifest.

The [Sprig function library](https://masterminds.github.io/sprig/) (except for `env`, `expandenv` and `getHostByName`)
is available in addition to the default Go Text Template functions.

An additional `normalize` function makes any string parameter usable as a valid DNS name by replacing invalid characters
with hyphens and truncating at 253 characters. This is useful when making parameters safe for things like Application
names.

Another `slugify` function has been added which, by default, sanitizes and smart truncates (it doesn't cut a word into 2). This function accepts a couple of arguments:

- The first argument (if provided) is an integer specifying the maximum length of the slug.
- The second argument (if provided) is a boolean indicating whether smart truncation is enabled.
- The last argument (if provided) is the input name that needs to be slugified.

#### Usage example

```
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: test-appset
spec:
  ...
  template:
    metadata:
      name: 'hellos3--'
      annotations:
        label-1: ''
        label-2: ''
        label-3: ''
```

If you want to customize [options defined by text/template](https://pkg.go.dev/text/template#Template.Option), you can
add the `goTemplateOptions: ["opt1", "opt2", ...]` key to your ApplicationSet next to `goTemplate: true`. Note that at
the time of writing, there is only one useful option defined, which is `missingkey=error`.

The recommended setting of `goTemplateOptions` is `["missingkey=error"]`, which ensures that if undefined values are
looked up by your template then an error is reported instead of being ignored silently. This is not currently the default
behavior, for backwards compatibility.

## Motivation

Go Template is the Go Standard for string templating. It is also more powerful than fasttemplate (the default templating
engine) as it allows doing complex templating logic.

## Limitations

Go templates are applied on a per-field basis, and only on string fields. Here are some examples of what is **not**
possible with Go text templates:

- Templating a boolean field.

        ::yaml
        apiVersion: argoproj.io/v1alpha1
        kind: ApplicationSet
        spec:
          goTemplate: true
          goTemplateOptions: ["missingkey=error"]
          template:
            spec:
              source:
                helm:
                  useCredentials: ""  # This field may NOT be templated, because it is a boolean field.

- Templating an object field:

        ::yaml
        apiVersion: argoproj.io/v1alpha1
        kind: ApplicationSet
        spec:
          goTemplate: true
          goTemplateOptions: ["missingkey=error"]
          template:
            spec:
              syncPolicy: ""  # This field may NOT be templated, because it is an object field.

- Using control keywords across fields:

        ::yaml
        apiVersion: argoproj.io/v1alpha1
        kind: ApplicationSet
        spec:
          goTemplate: true
          goTemplateOptions: ["missingkey=error"]
          template:
            spec:
              source:
                helm:
                  parameters:
                  # Each of these fields is evaluated as an independent template, so the first one will fail with an error.
                  - name: ""
                  - name: ""
                    value: ""
                  - name: throw-away
                    value: ""

- Signature verification is not supported for the templated `project` field when using the Git generator.

        ::yaml
        apiVersion: argoproj.io/v1alpha1
        kind: ApplicationSet
        spec:
          goTemplate: true
          template:
            spec:
              project:

## Migration guide

### Globals

All your templates must replace parameters with GoTemplate Syntax:

Example: `` becomes ``

### Cluster Generators

By activating Go Templating, `` becomes an object.

- `` becomes ``
- `` becomes ``

### Git Generators

By activating Go Templating, `` becomes an object. Therefore, some changes must be made to the Git
generators' templating:

- `` becomes ``
- `` becomes ``
- `` becomes ``
- `` becomes ``
- `` becomes ``
- `` becomes ``
- `` if being used in the file generator becomes ``

Here is an example:

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-addons
spec:
  generators:
  - git:
      repoURL: https://github.com/argoproj/argo-cd.git
      revision: HEAD
      directories:
      - path: applicationset/examples/git-generator-directory/cluster-addons/*
  template:
    metadata:
      name: ''
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: ''
      destination:
        server: https://kubernetes.default.svc
        namespace: ''
```

becomes

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-addons
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - git:
      repoURL: https://github.com/argoproj/argo-cd.git
      revision: HEAD
      directories:
      - path: applicationset/examples/git-generator-directory/cluster-addons/*
  template:
    metadata:
      name: ''
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: ''
      destination:
        server: https://kubernetes.default.svc
        namespace: ''
```

It is also possible to use Sprig functions to construct the path variables manually:

| with `goTemplate: false` | with `goTemplate: true` | with `goTemplate: true` + Sprig |
| ------------ | ----------- | --------------------- |
| `` | `` | `` |
| `` | `` | `` |
| `` | `` | `` |
| `` | `` | `` |
| `` | `` | `` |
| `` | `-` | `` |

## Available template functions

ApplicationSet controller provides:

- all [sprig](http://masterminds.github.io/sprig/) Go templates function except `env`, `expandenv` and `getHostByName`
- `normalize`: sanitizes the input so that it complies with the following rules:
    1. contains no more than 253 characters
    2. contains only lowercase alphanumeric characters, '-' or '.'
    3. starts and ends with an alphanumeric character

- `slugify`: sanitizes like `normalize` and smart truncates (it doesn't cut a word into 2) like described in the [introduction](#introduction) section.
- `toYaml` / `fromYaml` / `fromYamlArray` helm like functions

## Examples

### Basic Go template usage

This example shows basic string parameter substitution.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: guestbook
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - cluster: engineering-dev
        url: https://1.2.3.4
      - cluster: engineering-prod
        url: https://2.4.6.8
      - cluster: finance-preprod
        url: https://9.8.7.6
  template:
    metadata:
      name: '-guestbook'
    spec:
      project: my-project
      source:
        repoURL: https://github.com/infra-team/cluster-deployments.git
        targetRevision: HEAD
        path: guestbook/
      destination:
        server: ''
        namespace: guestbook
```

### Fallbacks for unset parameters

For some generators, a parameter of a certain name might not always be populated (for example, with the values generator
or the git files generator). In these cases, you can use a Go template to provide a fallback value.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: guestbook
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - cluster: engineering-dev
        url: https://kubernetes.default.svc
      - cluster: engineering-prod
        url: https://kubernetes.default.svc
        nameSuffix: -my-name-suffix
  template:
    metadata:
      name: ''
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: applicationset/examples/list-generator/guestbook/
      destination:
        server: ''
        namespace: guestbook
```

This ApplicationSet will produce an Application called `engineering-dev` and another called
`engineering-prod-my-name-suffix`.

Note that unset parameters are an error, so you need to avoid looking up a property that doesn't exist. Instead, use
template functions like `dig` to do the lookup with a default. If you prefer to have unset parameters default to zero,
you can remove `goTemplateOptions: ["missingkey=error"]` or set it to `goTemplateOptions: ["missingkey=invalid"]`

Go Template     Introduction  ApplicationSet is able to use  Go Text Template  https   pkg go dev text template   To activate this feature  add   goTemplate  true  to your ApplicationSet manifest   The  Sprig function library  https   masterminds github io sprig    except for  env    expandenv  and  getHostByName    is available in addition to the default Go Text Template functions   An additional  normalize  function makes any string parameter usable as a valid DNS name by replacing invalid characters  with hyphens and truncating at 253 characters  This is useful when making parameters safe for things like Application names   Another  slugify  function has been added which  by default  sanitizes and smart truncates  it doesn t cut a word into 2   This function accepts a couple of arguments     The first argument  if provided  is an integer specifying the maximum length of the slug    The second argument  if provided  is a boolean indicating whether smart truncation is enabled    The last argument  if provided  is the input name that needs to be slugified        Usage example      apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  test appset spec           template      metadata        name   hellos3          annotations          label 1             label 2             label 3          If you want to customize  options defined by text template  https   pkg go dev text template Template Option   you can add the  goTemplateOptions    opt1    opt2         key to your ApplicationSet next to  goTemplate  true   Note that at the time of writing  there is only one useful option defined  which is  missingkey error    The recommended setting of  goTemplateOptions  is    missingkey error     which ensures that if undefined values are looked up by your template then an error is reported instead of being ignored silently  This is not currently the default behavior  for backwards compatibility      Motivation  Go Template is the Go Standard for string templating  It is also more powerful than fasttemplate  the default templating  engine  as it allows doing complex templating logic      Limitations  Go templates are applied on a per field basis  and only on string fields  Here are some examples of what is   not    possible with Go text templates     Templating a boolean field             yaml         apiVersion  argoproj io v1alpha1         kind  ApplicationSet         spec            goTemplate  true           goTemplateOptions    missingkey error             template              spec                source                  helm                    useCredentials        This field may NOT be templated  because it is a boolean field     Templating an object field             yaml         apiVersion  argoproj io v1alpha1         kind  ApplicationSet         spec            goTemplate  true           goTemplateOptions    missingkey error             template              spec                syncPolicy        This field may NOT be templated  because it is an object field     Using control keywords across fields             yaml         apiVersion  argoproj io v1alpha1         kind  ApplicationSet         spec            goTemplate  true           goTemplateOptions    missingkey error             template              spec                source                  helm                    parameters                      Each of these fields is evaluated as an independent template  so the first one will fail with an error                      name                         name                         value                         name  throw away                     value        Signature verification is not supported for the templated  project  field when using the Git generator             yaml         apiVersion  argoproj io v1alpha1         kind  ApplicationSet         spec            goTemplate  true           template              spec                project        Migration guide      Globals  All your templates must replace parameters with GoTemplate Syntax   Example     becomes         Cluster Generators  By activating Go Templating     becomes an object        becomes         becomes         Git Generators  By activating Go Templating     becomes an object  Therefore  some changes must be made to the Git  generators  templating        becomes         becomes         becomes         becomes         becomes         becomes         if being used in the file generator becomes     Here is an example      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster addons spec    generators      git        repoURL  https   github com argoproj argo cd git       revision  HEAD       directories          path  applicationset examples git generator directory cluster addons     template      metadata        name         spec        project  default       source          repoURL  https   github com argoproj argo cd git         targetRevision  HEAD         path           destination          server  https   kubernetes default svc         namespace          becomes     yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster addons spec    goTemplate  true   goTemplateOptions    missingkey error     generators      git        repoURL  https   github com argoproj argo cd git       revision  HEAD       directories          path  applicationset examples git generator directory cluster addons     template      metadata        name         spec        project  default       source          repoURL  https   github com argoproj argo cd git         targetRevision  HEAD         path           destination          server  https   kubernetes default svc         namespace          It is also possible to use Sprig functions to construct the path variables manually     with  goTemplate  false    with  goTemplate  true    with  goTemplate  true    Sprig                                                                                Available template functions  ApplicationSet controller provides     all  sprig  http   masterminds github io sprig   Go templates function except  env    expandenv  and  getHostByName     normalize   sanitizes the input so that it complies with the following rules      1  contains no more than 253 characters     2  contains only lowercase alphanumeric characters      or         3  starts and ends with an alphanumeric character     slugify   sanitizes like  normalize  and smart truncates  it doesn t cut a word into 2  like described in the  introduction   introduction  section     toYaml     fromYaml     fromYamlArray  helm like functions      Examples      Basic Go template usage  This example shows basic string parameter substitution      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  guestbook spec    goTemplate  true   goTemplateOptions    missingkey error     generators      list        elements          cluster  engineering dev         url  https   1 2 3 4         cluster  engineering prod         url  https   2 4 6 8         cluster  finance preprod         url  https   9 8 7 6   template      metadata        name    guestbook      spec        project  my project       source          repoURL  https   github com infra team cluster deployments git         targetRevision  HEAD         path  guestbook        destination          server             namespace  guestbook          Fallbacks for unset parameters  For some generators  a parameter of a certain name might not always be populated  for example  with the values generator or the git files generator   In these cases  you can use a Go template to provide a fallback value      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  guestbook spec    goTemplate  true   goTemplateOptions    missingkey error     generators      list        elements          cluster  engineering dev         url  https   kubernetes default svc         cluster  engineering prod         url  https   kubernetes default svc         nameSuffix   my name suffix   template      metadata        name         spec        project  default       source          repoURL  https   github com argoproj argo cd git         targetRevision  HEAD         path  applicationset examples list generator guestbook        destination          server             namespace  guestbook      This ApplicationSet will produce an Application called  engineering dev  and another called   engineering prod my name suffix    Note that unset parameters are an error  so you need to avoid looking up a property that doesn t exist  Instead  use template functions like  dig  to do the lookup with a default  If you prefer to have unset parameters default to zero  you can remove  goTemplateOptions    missingkey error    or set it to  goTemplateOptions    missingkey invalid


argocd Using a Merge generator is appropriate when a subset of parameter sets require overriding Merge Generator As an example imagine that we have two clusters The Merge generator combines parameters produced by the base first generator with matching parameter sets produced by subsequent generators A matching parameter set has the same values for the configured merge keys Non matching parameter sets are discarded Override precedence is bottom to top the values from a matching parameter set produced by generator 3 will take precedence over the values from the corresponding parameter set produced by generator 2 Example Base Cluster generator override Cluster generator List generator

Answer:
# Merge Generator

The Merge generator combines parameters produced by the base (first) generator with matching parameter sets produced by subsequent generators. A _matching_ parameter set has the same values for the configured _merge keys_. _Non-matching_ parameter sets are discarded. Override precedence is bottom-to-top: the values from a matching parameter set produced by generator 3 will take precedence over the values from the corresponding parameter set produced by generator 2.

Using a Merge generator is appropriate when a subset of parameter sets require overriding.

## Example: Base Cluster generator + override Cluster generator + List generator

As an example, imagine that we have two clusters:

- A `staging` cluster (at `https://1.2.3.4`)
- A `production` cluster (at `https://2.4.6.8`)

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-git
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    # merge 'parent' generator
    - merge:
        mergeKeys:
          - server
        generators:
          - clusters:
              values:
                kafka: 'true'
                redis: 'false'
          # For clusters with a specific label, enable Kafka.
          - clusters:
              selector:
                matchLabels:
                  use-kafka: 'false'
              values:
                kafka: 'false'
          # For a specific cluster, enable Redis.
          - list:
              elements:
                - server: https://2.4.6.8
                  values.redis: 'true'
  template:
    metadata:
      name: ''
    spec:
      project: ''
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: app
        helm:
          parameters:
            - name: kafka
              value: ''
            - name: redis
              value: ''
      destination:
        server: ''
        namespace: default
```

The base Cluster generator scans the [set of clusters defined in Argo CD](Generators-Cluster.md), finds the staging and production cluster secrets, and produces two corresponding sets of parameters:
```yaml
- name: staging
  server: https://1.2.3.4
  values.kafka: 'true'
  values.redis: 'false'

- name: production
  server: https://2.4.6.8
  values.kafka: 'true'
  values.redis: 'false'
```

The override Cluster generator scans the [set of clusters defined in Argo CD](Generators-Cluster.md), finds the staging cluster secret (which has the required label), and produces the following parameters:
```yaml
- name: staging
  server: https://1.2.3.4
  values.kafka: 'false'
```

When merged with the base generator's parameters, the `values.kafka` value for the staging cluster is set to `'false'`.
```yaml
- name: staging
  server: https://1.2.3.4
  values.kafka: 'false'
  values.redis: 'false'

- name: production
  server: https://2.4.6.8
  values.kafka: 'true'
  values.redis: 'false'
```

Finally, the List cluster generates a single set of parameters:
```yaml
- server: https://2.4.6.8
  values.redis: 'true'
```

When merged with the updated base parameters, the `values.redis` value for the production cluster is set to `'true'`. This is the merge generator's final output:
```yaml
- name: staging
  server: https://1.2.3.4
  values.kafka: 'false'
  values.redis: 'false'

- name: production
  server: https://2.4.6.8
  values.kafka: 'true'
  values.redis: 'true'
```

## Example: Use value interpolation in merge

Some generators support additional values and interpolating from generated variables to selected values. This can be used to teach the merge generator which generated variables to use to combine different generators.

The following example combines discovered clusters and a git repository by cluster labels and the branch name:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-git
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    # merge 'parent' generator:
    # Use the selector set by both child generators to combine them.
    - merge:
        mergeKeys:
          # Note that this would not work with goTemplate enabled,
          # nested merge keys are not supported there.
          - values.selector
        generators:
          # Assuming, all configured clusters have a label for their location:
          # Set the selector to this location.
          - clusters:
              values:
                selector: ''
          # The git repo may have different directories which correspond to the
          # cluster locations, using these as a selector.
          - git:
              repoURL: https://github.com/argoproj/argocd-example-apps/
              revision: HEAD
              directories:
              - path: '*'
              values:
                selector: ''
  template:
    metadata:
      name: ''
    spec:
      project: ''
      source:
        repoURL: https://github.com/argoproj/argocd-example-apps/
        # The cluster values field for each generator will be substituted here:
        targetRevision: HEAD
        path: ''
      destination:
        server: ''
        namespace: default
```

Assuming a cluster named `germany01` with the label `metadata.labels.location=Germany` and a git repository containing a directory called `Germany`, this could combine to values as follows:

```yaml
  # From the cluster generator
- name: germany01
  server: https://1.2.3.4
  # From the git generator
  path: Germany
  # Combining selector with the merge generator
  values.selector: 'Germany'
  # More values from cluster & git generator
  # […]
```

## Restrictions

1. You should specify only a single generator per array entry. This is not valid:

        - merge:
            generators:
            - list: # (...)
              git: # (...)

    - While this *will* be accepted by Kubernetes API validation, the controller will report an error on generation. Each generator should be specified in a separate array element, as in the examples above.

1. The Merge generator does not support [`template` overrides](Template.md#generator-templates) specified on child generators. This `template` will not be processed:

        - merge:
            generators:
              - list:
                  elements:
                    - # (...)
                  template: { } # Not processed

1. Combination-type generators (Matrix or Merge) can only be nested once. For example, this will not work:

        - merge:
            generators:
              - merge:
                  generators:
                    - merge:  # This third level is invalid.
                        generators:
                          - list:
                              elements:
                                - # (...)

1. Merging on nested values while using `goTemplate: true` is currently not supported, this will not work

        spec:
          goTemplate: true
          generators:
          - merge:
              mergeKeys:
                - values.merge

1. When using a Merge generator nested inside another Matrix or Merge generator, [Post Selectors](Generators-Post-Selector.md) for this nested generator's generators will only be applied when enabled via `spec.applyNestedSelectors`.

        - merge:
            generators:
              - merge:
                  generators:
                    - list
                        elements:
                          - # (...)
                      selector: { } # Only applied when applyNestedSelectors is true

Merge Generator  The Merge generator combines parameters produced by the base  first  generator with matching parameter sets produced by subsequent generators  A  matching  parameter set has the same values for the configured  merge keys    Non matching  parameter sets are discarded  Override precedence is bottom to top  the values from a matching parameter set produced by generator 3 will take precedence over the values from the corresponding parameter set produced by generator 2   Using a Merge generator is appropriate when a subset of parameter sets require overriding      Example  Base Cluster generator   override Cluster generator   List generator   As an example  imagine that we have two clusters     A  staging  cluster  at  https   1 2 3 4     A  production  cluster  at  https   2 4 6 8       yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster git spec    goTemplate  true   goTemplateOptions    missingkey error     generators        merge  parent  generator       merge          mergeKeys              server         generators              clusters                values                  kafka   true                  redis   false              For clusters with a specific label  enable Kafka              clusters                selector                  matchLabels                    use kafka   false                values                  kafka   false              For a specific cluster  enable Redis              list                elements                     server  https   2 4 6 8                   values redis   true    template      metadata        name         spec        project           source          repoURL  https   github com argoproj argo cd git         targetRevision  HEAD         path  app         helm            parameters                name  kafka               value                   name  redis               value           destination          server             namespace  default      The base Cluster generator scans the  set of clusters defined in Argo CD  Generators Cluster md   finds the staging and production cluster secrets  and produces two corresponding sets of parameters     yaml   name  staging   server  https   1 2 3 4   values kafka   true    values redis   false       name  production   server  https   2 4 6 8   values kafka   true    values redis   false       The override Cluster generator scans the  set of clusters defined in Argo CD  Generators Cluster md   finds the staging cluster secret  which has the required label   and produces the following parameters     yaml   name  staging   server  https   1 2 3 4   values kafka   false       When merged with the base generator s parameters  the  values kafka  value for the staging cluster is set to   false       yaml   name  staging   server  https   1 2 3 4   values kafka   false    values redis   false     name  production   server  https   2 4 6 8   values kafka   true    values redis   false       Finally  the List cluster generates a single set of parameters     yaml   server  https   2 4 6 8   values redis   true       When merged with the updated base parameters  the  values redis  value for the production cluster is set to   true    This is the merge generator s final output     yaml   name  staging   server  https   1 2 3 4   values kafka   false    values redis   false     name  production   server  https   2 4 6 8   values kafka   true    values redis   true          Example  Use value interpolation in merge  Some generators support additional values and interpolating from generated variables to selected values  This can be used to teach the merge generator which generated variables to use to combine different generators   The following example combines discovered clusters and a git repository by cluster labels and the branch name     yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster git spec    goTemplate  true   goTemplateOptions    missingkey error     generators        merge  parent  generator        Use the selector set by both child generators to combine them        merge          mergeKeys              Note that this would not work with goTemplate enabled              nested merge keys are not supported there              values selector         generators              Assuming  all configured clusters have a label for their location              Set the selector to this location              clusters                values                  selector                 The git repo may have different directories which correspond to the             cluster locations  using these as a selector              git                repoURL  https   github com argoproj argocd example apps                revision  HEAD               directories                  path                    values                  selector       template      metadata        name         spec        project           source          repoURL  https   github com argoproj argocd example apps            The cluster values field for each generator will be substituted here          targetRevision  HEAD         path           destination          server             namespace  default      Assuming a cluster named  germany01  with the label  metadata labels location Germany  and a git repository containing a directory called  Germany   this could combine to values as follows      yaml     From the cluster generator   name  germany01   server  https   1 2 3 4     From the git generator   path  Germany     Combining selector with the merge generator   values selector   Germany      More values from cluster   git generator                  Restrictions  1  You should specify only a single generator per array entry  This is not valid             merge              generators                list                        git                 While this  will  be accepted by Kubernetes API validation  the controller will report an error on generation  Each generator should be specified in a separate array element  as in the examples above   1  The Merge generator does not support   template  overrides  Template md generator templates  specified on child generators  This  template  will not be processed             merge              generators                  list                    elements                                                  template        Not processed  1  Combination type generators  Matrix or Merge  can only be nested once  For example  this will not work             merge              generators                  merge                    generators                        merge     This third level is invalid                          generators                              list                                elements                                             1  Merging on nested values while using  goTemplate  true  is currently not supported  this will not work          spec            goTemplate  true           generators              merge                mergeKeys                    values merge  1  When using a Merge generator nested inside another Matrix or Merge generator   Post Selectors  Generators Post Selector md  for this nested generator s generators will only be applied when enabled via  spec applyNestedSelectors              merge              generators                  merge                    generators                        list                         elements                                                            selector        Only applied when applyNestedSelectors is true


argocd And so on Git File Generator List Generator Providing a list of applications to deploy via configuration files with optional configuration options and deploying them to a fixed list of clusters Git Directory Generator Cluster Decision Resource Generator Locate application resources contained within folders of a Git repository and deploy them to a list of clusters provided via an external custom resource SCM Provider Generator Cluster Generator Scanning the repositories of a GitHub organization for application resources and targeting those resources to all available clusters The Matrix generator combines the parameters generated by two child generators iterating through every combination of each generator s generated parameters Matrix Generator By combining both generators parameters to produce every possible combination this allows you to gain the intrinsic properties of both generators For example a small subset of the many possible use cases include

Answer:
# Matrix Generator

The Matrix generator combines the parameters generated by two child generators, iterating through every combination of each generator's generated parameters.

By combining both generators parameters, to produce every possible combination, this allows you to gain the intrinsic properties of both generators. For example, a small subset of the many possible use cases include:

- *SCM Provider Generator + Cluster Generator*: Scanning the repositories of a GitHub organization for application resources, and targeting those resources to all available clusters.
- *Git File Generator + List Generator*: Providing a list of applications to deploy via configuration files, with optional configuration options, and deploying them to a fixed list of clusters.
- *Git Directory Generator + Cluster Decision Resource Generator*: Locate application resources contained within folders of a Git repository, and deploy them to a list of clusters provided via an external custom resource.
- And so on...

Any set of generators may be used, with the combined values of those generators inserted into the `template` parameters, as usual.

**Note**: If both child generators are Git generators, one or both of them must use the `pathParamPrefix` option to avoid conflicts when merging the child generators’ items.

## Example: Git Directory generator + Cluster generator

As an example, imagine that we have two clusters:

- A `staging` cluster (at `https://1.2.3.4`)
- A `production` cluster (at `https://2.4.6.8`)

And our application YAMLs are defined in a Git repository:

- [Argo Workflows controller](https://github.com/argoproj/argo-cd/tree/master/applicationset/examples/git-generator-directory/cluster-addons/argo-workflows)
- [Prometheus operator](https://github.com/argoproj/argo-cd/tree/master/applicationset/examples/git-generator-directory/cluster-addons/prometheus-operator)

Our goal is to deploy both applications onto both clusters, and, more generally, in the future to automatically deploy new applications in the Git repository, and to new clusters defined within Argo CD, as well.

For this we will use the Matrix generator, with the Git and the Cluster as child generators:

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-git
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    # matrix 'parent' generator
    - matrix:
        generators:
          # git generator, 'child' #1
          - git:
              repoURL: https://github.com/argoproj/argo-cd.git
              revision: HEAD
              directories:
                - path: applicationset/examples/matrix/cluster-addons/*
          # cluster generator, 'child' #2
          - clusters:
              selector:
                matchLabels:
                  argocd.argoproj.io/secret-type: cluster
  template:
    metadata:
      name: '-'
    spec:
      project: ''
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: ''
      destination:
        server: ''
        namespace: ''
```

First, the Git directory generator will scan the Git repository, discovering directories under the specified path. It discovers the argo-workflows and prometheus-operator applications, and produces two corresponding sets of parameters:
```yaml
- path: /examples/git-generator-directory/cluster-addons/argo-workflows
  path.basename: argo-workflows

- path: /examples/git-generator-directory/cluster-addons/prometheus-operator
  path.basename: prometheus-operator
```

Next, the Cluster generator scans the [set of clusters defined in Argo CD](Generators-Cluster.md), finds the staging and production cluster secrets, and produce two corresponding sets of parameters:
```yaml
- name: staging
  server: https://1.2.3.4

- name: production
  server: https://2.4.6.8
```

Finally, the Matrix generator will combine both sets of outputs, and produce:
```yaml
- name: staging
  server: https://1.2.3.4
  path: /examples/git-generator-directory/cluster-addons/argo-workflows
  path.basename: argo-workflows

- name: staging
  server: https://1.2.3.4
  path: /examples/git-generator-directory/cluster-addons/prometheus-operator
  path.basename: prometheus-operator

- name: production
  server: https://2.4.6.8
  path: /examples/git-generator-directory/cluster-addons/argo-workflows
  path.basename: argo-workflows

- name: production
  server: https://2.4.6.8
  path: /examples/git-generator-directory/cluster-addons/prometheus-operator
  path.basename: prometheus-operator
```
(*The full example can be found [here](https://github.com/argoproj/argo-cd/tree/master/applicationset/examples/matrix).*)

## Using Parameters from one child generator in another child generator

The Matrix generator allows using the parameters generated by one child generator inside another child generator.
Below is an example that uses a git-files generator in conjunction with a cluster generator.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-git
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    # matrix 'parent' generator
    - matrix:
        generators:
          # git generator, 'child' #1
          - git:
              repoURL: https://github.com/argoproj/applicationset.git
              revision: HEAD
              files:
                - path: "examples/git-generator-files-discovery/cluster-config/**/config.json"
          # cluster generator, 'child' #2
          - clusters:
              selector:
                matchLabels:
                  argocd.argoproj.io/secret-type: cluster
                  kubernetes.io/environment: ''
  template:
    metadata:
      name: '-guestbook'
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/applicationset.git
        targetRevision: HEAD
        path: "examples/git-generator-files-discovery/apps/guestbook"
      destination:
        server: ''
        namespace: guestbook
```
Here is the corresponding folder structure for the git repository used by the git-files generator:

```
├── apps
│   └── guestbook
│       ├── guestbook-ui-deployment.yaml
│       ├── guestbook-ui-svc.yaml
│       └── kustomization.yaml
├── cluster-config
│   └── engineering
│       ├── dev
│       │   └── config.json
│       └── prod
│           └── config.json
└── git-generator-files.yaml
```
In the above example, the `` parameters produced by the git-files generator will resolve to `dev` and `prod`.
In the 2nd child generator, the label selector with label `kubernetes.io/environment: ` will resolve with the values produced by the first child generator's parameters (`kubernetes.io/environment: prod` and `kubernetes.io/environment: dev`).

So in the above example, clusters with the label `kubernetes.io/environment: prod` will have only prod-specific configuration (ie. `prod/config.json`) applied to it, wheres clusters
with the label `kubernetes.io/environment: dev` will have only dev-specific configuration (ie. `dev/config.json`)

## Overriding parameters from one child generator in another child generator

The Matrix Generator allows parameters with the same name to be defined in multiple child generators. This is useful, for example, to define default values for all stages in one generator and override them with stage-specific values in another generator. The example below generates a Helm-based application using a matrix generator with two git generators: the first provides stage-specific values (one directory per stage) and the second provides global values for all stages.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: parameter-override-example
spec:
  generators:
    - matrix:
        generators:
          - git:
              repoURL: https://github.com/example/values.git
              revision: HEAD
              files:
                - path: "**/stage.values.yaml"
          - git:
               repoURL: https://github.com/example/values.git
               revision: HEAD
               files:
                  - path: "global.values.yaml"
  goTemplate: true
  template:
    metadata:
      name: example
    spec:
      project: default
      source:
        repoURL: https://github.com/example/example-app.git
        targetRevision: HEAD
        path: .
        helm:
          values: |
            ` }}
      destination:
        server: in-cluster
        namespace: default
```

Given the following structure/content of the example/values repository:

```
├── test
│   └── stage.values.yaml
│         stageName: test
│         cpuRequest: 100m
│         debugEnabled: true
├── staging
│   └── stage.values.yaml
│         stageName: staging
├── production
│   └── stage.values.yaml
│         stageName: production
│         memoryLimit: 512Mi
│         debugEnabled: false
└── global.values.yaml
      cpuRequest: 200m
      memoryLimit: 256Mi
      debugEnabled: true
```

The matrix generator above would yield the following results:

```yaml
- stageName: test
  cpuRequest: 100m
  memoryLimit: 256Mi
  debugEnabled: true

- stageName: staging
  cpuRequest: 200m
  memoryLimit: 256Mi
  debugEnabled: true

- stageName: production
  cpuRequest: 200m
  memoryLimit: 512Mi
  debugEnabled: false
```

## Example: Two Git Generators Using `pathParamPrefix`

The matrix generator will fail if its children produce results containing identical keys with differing values.
This poses a problem for matrix generators where both children are Git generators since they auto-populate `path`-related parameters in their outputs.
To avoid this problem, specify a `pathParamPrefix` on one or both of the child generators to avoid conflicting parameter keys in the output.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: two-gits-with-path-param-prefix
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - matrix:
        generators:
          # git file generator referencing files containing details about each
          # app to be deployed (e.g., `appName`).
          - git:
              repoURL: https://github.com/some-org/some-repo.git
              revision: HEAD
              files:
                - path: "apps/*.json"
              pathParamPrefix: app
          # git file generator referencing files containing details about
          # locations to which each app should deploy (e.g., `region` and
          # `clusterName`).
          - git:
              repoURL: https://github.com/some-org/some-repo.git
              revision: HEAD
              files:
                - path: "targets//*.json"
              pathParamPrefix: target
  template: {} # ...
```

Then, given the following file structure/content:

```
├── apps
│   ├── app-one.json
│   │   { "appName": "app-one" }
│   └── app-two.json
│       { "appName": "app-two" }
└── targets
    ├── app-one
    │   ├── east-cluster-one.json
    │   │   { "region": "east", "clusterName": "cluster-one" }
    │   └── east-cluster-two.json
    │       { "region": "east", "clusterName": "cluster-two" }
    └── app-two
        ├── east-cluster-one.json
        │   { "region": "east", "clusterName": "cluster-one" }
        └── west-cluster-three.json
            { "region": "west", "clusterName": "cluster-three" }
```

…the matrix generator above would yield the following results:

```yaml
- appName: app-one
  app.path: /apps
  app.path.filename: app-one.json
  # plus additional path-related parameters from the first child generator, all
  # prefixed with "app".
  region: east
  clusterName: cluster-one
  target.path: /targets/app-one
  target.path.filename: east-cluster-one.json
  # plus additional path-related parameters from the second child generator, all
  # prefixed with "target".

- appName: app-one
  app.path: /apps
  app.path.filename: app-one.json
  region: east
  clusterName: cluster-two
  target.path: /targets/app-one
  target.path.filename: east-cluster-two.json

- appName: app-two
  app.path: /apps
  app.path.filename: app-two.json
  region: east
  clusterName: cluster-one
  target.path: /targets/app-two
  target.path.filename: east-cluster-one.json

- appName: app-two
  app.path: /apps
  app.path.filename: app-two.json
  region: west
  clusterName: cluster-three
  target.path: /targets/app-two
  target.path.filename: west-cluster-three.json
```

## Restrictions

1. The Matrix generator currently only supports combining the outputs of only two child generators (eg does not support generating combinations for 3 or more).

1. You should specify only a single generator per array entry, eg this is not valid:

        - matrix:
            generators:
            - list: # (...)
              git: # (...)

    - While this *will* be accepted by Kubernetes API validation, the controller will report an error on generation. Each generator should be specified in a separate array element, as in the examples above.

1. The Matrix generator does not currently support [`template` overrides](Template.md#generator-templates) specified on child generators, eg this `template` will not be processed:

        - matrix:
            generators:
              - list:
                  elements:
                    - # (...)
                  template: { } # Not processed

1. Combination-type generators (matrix or merge) can only be nested once. For example, this will not work:

        - matrix:
            generators:
              - matrix:
                  generators:
                    - matrix:  # This third level is invalid.
                        generators:
                          - list:
                              elements:
                                - # (...)

1. When using parameters from one child generator inside another child generator, the child generator that *consumes* the parameters **must come after** the child generator that *produces* the parameters.
For example, the below example would be invalid (cluster-generator must come after the git-files generator):

        - matrix:
            generators:
              # cluster generator, 'child' #1
              - clusters:
                  selector:
                    matchLabels:
                      argocd.argoproj.io/secret-type: cluster
                      kubernetes.io/environment: '' #  is produced by git-files generator
              # git generator, 'child' #2
              - git:
                  repoURL: https://github.com/argoproj/applicationset.git
                  revision: HEAD
                  files:
                    - path: "examples/git-generator-files-discovery/cluster-config/**/config.json"

1. You cannot have both child generators consuming parameters from each another. In the example below, the cluster generator is consuming the `` parameter produced by the git-files generator, whereas the git-files generator is consuming the `` parameter produced by the cluster generator. This will result in a circular dependency, which is invalid.

        - matrix:
            generators:
              # cluster generator, 'child' #1
              - clusters:
                  selector:
                    matchLabels:
                      argocd.argoproj.io/secret-type: cluster
                      kubernetes.io/environment: '' #  is produced by git-files generator
              # git generator, 'child' #2
              - git:
                  repoURL: https://github.com/argoproj/applicationset.git
                  revision: HEAD
                  files:
                    - path: "examples/git-generator-files-discovery/cluster-config/engineering/**/config.json" #  is produced by cluster generator

1. When using a Matrix generator nested inside another Matrix or Merge generator, [Post Selectors](Generators-Post-Selector.md) for this nested generator's generators will only be applied when enabled via `spec.applyNestedSelectors`. You may also need to enable this even if your Post Selectors are not within the nested matrix or Merge generator, but are instead a sibling of a nested Matrix or Merge generator.

        - matrix:
            generators:
              - matrix:
                  generators:
                    - list
                        elements:
                          - # (...)
                      selector: { } # Only applied when applyNestedSelectors is true

Matrix Generator  The Matrix generator combines the parameters generated by two child generators  iterating through every combination of each generator s generated parameters   By combining both generators parameters  to produce every possible combination  this allows you to gain the intrinsic properties of both generators  For example  a small subset of the many possible use cases include      SCM Provider Generator   Cluster Generator   Scanning the repositories of a GitHub organization for application resources  and targeting those resources to all available clusters     Git File Generator   List Generator   Providing a list of applications to deploy via configuration files  with optional configuration options  and deploying them to a fixed list of clusters     Git Directory Generator   Cluster Decision Resource Generator   Locate application resources contained within folders of a Git repository  and deploy them to a list of clusters provided via an external custom resource    And so on     Any set of generators may be used  with the combined values of those generators inserted into the  template  parameters  as usual     Note    If both child generators are Git generators  one or both of them must use the  pathParamPrefix  option to avoid conflicts when merging the child generators  items      Example  Git Directory generator   Cluster generator  As an example  imagine that we have two clusters     A  staging  cluster  at  https   1 2 3 4     A  production  cluster  at  https   2 4 6 8    And our application YAMLs are defined in a Git repository      Argo Workflows controller  https   github com argoproj argo cd tree master applicationset examples git generator directory cluster addons argo workflows     Prometheus operator  https   github com argoproj argo cd tree master applicationset examples git generator directory cluster addons prometheus operator   Our goal is to deploy both applications onto both clusters  and  more generally  in the future to automatically deploy new applications in the Git repository  and to new clusters defined within Argo CD  as well   For this we will use the Matrix generator  with the Git and the Cluster as child generators      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster git spec    goTemplate  true   goTemplateOptions    missingkey error     generators        matrix  parent  generator       matrix          generators              git generator   child   1             git                repoURL  https   github com argoproj argo cd git               revision  HEAD               directories                    path  applicationset examples matrix cluster addons               cluster generator   child   2             clusters                selector                  matchLabels                    argocd argoproj io secret type  cluster   template      metadata        name          spec        project           source          repoURL  https   github com argoproj argo cd git         targetRevision  HEAD         path           destination          server             namespace          First  the Git directory generator will scan the Git repository  discovering directories under the specified path  It discovers the argo workflows and prometheus operator applications  and produces two corresponding sets of parameters     yaml   path   examples git generator directory cluster addons argo workflows   path basename  argo workflows    path   examples git generator directory cluster addons prometheus operator   path basename  prometheus operator      Next  the Cluster generator scans the  set of clusters defined in Argo CD  Generators Cluster md   finds the staging and production cluster secrets  and produce two corresponding sets of parameters     yaml   name  staging   server  https   1 2 3 4    name  production   server  https   2 4 6 8      Finally  the Matrix generator will combine both sets of outputs  and produce     yaml   name  staging   server  https   1 2 3 4   path   examples git generator directory cluster addons argo workflows   path basename  argo workflows    name  staging   server  https   1 2 3 4   path   examples git generator directory cluster addons prometheus operator   path basename  prometheus operator    name  production   server  https   2 4 6 8   path   examples git generator directory cluster addons argo workflows   path basename  argo workflows    name  production   server  https   2 4 6 8   path   examples git generator directory cluster addons prometheus operator   path basename  prometheus operator       The full example can be found  here  https   github com argoproj argo cd tree master applicationset examples matrix         Using Parameters from one child generator in another child generator  The Matrix generator allows using the parameters generated by one child generator inside another child generator   Below is an example that uses a git files generator in conjunction with a cluster generator      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  cluster git spec    goTemplate  true   goTemplateOptions    missingkey error     generators        matrix  parent  generator       matrix          generators              git generator   child   1             git                repoURL  https   github com argoproj applicationset git               revision  HEAD               files                    path   examples git generator files discovery cluster config    config json              cluster generator   child   2             clusters                selector                  matchLabels                    argocd argoproj io secret type  cluster                   kubernetes io environment       template      metadata        name    guestbook      spec        project  default       source          repoURL  https   github com argoproj applicationset git         targetRevision  HEAD         path   examples git generator files discovery apps guestbook        destination          server             namespace  guestbook     Here is the corresponding folder structure for the git repository used by the git files generator           apps         guestbook             guestbook ui deployment yaml             guestbook ui svc yaml             kustomization yaml     cluster config         engineering             dev                 config json             prod                 config json     git generator files yaml     In the above example  the    parameters produced by the git files generator will resolve to  dev  and  prod   In the 2nd child generator  the label selector with label  kubernetes io environment    will resolve with the values produced by the first child generator s parameters   kubernetes io environment  prod  and  kubernetes io environment  dev      So in the above example  clusters with the label  kubernetes io environment  prod  will have only prod specific configuration  ie   prod config json   applied to it  wheres clusters with the label  kubernetes io environment  dev  will have only dev specific configuration  ie   dev config json       Overriding parameters from one child generator in another child generator  The Matrix Generator allows parameters with the same name to be defined in multiple child generators  This is useful  for example  to define default values for all stages in one generator and override them with stage specific values in another generator  The example below generates a Helm based application using a matrix generator with two git generators  the first provides stage specific values  one directory per stage  and the second provides global values for all stages      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  parameter override example spec    generators        matrix          generators              git                repoURL  https   github com example values git               revision  HEAD               files                    path      stage values yaml              git                 repoURL  https   github com example values git                revision  HEAD                files                      path   global values yaml    goTemplate  true   template      metadata        name  example     spec        project  default       source          repoURL  https   github com example example app git         targetRevision  HEAD         path            helm            values                           destination          server  in cluster         namespace  default      Given the following structure content of the example values repository           test         stage values yaml           stageName  test           cpuRequest  100m           debugEnabled  true     staging         stage values yaml           stageName  staging     production         stage values yaml           stageName  production           memoryLimit  512Mi           debugEnabled  false     global values yaml       cpuRequest  200m       memoryLimit  256Mi       debugEnabled  true      The matrix generator above would yield the following results      yaml   stageName  test   cpuRequest  100m   memoryLimit  256Mi   debugEnabled  true      stageName  staging   cpuRequest  200m   memoryLimit  256Mi   debugEnabled  true    stageName  production   cpuRequest  200m   memoryLimit  512Mi   debugEnabled  false         Example  Two Git Generators Using  pathParamPrefix   The matrix generator will fail if its children produce results containing identical keys with differing values  This poses a problem for matrix generators where both children are Git generators since they auto populate  path  related parameters in their outputs  To avoid this problem  specify a  pathParamPrefix  on one or both of the child generators to avoid conflicting parameter keys in the output      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  two gits with path param prefix spec    goTemplate  true   goTemplateOptions    missingkey error     generators        matrix          generators              git file generator referencing files containing details about each             app to be deployed  e g    appName                git                repoURL  https   github com some org some repo git               revision  HEAD               files                    path   apps   json                pathParamPrefix  app             git file generator referencing files containing details about             locations to which each app should deploy  e g    region  and              clusterName                git                repoURL  https   github com some org some repo git               revision  HEAD               files                    path   targets    json                pathParamPrefix  target   template                Then  given the following file structure content           apps         app one json            appName    app one            app two json            appName    app two        targets         app one             east cluster one json                region    east    clusterName    cluster one                east cluster two json                region    east    clusterName    cluster two            app two             east cluster one json                region    east    clusterName    cluster one                west cluster three json                region    west    clusterName    cluster three          the matrix generator above would yield the following results      yaml   appName  app one   app path   apps   app path filename  app one json     plus additional path related parameters from the first child generator  all     prefixed with  app     region  east   clusterName  cluster one   target path   targets app one   target path filename  east cluster one json     plus additional path related parameters from the second child generator  all     prefixed with  target      appName  app one   app path   apps   app path filename  app one json   region  east   clusterName  cluster two   target path   targets app one   target path filename  east cluster two json    appName  app two   app path   apps   app path filename  app two json   region  east   clusterName  cluster one   target path   targets app two   target path filename  east cluster one json    appName  app two   app path   apps   app path filename  app two json   region  west   clusterName  cluster three   target path   targets app two   target path filename  west cluster three json         Restrictions  1  The Matrix generator currently only supports combining the outputs of only two child generators  eg does not support generating combinations for 3 or more    1  You should specify only a single generator per array entry  eg this is not valid             matrix              generators                list                        git                 While this  will  be accepted by Kubernetes API validation  the controller will report an error on generation  Each generator should be specified in a separate array element  as in the examples above   1  The Matrix generator does not currently support   template  overrides  Template md generator templates  specified on child generators  eg this  template  will not be processed             matrix              generators                  list                    elements                                                  template        Not processed  1  Combination type generators  matrix or merge  can only be nested once  For example  this will not work             matrix              generators                  matrix                    generators                        matrix     This third level is invalid                          generators                              list                                elements                                             1  When using parameters from one child generator inside another child generator  the child generator that  consumes  the parameters   must come after   the child generator that  produces  the parameters  For example  the below example would be invalid  cluster generator must come after the git files generator              matrix              generators                  cluster generator   child   1                 clusters                    selector                      matchLabels                        argocd argoproj io secret type  cluster                       kubernetes io environment        is produced by git files generator                 git generator   child   2                 git                    repoURL  https   github com argoproj applicationset git                   revision  HEAD                   files                        path   examples git generator files discovery cluster config    config json   1  You cannot have both child generators consuming parameters from each another  In the example below  the cluster generator is consuming the    parameter produced by the git files generator  whereas the git files generator is consuming the    parameter produced by the cluster generator  This will result in a circular dependency  which is invalid             matrix              generators                  cluster generator   child   1                 clusters                    selector                      matchLabels                        argocd argoproj io secret type  cluster                       kubernetes io environment        is produced by git files generator                 git generator   child   2                 git                    repoURL  https   github com argoproj applicationset git                   revision  HEAD                   files                        path   examples git generator files discovery cluster config engineering    config json     is produced by cluster generator  1  When using a Matrix generator nested inside another Matrix or Merge generator   Post Selectors  Generators Post Selector md  for this nested generator s generators will only be applied when enabled via  spec applyNestedSelectors   You may also need to enable this even if your Post Selectors are not within the nested matrix or Merge generator  but are instead a sibling of a nested Matrix or Merge generator             matrix              generators                  matrix                    generators                        list                         elements                                                            selector        Only applied when applyNestedSelectors is true


argocd The ApplicationSet controller is a that adds support for an CRD This controller CRD enables both automation and greater flexibility managing Applications across a large number of clusters and within monorepos plus it makes self service usage possible on multitenant Kubernetes clusters The ApplicationSet controller works alongside an existing Argo CD is a declarative GitOps continuous delivery tool which allows developers to define and control deployment of Kubernetes application resources from within their existing Git workflow Starting with Argo CD v2 3 the ApplicationSet controller is bundled with Argo CD Introduction Introduction to ApplicationSet controller

Answer:
# Introduction to ApplicationSet controller

## Introduction

The ApplicationSet controller is a [Kubernetes controller](https://kubernetes.io/docs/concepts/architecture/controller/) that adds support for an `ApplicationSet` [CustomResourceDefinition](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/) (CRD). This controller/CRD enables both automation and greater flexibility managing [Argo CD](../../index.md) Applications across a large number of clusters and within monorepos, plus it makes self-service usage possible on multitenant Kubernetes clusters.

The ApplicationSet controller works alongside an existing [Argo CD installation](../../index.md). Argo CD is a declarative, GitOps continuous delivery tool, which allows developers to define and control deployment of Kubernetes application resources from within their existing Git workflow.

Starting with Argo CD v2.3, the ApplicationSet controller is bundled with Argo CD.

The ApplicationSet controller, supplements Argo CD by adding additional features in support of cluster-administrator-focused scenarios. The `ApplicationSet` controller provides:

- The ability to use a single Kubernetes manifest to target multiple Kubernetes clusters with Argo CD
- The ability to use a single Kubernetes manifest to deploy multiple applications from one or multiple Git repositories with Argo CD
- Improved support for monorepos: in the context of Argo CD, a monorepo is multiple Argo CD Application resources defined within a single Git repository
- Within multitenant clusters, improves the ability of individual cluster tenants to deploy applications using Argo CD (without needing to involve privileged cluster administrators in enabling the destination clusters/namespaces)

!!! note
    Be aware of the [security implications](./Security.md) of ApplicationSets before using them.

## The ApplicationSet resource

This example defines a new `guestbook` resource of kind `ApplicationSet`:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: guestbook
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - cluster: engineering-dev
        url: https://1.2.3.4
      - cluster: engineering-prod
        url: https://2.4.6.8
      - cluster: finance-preprod
        url: https://9.8.7.6
  template:
    metadata:
      name: '-guestbook'
    spec:
      project: my-project
      source:
        repoURL: https://github.com/infra-team/cluster-deployments.git
        targetRevision: HEAD
        path: guestbook/
      destination:
        server: ''
        namespace: guestbook
```

In this example, we want to deploy our `guestbook` application (with the Kubernetes resources for this application coming from Git, since this is GitOps) to a list of Kubernetes clusters (with the list of target clusters defined in the List items element of the `ApplicationSet` resource).

While there are multiple types of *generators* that are available to use with the `ApplicationSet` resource, this example uses the List generator, which simply contains a fixed, literal list of clusters to target. This list of clusters will be the clusters upon which Argo CD deploys the `guestbook` application resources, once the ApplicationSet controller has processed the `ApplicationSet` resource.

Generators, such as the List generator, are responsible for generating *parameters*. Parameters are key-values pairs that are substituted into the `template:` section of the ApplicationSet resource during template rendering.

There are multiple generators currently supported by the ApplicationSet controller:

- **List generator**: Generates parameters based on a fixed list of cluster name/URL values, as seen in the example above.
- **Cluster generator**: Rather than a literal list of clusters (as with the list generator), the cluster generator automatically generates cluster parameters based on the clusters that are defined within Argo CD.
- **Git generator**: The Git generator generates parameters based on files or folders that are contained within the Git repository defined within the generator resource.
    - Files containing JSON values will be parsed and converted into template parameters.
    - Individual directory paths within the Git repository may be used as parameter values, as well.
- **Matrix generator**: The Matrix generators combines the generated parameters of two other generators.

See the [generator section](Generators.md) for more information about individual generators, and the other generators not listed above.

## Parameter substitution into templates

Independent of which generator is used, parameters generated by a generator are substituted into `` values within the `template:` section of the `ApplicationSet` resource. In this example, the List generator defines `cluster` and `url` parameters, which are then substituted into the template's `` and `` values, respectively.

After substitution, this `guestbook` `ApplicationSet` resource is applied to the Kubernetes cluster:

1. The ApplicationSet controller processes the generator entries, producing a set of template parameters.
2. These parameters are substituted into the template, once for each set of parameters.
3. Each rendered template is converted into an Argo CD `Application` resource, which is then created (or updated) within the Argo CD namespace.
4. Finally, the Argo CD controller is notified of these `Application` resources and is responsible for handling them.

With the three different clusters defined in our example -- `engineering-dev`, `engineering-prod`, and `finance-preprod` -- this will produce three new Argo CD `Application` resources: one for each cluster.

Here is an example of one of the `Application` resources that would be created, for the `engineering-dev` cluster at `1.2.3.4`:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: engineering-dev-guestbook
spec:
  source:
    repoURL: https://github.com/infra-team/cluster-deployments.git
    targetRevision: HEAD
    path: guestbook/engineering-dev
  destination:
    server: https://1.2.3.4
    namespace: guestbook
```
We can see that the generated values have been substituted into the `server` and `path` fields of the template, and the template has been rendered into a fully-fleshed out Argo CD Application.

The Applications are now also visible from within the Argo CD UI:

![List generator example in Argo CD Web UI](../../assets/applicationset/Introduction/List-Example-In-Argo-CD-Web-UI.png)

The ApplicationSet controller will ensure that any changes, updates, or deletions made to `ApplicationSet` resources are automatically applied to the corresponding `Application`(s).

For instance, if a new cluster/URL list entry was added to the List generator, a new Argo CD `Application` resource would be accordingly created for this new cluster. Any edits made to the `guestbook` `ApplicationSet` resource will affect all the Argo CD Applications that were instantiated by that resource, including the new Application.

While the List generator's literal list of clusters is fairly simplistic, much more sophisticated scenarios are supported by the other available generators in the ApplicationSet controller.

Introduction to ApplicationSet controller     Introduction  The ApplicationSet controller is a  Kubernetes controller  https   kubernetes io docs concepts architecture controller   that adds support for an  ApplicationSet   CustomResourceDefinition  https   kubernetes io docs tasks extend kubernetes custom resources custom resource definitions    CRD   This controller CRD enables both automation and greater flexibility managing  Argo CD        index md  Applications across a large number of clusters and within monorepos  plus it makes self service usage possible on multitenant Kubernetes clusters   The ApplicationSet controller works alongside an existing  Argo CD installation        index md   Argo CD is a declarative  GitOps continuous delivery tool  which allows developers to define and control deployment of Kubernetes application resources from within their existing Git workflow   Starting with Argo CD v2 3  the ApplicationSet controller is bundled with Argo CD   The ApplicationSet controller  supplements Argo CD by adding additional features in support of cluster administrator focused scenarios  The  ApplicationSet  controller provides     The ability to use a single Kubernetes manifest to target multiple Kubernetes clusters with Argo CD   The ability to use a single Kubernetes manifest to deploy multiple applications from one or multiple Git repositories with Argo CD   Improved support for monorepos  in the context of Argo CD  a monorepo is multiple Argo CD Application resources defined within a single Git repository   Within multitenant clusters  improves the ability of individual cluster tenants to deploy applications using Argo CD  without needing to involve privileged cluster administrators in enabling the destination clusters namespaces       note     Be aware of the  security implications    Security md  of ApplicationSets before using them      The ApplicationSet resource  This example defines a new  guestbook  resource of kind  ApplicationSet      yaml apiVersion  argoproj io v1alpha1 kind  ApplicationSet metadata    name  guestbook spec    goTemplate  true   goTemplateOptions    missingkey error     generators      list        elements          cluster  engineering dev         url  https   1 2 3 4         cluster  engineering prod         url  https   2 4 6 8         cluster  finance preprod         url  https   9 8 7 6   template      metadata        name    guestbook      spec        project  my project       source          repoURL  https   github com infra team cluster deployments git         targetRevision  HEAD         path  guestbook        destination          server             namespace  guestbook      In this example  we want to deploy our  guestbook  application  with the Kubernetes resources for this application coming from Git  since this is GitOps  to a list of Kubernetes clusters  with the list of target clusters defined in the List items element of the  ApplicationSet  resource    While there are multiple types of  generators  that are available to use with the  ApplicationSet  resource  this example uses the List generator  which simply contains a fixed  literal list of clusters to target  This list of clusters will be the clusters upon which Argo CD deploys the  guestbook  application resources  once the ApplicationSet controller has processed the  ApplicationSet  resource   Generators  such as the List generator  are responsible for generating  parameters   Parameters are key values pairs that are substituted into the  template   section of the ApplicationSet resource during template rendering   There are multiple generators currently supported by the ApplicationSet controller       List generator    Generates parameters based on a fixed list of cluster name URL values  as seen in the example above      Cluster generator    Rather than a literal list of clusters  as with the list generator   the cluster generator automatically generates cluster parameters based on the clusters that are defined within Argo CD      Git generator    The Git generator generates parameters based on files or folders that are contained within the Git repository defined within the generator resource        Files containing JSON values will be parsed and converted into template parameters        Individual directory paths within the Git repository may be used as parameter values  as well      Matrix generator    The Matrix generators combines the generated parameters of two other generators   See the  generator section  Generators md  for more information about individual generators  and the other generators not listed above      Parameter substitution into templates  Independent of which generator is used  parameters generated by a generator are substituted into    values within the  template   section of the  ApplicationSet  resource  In this example  the List generator defines  cluster  and  url  parameters  which are then substituted into the template s    and    values  respectively   After substitution  this  guestbook   ApplicationSet  resource is applied to the Kubernetes cluster   1  The ApplicationSet controller processes the generator entries  producing a set of template parameters  2  These parameters are substituted into the template  once for each set of parameters  3  Each rendered template is converted into an Argo CD  Application  resource  which is then created  or updated  within the Argo CD namespace  4  Finally  the Argo CD controller is notified of these  Application  resources and is responsible for handling them    With the three different clusters defined in our example     engineering dev    engineering prod   and  finance preprod     this will produce three new Argo CD  Application  resources  one for each cluster   Here is an example of one of the  Application  resources that would be created  for the  engineering dev  cluster at  1 2 3 4      yaml apiVersion  argoproj io v1alpha1 kind  Application metadata    name  engineering dev guestbook spec    source      repoURL  https   github com infra team cluster deployments git     targetRevision  HEAD     path  guestbook engineering dev   destination      server  https   1 2 3 4     namespace  guestbook     We can see that the generated values have been substituted into the  server  and  path  fields of the template  and the template has been rendered into a fully fleshed out Argo CD Application   The Applications are now also visible from within the Argo CD UI     List generator example in Argo CD Web UI        assets applicationset Introduction List Example In Argo CD Web UI png   The ApplicationSet controller will ensure that any changes  updates  or deletions made to  ApplicationSet  resources are automatically applied to the corresponding  Application  s    For instance  if a new cluster URL list entry was added to the List generator  a new Argo CD  Application  resource would be accordingly created for this new cluster  Any edits made to the  guestbook   ApplicationSet  resource will affect all the Argo CD Applications that were instantiated by that resource  including the new Application   While the List generator s literal list of clusters is fairly simplistic  much more sophisticated scenarios are supported by the other available generators in the ApplicationSet controller