Skip to content
English
  • There are no suggestions because the search field is empty.

Automatic Namespace Cleanup After PR Merge or Close

How to configure ApplicationSet PR generators so that namespaces are fully managed by Argo CD and are automatically deleted when pull requests are merged or closed.

Overview

When using Argo CD ApplicationSets with PR generators to deploy feature branches, each pull request typically gets its own dedicated Kubernetes namespace (e.g., pr-42). These ephemeral environments allow teams to preview and test changes in isolation before they are merged into the main branch.

However, a common pain point arises after the pull request lifecycle ends — either because the PR is merged or closed. In many configurations, Argo CD deletes the Application resource but leaves the Kubernetes namespace behind, requiring manual cleanup.

Problem

Teams using ApplicationSet PR generators observe the following behaviour:

  • A PR is opened → Argo CD creates an Application and a Kubernetes namespace for the feature branch.
  • The PR is merged or closed → Argo CD deletes the generated Application resource.
  • The Kubernetes namespace persists, accumulating over time and consuming cluster resources.
  • Manual namespace deletion is required, adding operational overhead and risk of forgotten cleanup.

Root Cause

Argo CD only manages resources it explicitly owns. Without a tracking annotation on the namespace, Argo CD does not consider the namespace part of the managed resource set and therefore does not prune it during sync or on Application deletion.

Solution

The fix is to add a managedNamespaceMetadata block with an argocd.argoproj.io/tracking-id annotation under syncPolicy in your ApplicationSet template. This annotation tells Argo CD that it owns the namespace resource, enabling full lifecycle management including pruning.

Required Annotation

Add the following to the syncPolicy section of your ApplicationSet spec:

managedNamespaceMetadata:

  annotations:

    argocd.argoproj.io/tracking-id: ":/Namespace:/"

Complete syncPolicy Example

Below is a complete syncPolicy block for a PR-based ApplicationSet, including automated pruning and namespace creation:

syncPolicy:

  managedNamespaceMetadata:

    annotations:

      argocd.argoproj.io/tracking-id: >-

        preview--:/Namespace:/pr-

  automated:

    prune: true

  syncOptions:

    - CreateNamespace=true

Summary

  • Argo CD version 2.5 or later (managedNamespaceMetadata was introduced in this release).
  • The ApplicationSet is configured with a PR generator (GitHub, GitLab, Bitbucket, Gitea, etc.).
  • CreateNamespace=true must be set under syncOptions so that Argo CD is responsible for namespace creation.
  • The Argo CD service account must have sufficient RBAC permissions to create and delete Namespace resources in the target cluster.