This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: argocd-applicationset-matrix-governance-guardrail

ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards

Enforces strict structural constraints on ArgoCD ApplicationSet Matrix generators combining cluster selectors and Git directories. Prevents catastrophic multi-cluster cascade pruning, accidental secret exposure through parameter interpolation, and runaway Application CR explosion via explicit sync policies, preservation finalizers, and parameter validation.

Prohibited Anti-Pattern: Unbounded Matrix Combinations with Default Cascade Pruning and Raw Secret Interpolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards - Enforces strict structural constraints on ArgoCD ApplicationSet Matrix generators combining cluster selectors and Git directories. Prevents catastrophic multi-cluster cascade pruning, accidental secret exposure through parameter interpolation, and runaway Application CR explosion via explicit sync policies, preservation finalizers, and parameter validation.
globs: **/applicationset*.yaml, **/applicationset*.yml, **/templates/applicationset*.yaml, **/templates/applicationset*.yml, **/gitops/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/argocd-applicationset-matrix-governance-guardrail"
---

# ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Matrix Combinations with Default Cascade Pruning and Raw Secret Interpolation

## System Constraints
You are a Principal GitOps Architect enforcing zero-trust, resilient ArgoCD ApplicationSet Matrix generators. Mandate preserveResources deletion policies, strict generator matrix dimensions, non-cascading AppProject controls, and automated secret hydration via external secret operators rather than Git parameter substitution.

## Strict Guidelines
- Engineers MUST ALWAYS configure 'spec.syncPolicy.preserveResourcesOnDeletion: true' in ApplicationSets to prevent transient matrix evaluation errors from cascades wiping live cluster workloads.
- Engineers MUST NOT combine more than two matrix generators (e.g., Git + Clusters) without strict negative matching labels or explicit path filters to avoid Cartesian product explosion.
- Code MUST explicitly set metadata finalizers to 'resources-finalizer.argocd.argoproj.io/foreground' only when deterministic de-provisioning is required, otherwise default to non-cascading deletion during refactors.
- Services MUST delegate secret injection to in-cluster operators (ExternalSecrets/Vault CSI) via dynamic metadata targets rather than hydrating cleartext secrets via Git generator template substitution.
- Components NEVER interpolate raw user-controlled branch names or unbound Git revisions directly into 'spec.template.spec.destination.namespace' without sanitization filters.

## Bad vs Good Implementations
### ApplicationSet Matrix Generator: Unsafe Deletion Cascade vs. Guarded Multi-Cluster Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Critical flaws: 1) Empty cluster generator creates an unbounded cross-product targeting all registered clusters (including non-production). 2) Missing 'preserveResourcesOnDeletion' causes complete deletion of all production workloads if Git repo connectivity blips. 3) Interpolates cleartext database password from cluster annotations directly into Helm values. 4) Unrestricted namespace creation without project guardrails.
```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: microservices-deployer
  namespace: argocd
spec:
  generators:
    - matrix:
        generators:
          - git:
              repoURL: https://github.com/org/infra-gitops.git
              revision: HEAD
              directories:
                - path: apps/*
          - clusters: {}
  template:
    metadata:
      name: '{{path.basename}}-{{name}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/org/infra-gitops.git
        targetRevision: HEAD
        path: '{{path}}'
        helm:
          parameters:
            - name: "databasePassword"
              value: "{{cluster.metadata.annotations.dbPassword}}"
      destination:
        server: '{{server}}'
        namespace: '{{path.basename}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
```

#### Production Standard (Correct)
> **Standard**: Production invariants applied: 1) 'preserveResourcesOnDeletion: true' protects all underlying Kubernetes resources if the ApplicationSet is deleted or generator calculation fails. 2) Explicit cluster matchLabels bound the matrix cross-product to designated production clusters. 3) Secret hydration uses ExternalSecrets references rather than parameter injection. 4) Target namespace is explicitly prefixed and managed out-of-band ('CreateNamespace=false').
```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: microservices-deployer
  namespace: argocd
spec:
  syncPolicy:
    preserveResourcesOnDeletion: true
  generators:
    - matrix:
        generators:
          - git:
              repoURL: https://github.com/org/infra-gitops.git
              revision: HEAD
              directories:
                - path: apps/*
              exclude: false
          - clusters:
              selector:
                matchLabels:
                  argocd.argoproj.io/environment: production
                  workload.capability/microservices: "enabled"
  template:
    metadata:
      name: 'prod-{{path.basename}}-{{name}}'
      labels:
        environment: '{{metadata.labels.argocd.argoproj.io/environment}}'
    spec:
      project: microservices-prod
      source:
        repoURL: https://github.com/org/infra-gitops.git
        targetRevision: HEAD
        path: '{{path}}'
        helm:
          values: |
            externalSecrets:
              enabled: true
              secretStoreRef: "vault-backend"
      destination:
        server: '{{server}}'
        namespace: 'apps-{{path.basename}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - CreateNamespace=false
          - ServerSideApply=true
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards

ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards defines an industrial-grade behavioral standard for devops engineering. Enforces strict structural constraints on ArgoCD ApplicationSet Matrix generators combining cluster selectors and Git directories. Prevents catastrophic multi-cluster cascade pruning, accidental secret exposure through parameter interpolation, and runaway Application CR explosion via explicit sync policies, preservation finalizers, and parameter validation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Matrix Combinations with Default Cascade Pruning and Raw Secret Interpolation Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Matrix Combinations with Default Cascade Pruning and Raw Secret InterpolationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS configure 'spec.syncPolicy.preserveResourcesOnDeletion

Engineers MUST ALWAYS configure 'spec.syncPolicy.preserveResourcesOnDeletion: true' in ApplicationSets to prevent transient matrix evaluation errors from cascades wiping live cluster workloads.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT combine more than two matrix generators (e.g., Git + Clusters) without strict negative matching labels or explicit path filters to avoid Cartesian product explosion.

Engineers MUST NOT combine more than two matrix generators (e.g., Git + Clusters) without strict negative matching labels or explicit path filters to avoid Cartesian product explosion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST explicitly set metadata finalizers to 'resources-finalizer.argocd.argoproj.io/foreground' only when deterministic de-provisioning is required, otherwise default to non-cascading deletion during refactors.

Code MUST explicitly set metadata finalizers to 'resources-finalizer.argocd.argoproj.io/foreground' only when deterministic de-provisioning is required, otherwise default to non-cascading deletion during refactors.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST delegate secret injection to in-cluster operators (ExternalSecrets/Vault CSI) via dynamic metadata targets rather than hydrating cleartext secrets via Git generator template substitution.

Services MUST delegate secret injection to in-cluster operators (ExternalSecrets/Vault CSI) via dynamic metadata targets rather than hydrating cleartext secrets via Git generator template substitution.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER interpolate raw user-controlled branch names or unbound Git revisions directly into 'spec.template.spec.destination.namespace' without sanitization filters.

Components NEVER interpolate raw user-controlled branch names or unbound Git revisions directly into 'spec.template.spec.destination.namespace' without sanitization filters.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is ArgoCD ApplicationSet Matrix Generator Invariants & Cascade Deletion Guards critical for AI coding assistants?

Enforces strict structural constraints on ArgoCD ApplicationSet Matrix generators combining cluster selectors and Git directories. Prevents catastrophic multi-cluster cascade pruning, accidental secret exposure through parameter interpolation, and runaway Application CR explosion via explicit sync policies, preservation finalizers, and parameter validation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Matrix Combinations with Default Cascade Pruning and Raw Secret Interpolation) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

ArgoCD