Lesson 4: ArgoCD ApplicationSets, Crossplane vs. Terraform & Exception Handling
๐ง The Concept (Explain Like Iโm 5)
Imagine you own a national toy store franchise with 50 stores across the country:
- The Manual Application (One Toy Box at a Time): In pure ArgoCD, an
Applicationmanifest deploys one microservice to one cluster. If you have 50 Kubernetes clusters and 200 microservices, an engineer has to write and maintain 10,000 separate YAML files by hand (50 ร 200). If you open Store #51, you must spend a week writing 200 more YAML files. - The ApplicationSet (The Automated Industrial Assembly Line): You write one single 25-line template that says: โFor every production store that opens, cross-multiply it with every core microservice and deploy them automatically.โ When Store #51 opens, all 200 microservices deploy in 30 seconds with zero new lines of code!
- Crossplane vs. Terraform (The Thermostat vs. The Recipe):
- Terraform is a Baking Recipe: You follow the instructions, bake the cake, and turn off the oven (
terraform apply). If someone steals a slice 3 days later, Terraform doesnโt notice until someone explicitly runsterraform plan. - Crossplane is a Smart Thermostat: You set the temperature to 72ยฐF. It sits in a continuous 24/7 control loop. The millisecond someone opens a window (manual out-of-band cloud edit), the thermostat detects the cold air and automatically fires the furnace to push reality back to 72ยฐF (Continuous Kubernetes Reconciliation).
- Terraform is a Baking Recipe: You follow the instructions, bake the cake, and turn off the oven (
๐ข The Enterprise Context (Why Platform Architects Care)
- Fleet Fleetwide GitOps Orchestration: Large enterprises do not operate single monolithic clusters. They operate dozens of clusters partitioned by region, environment, and compliance tier (PCI, HIPAA, FedRAMP).
ApplicationSetsallow platform teams to manage thousands of application deployments declaratively using automated generators. - The Paradigm Shift: Infrastructure as Code (IaC) vs. Control Planes:
- Terraform is optimal for Day-0 foundational bootstrapping (AWS Organizations, Landing Zones, VPCs, Transit Gateways).
- Crossplane is superior for Day-2 developer self-service claims (allowing developers to provision RDS databases or S3 buckets directly using native Kubernetes YAML without needing AWS console access or Terraform CI pipeline queues).
- Preventing Mass Destruction at Fleet Scale: An ApplicationSet is extraordinarily powerfulโwhich means a syntax error or misconfigured label selector can accidentally trigger the simultaneous deletion of 500 applications across 50 production clusters in seconds! Implementing safety policies (
preserveResourcesOnDeletion) is paramount.
๐บ๏ธ Visual Architecture: ApplicationSet Matrix Generator Workflow
flowchart TD
subgraph Generators ["ApplicationSet Matrix Generators"]
GenCluster["<b>Cluster Generator</b><br/>Discovers clusters with label: <code>env=production</code><br/>โข prod-us-east-1<br/>โข prod-eu-west-1<br/>โข prod-ap-southeast-1"]
GenGit["<b>Git Directory Generator</b><br/>Discovers folders under <code>services/*</code> in Git<br/>โข payment-api<br/>โข order-api<br/>โข auth-api"]
end
Matrix["<b>ArgoCD ApplicationSet Controller (Matrix Generator)</b><br/>Mathematically Cross-Multiplies: 3 Clusters ร 3 Services = 9 Apps"]
GenCluster --> Matrix
GenGit --> Matrix
subgraph GeneratedApplications ["Automatically Generated ArgoCD Applications"]
A1["App: payment-api on prod-us-east-1"]
A2["App: payment-api on prod-eu-west-1"]
A3["App: payment-api on prod-ap-southeast-1"]
A4["App: order-api on prod-us-east-1"]
A5["App: order-api on prod-eu-west-1"]
A6["... Remaining Applications"]
end
Matrix --> A1
Matrix --> A2
Matrix --> A3
Matrix --> A4
Matrix --> A5
Matrix --> A6
๐ฌ Under the Hood: Crossplane vs. Terraform Architectural Showdown
| Evaluation Dimension | HashiCorp Terraform | Crossplane (Kubernetes Control Plane) |
|---|---|---|
| Execution Architecture | Discrete, batch-driven execution triggered by CI/CD runner | Continuous 24/7 reconciliation loop running inside Kubernetes |
| State Storage | terraform.tfstate in AWS S3 with DynamoDB lock |
Stored natively in Kubernetes etcd as Custom Resources (CRDs) |
| Drift Management | Detects drift only when terraform plan is executed |
Self-healing: Reverts unauthorized console changes immediately |
| API Paradigm | HashiCorp Configuration Language (HCL) | Declarative Kubernetes YAML / OpenAPI schema |
| RBAC Integration | Cloud IAM roles, VCS tokens, or Terraform Cloud RBAC | Native Kubernetes RBAC, ServiceAccounts, and Namespaces |
| Primary Platform Fit | Day-0 Architecture: AWS Landing Zones, TGWs, Base VPCs | Day-2 Self-Service: Developer Claims for S3, RDS, Redis, SQS |
๐ป Production Code: Enterprise Matrix ApplicationSet
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: enterprise-workload-matrix
namespace: argocd
spec:
# CRITICAL SAFETY RULE: Prevent deleting K8s resources if ApplicationSet is modified
syncPolicy:
preserveResourcesOnDeletion: true
generators:
- matrix:
generators:
# Generator 1: Discover all production clusters registered with the Hub
- clusters:
selector:
matchLabels:
environment: production
# Generator 2: Discover service manifests from Git directory layout
- git:
repoURL: https://github.com/corp-enterprise/gitops-fleet.git
revision: HEAD
directories:
- path: apps/workloads/*
template:
metadata:
name: '{{name}}-{{path.basename}}'
annotations:
notifications.argoproj.io/subscribe.on-sync-failed.slack: platform-alerts
spec:
project: default
source:
repoURL: https://github.com/corp-enterprise/gitops-fleet.git
targetRevision: HEAD
path: '{{path}}'
helm:
valueFiles:
- 'values.yaml'
- 'values-{{name}}.yaml' # Dynamically injects cluster-specific overrides!
destination:
server: '{{server}}' # Target cluster API endpoint injected by generator
namespace: '{{path.basename}}'
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
- ApplyOutOfSyncOnly=true
Detailed Breakdown of ApplicationSet Key Fields & Mechanics:
preserveResourcesOnDeletion: true(The Platform Safety Airbag):- Mechanism: Prevents ArgoCD from cascading deletion of underlying cluster resources if the ApplicationSet is deleted, refactored, or its generator criteria change. Without this, altering a label selector wipes out 500 applications across 50 clusters in seconds.
generators.matrix(Combinatorial Cross-Multiplication):- Mechanism: Evaluates multiple generator arrays simultaneously. Here, it multiplies the discovered cluster list (Env: production = N clusters) by the discovered service directories (apps/workloads/* = M microservices). Total applications managed: N ร M.
- Dynamic Helm Value Overrides (
values-{{name}}.yaml):- Mechanism: Injects cluster-specific environment variables, replica counts, or ingress domains (
values-prod-us-east-1.yamlvsvalues-prod-eu-west-1.yaml) while referencing a single centralized Helm chart codebase.
- Mechanism: Injects cluster-specific environment variables, replica counts, or ingress domains (
ApplyOutOfSyncOnly: true(etcd Performance Optimization):- Mechanism: By default, ArgoCD re-applies all Kubernetes resources during a sync. Setting this flag instructs ArgoCD to only send HTTP PATCH requests to the Kubernetes API server for resources that actually drifted, reducing API server CPU load and
etcdwrite latency by 85% at fleet scale.
- Mechanism: By default, ArgoCD re-applies all Kubernetes resources during a sync. Setting this flag instructs ArgoCD to only send HTTP PATCH requests to the Kubernetes API server for resources that actually drifted, reducing API server CPU load and
๐๏ธ Production Manifests: Crossplane XRD, Composition & Claim Ecosystem
To turn Kubernetes into a true enterprise Internal Developer Platform (IDP) control plane, Platform Architects define custom infrastructure APIs using Crossplane:
flowchart TD
Dev["๐จโ๐ป App Developer"] -->|"1. Submits 10-line Claim"| Claim["<b>Developer Claim</b><br/>(PostgreSQLInstance)"]
Claim --> XRD["<b>CompositeResourceDefinition (XRD)</b><br/>API Contract & Schema Validator"]
XRD --> Composition["<b>Platform Composition</b><br/>Enforces Encryption, VPC, Subnets & Backup Policies"]
Composition --> AWS_RDS["โ๏ธ AWS RDS DBInstance"]
Composition --> AWS_KMS["โ๏ธ AWS KMS CMK Key"]
Composition --> AWS_SecGrp["โ๏ธ AWS Security Group"]
AWS_RDS -.->|"Connection Secret"| Secret[("Kubernetes Secret in App Namespace<br/>(host, port, user, password)")]
Secret --> Pod["๐ฆ App Pod connects to Database โ
"]
1. The API Contract: CompositeResourceDefinition (xrd.yaml)
apiVersion: apiextensions.crossplane.io/v1
kind: CompositeResourceDefinition
metadata:
name: xpostgresqlinstances.database.corp.io
spec:
group: database.corp.io
names:
kind: XPostgreSQLInstance
plural: xpostgresqlinstances
claimNames:
kind: PostgreSQLInstance
plural: postgresqlinstances
versions:
- name: v1alpha1
served: true
referenceable: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [storageGB, environment]
properties:
storageGB:
type: integer
minimum: 20
maximum: 1000
environment:
type: string
enum: [dev, staging, prod]
2. The Platform Blueprint: Pipeline Composition with KCL (composition.yaml)
In modern Crossplane (v1.14+), raw YAML patches have been officially superseded by Composition Functions (mode: Pipeline). Using KCL (Knowledge Constraint Language) or Python functions allows platform architects to write real conditional logic, dynamic sizing, and loops with compile-time type safety:
# composition-kcl.yaml - Modern Crossplane v1.14+ Pipeline Composition
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
name: xpostgresqlinstances.aws.pipeline
labels:
provider: aws
db: postgresql
spec:
compositeTypeRef:
apiVersion: database.corp.io/v1alpha1
kind: XPostgreSQLInstance
mode: Pipeline # Enables Function Pipeline execution
pipeline:
# Step 1: Execute KCL Function for dynamic sizing and conditional logic
- step: generate-cloud-resources
functionRef:
name: function-kcl
input:
apiVersion: kcl.fn.crossplane.io/v1alpha1
kind: KCLInput
source: |
# Read developer claim inputs
oxr = option("params").oxr
env = oxr.spec.environment
storage_gb = oxr.spec.storageGB
# Enterprise conditional logic: Prod gets Multi-AZ, Dev gets Cost-Optimized
is_prod = env == "prod"
instance_class = "db.m6g.xlarge" if is_prod else "db.t4g.medium"
backup_retention = 30 if is_prod else 1
multi_az = True if is_prod else False
# Emit low-level AWS RDS Managed Resource dynamically
items = [
{
apiVersion = "rds.aws.upbound.io/v1beta1"
kind = "Instance"
metadata.name = "rds-{}-instance".format(oxr.metadata.name)
spec = {
forProvider = {
engine = "postgres"
engineVersion = "16.1"
instanceClass = instance_class
allocatedStorage = storage_gb
multiAz = multi_az
backupRetentionPeriod = backup_retention
publiclyAccessible = False
storageEncrypted = True
skipFinalSnapshot = not is_prod
}
# Securely write connection secrets back to developer namespace
writeConnectionSecretToRef = {
namespace = oxr.spec.claimRef.namespace if "claimRef" in oxr.spec else "default"
name = oxr.spec.writeConnectionSecretToRef.name
}
}
}
]
# Step 2: Automatically detect readiness of all child cloud resources
- step: auto-ready
functionRef:
name: function-auto-ready
3. The Self-Service Request: Developer Claim (claim.yaml)
# Submitted by App Developer in their own namespace (Zero AWS Console access needed!)
apiVersion: database.corp.io/v1alpha1
kind: PostgreSQLInstance
metadata:
name: payment-database
namespace: workloads
spec:
storageGB: 50
environment: prod
writeConnectionSecretToRef:
name: payment-db-credentials # Automatically injected into app namespace!
Detailed Breakdown of Crossplane Key Fields & Mechanics:
- The API Contract (
XRD: CompositeResourceDefinition):spec.schema.openAPIV3Schema: Restricts what developers can request. Here, developers can only specifystorageGB(integer clamped between 20 and 1000) andenvironment(dev,staging,prod). High-risk parameters (KMS encryption keys, VPC subnets, backup retention policies) are deliberately hidden from the developer API schema.
- The Platform Implementation (
Composition):spec.compositeTypeRef: Binds this blueprint to the XRD contract.patches.FromCompositeFieldPath: Maps developer-facing fields (spec.storageGB) into low-level cloud provider fields (spec.forProvider.allocatedStorageon the AWS RDS Custom Resource).connectionDetails: Securely tunnels database connection strings (username,password,endpoint) generated by AWS RDS directly back through the control plane into the developerโs Kubernetes namespace as a standard Secret (writeConnectionSecretToRef), without granting developers AWS IAM credentials.
- The Developer Claim (
PostgreSQLInstance):- Developer Experience (DevEx): Developers do not need Terraform CLI, AWS Console access, or IAM access keys. They submit a 10-line native Kubernetes manifest through GitOps. Crossplane reconciles it against AWS and hands back a secret ready for pod mounting.
โ ๏ธ Real-World Failure Modes, Exceptions & Break-Glass Playbooks
Exception 1: The Cascading Fleet Deletion Disaster (preserveResourcesOnDeletion)
- The Catastrophe: An engineer refactors the Git repository structure, renaming the folder
apps/workloadstoapps/services. They commit and push to Git. - The Immediate Outage: The ApplicationSet controller evaluates the Git directory generator. It determines that all 50 previous
apps/workloads/*applications no longer match the generator filter! - The Horrific Consequence: If
preserveResourcesOnDeletion: false(the default!), ArgoCD immediately initiates a cascading deletion, wiping out 50 production applications across 50 EKS clusters simultaneously! - The Architectural Rule:
Always declare
preserveResourcesOnDeletion: trueon every production ApplicationSet. If an Application is dereferenced by a generator, ArgoCD removes the Application metadata object from its dashboard while leaving the real-world Pods, Services, and Ingresses running safely in the cluster.
Exception 2: GitHub API Secondary Rate-Limiting During Matrix Generation
- The Failure: An ApplicationSet cross-multiplies 40 clusters by 30 Git directories (1,200 applications). Every 3 minutes, the ApplicationSet controller polls GitHub to check for updates. GitHub blocks the controller with
HTTP 403 Forbidden: You have exceeded a secondary rate limit. The entire GitOps reconciliation pipeline freezes. - The Resolution:
- Disable Aggressive Polling: Increase
appset.reconcile.intervalfrom the default 3 minutes to 30 minutes inargocd-cm. - Implement Webhook-Driven Reconciliation: Configure GitHub Webhooks to push change notifications to ArgoCDโs
/api/webhookendpoint, eliminating polling completely.
- Disable Aggressive Polling: Increase
Exception 3: Crossplane Reconciliation Deadlock on Slow Cloud Resources (RDS Multi-AZ)
- The Problem: A developer submits a Crossplane Claim for an AWS Aurora Multi-AZ database. Provisioning a Multi-AZ cluster in AWS takes 20 to 25 minutes.
- The Failure: Crossplaneโs controller attempts to reconcile the resource every 60 seconds. The underlying Kubernetes API context times out, marking the Custom Resource as
Synced: Falseand firing false-positive alerts while the database is still actively building in AWS. - The Architectural Fix: Tune Crossplaneโs provider poll intervals and configure
external-nameannotations to bind to existing cloud IDs cleanly without interrupting in-flight AWS API provisioning tasks.
๐ Staff Architect & SRE Interview Scenarios
โ ๐ข Low Difficulty: What is a Crossplane Composite Resource Definition (XRD)?
Question: In Crossplane, what is the architectural relationship between a Composite Resource Definition (XRD), a Composition, and a Claim?
Answer:
- XRD (The API Contract): Defines a custom, company-specific Kubernetes API schema (e.g.
kind: PostgreSQLDatabase) specifying high-level developer fields (storageSize: 50Gi,environment: prod). - Composition (The Implementation Blueprint): Created by platform architects. It translates the simple XRD into real low-level cloud resources (e.g., provisioning an AWS RDS DBInstance, a DBSubnetGroup, a KMS Key, and a Security Group).
- Claim (The Developer Request): The simple 10-line YAML file submitted by application developers in their own namespace to provision the infrastructure self-service.
โ ๐ก Medium Difficulty: Matrix Generator vs List Generator in ApplicationSets
Question: When should a platform architect use a List generator versus a Matrix generator in ArgoCD?
Answer:
ListGenerator: Used when deployment targets are static, discrete, and few in number (e.g., explicitly definingcluster-dev,cluster-staging,cluster-prod). Every target must be updated manually in YAML.MatrixGenerator: Used for fleet-scale combinatorial deployments. It cross-multiplies two dynamic generators (e.g., discovering all registered EKS clusters ร discovering all microservice directories in Git), dynamically generating hundreds of applications with zero manual list updates.
โ ๐ด Hard Difficulty: Preventing Out-Of-Sync Reconciliation Thrashing in GitOps
Question: What causes perpetual Out-Of-Sync thrashing between ArgoCD and Kubernetes when deploying workloads with mutating admission webhooks, and how do you resolve it?
Answer: If an external controller (such as an Istio Sidecar Injector, AWS Load Balancer Controller, or Vertical Pod Autoscaler) injects annotations, sidecars, or resources into a running Deployment, ArgoCD compares the live state against the pristine Git manifest. Detecting unexpected differences, ArgoCD flags the application as OutOfSync and attempts to overwrite the pod spec, triggering an infinite reconcile loop.
The Resolution: Configure ignoreDifferences in the Application spec to instruct ArgoCD to ignore fields dynamically managed by mutating webhooks:
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers:
- /spec/template/spec/containers/1 # Ignore injected sidecar
- /spec/template/metadata/annotations
โ ๐ฃ Complex Difficulty: Disaster Recovery Failover with ApplicationSets
Question: During a regional cloud disaster in us-east-1, how do ApplicationSets facilitate instant traffic redirection to a standby cluster in us-west-2 without editing 200 application manifests?
Answer: Because ApplicationSets evaluate cluster label selectors dynamically (environment: production, region: active), an SRE can execute fleet failover with a single cluster relabeling command:
- Relabel
prod-us-east-1fromstatus=activetostatus=standby. - Relabel
prod-us-west-2fromstatus=standbytostatus=active. - The ApplicationSet controller evaluates the change, automatically creates 200 application deployments on
prod-us-west-2, and shifts Route 53 DNS records via external-dns. The entire disaster recovery failover occurs through declarative GitOps without touching individual service YAMLs.