| name | crossplane |
| description | Crossplane composition patterns for cloud-native infrastructure provisioning. Provides XRD (CompositeResourceDefinition), Composition, and Claim patterns for AWS, Azure, GCP resources with security best practices, validation pipelines, and hallucination detection for AI-generated compositions.
Activate when user mentions: crossplane, XRD, composite resource, composition, claim, provider config, managed resources, crossplane composition, infrastructure composition, declarative infrastructure, control plane.
Use for: Generating Crossplane compositions, XRDs, Claims, ProviderConfigs, and managed resource patterns following cloud-native best practices with multi-phase validation and cost optimization.
Do NOT use for: Direct Terraform/Pulumi code, CloudFormation templates, Kubernetes operators (unless Crossplane-specific), raw cloud provider APIs.
|
Crossplane Composition Skill
Expert knowledge for generating production-ready Crossplane compositions that follow infrastructure-as-code best practices with strong security defaults, multi-phase validation, and hallucination prevention.
Core Capabilities
1. XRD (CompositeResourceDefinition) Generation
Create composite resource definitions with proper versioning, validation, and schema design:
- API Design: Group/version/kind naming conventions following Kubernetes API standards
- Schema Validation: OpenAPI v3 schemas with constraints, enums, and pattern validation
- Defaulting: Sensible defaults for optional fields with security-first values
- Status Fields: Connection secrets and condition reporting with proper status subresource
- Versioning: Support for v1alpha1, v1beta1, v1 progressions with conversion webhooks
- Schema Validation: Validate all generated resource types against official Crossplane provider schemas (hallucination detection)
2. Composition Patterns
Generate compositions that implement XRDs with managed resources:
- Resource Selection: Use
matchLabels for dynamic composition selection
- Patch Strategies: FromCompositeFieldPath, ToCompositeFieldPath, CombineFromComposite, CombineToComposite
- Connection Secrets: Properly expose credentials to claims with secret propagation
- Dependencies: Use
readinessChecks for resource ordering and dependency management
- Multi-Cloud: Abstract provider differences in compositions for portability
- Transform Functions: Use string, math, and map transforms for computed values
- Composition Functions: Leverage function pipelines for complex logic (Patch & Transform, Go templating)
3. Claim Templates
Generate namespace-scoped claims for developer self-service:
- Simple Interface: Hide complexity from application teams with minimal parameters
- Connection Secrets: Reference secrets in same namespace for application consumption
- Composition Selection: Use labels or explicit compositionRef for environment-specific routing
- Parameters: Expose only necessary configuration knobs following least-privilege principle
- Resource Quotas: Consider namespace resource limits in claim designs
4. ProviderConfig Security
Configure provider authentication following security best practices:
- OIDC/IRSA: Prefer IAM Roles for Service Accounts (no long-lived keys)
- Workload Identity: Use GCP Workload Identity or Azure Managed Identity
- Least Privilege: Scope permissions to required resources with policy validation
- Secret Management: Use Kubernetes secrets with proper RBAC when OIDC unavailable
- Multi-Account: Support separate dev/staging/prod configs with namespace isolation
- Credential Rotation: Document rotation procedures and expiration policies
Multi-Phase Validation Pipeline
CRITICAL: All AI-generated Crossplane compositions MUST pass two-phase validation before deployment:
Phase 1: Technical Validation (Syntax & Structure)
kubectl apply --dry-run=server -f composition.yaml
crossplane beta validate composition.yaml
kubectl get composition -o jsonpath='{.status.conditions[?(@.type=="Synced")].status}'
Phase 2: Intent Validation (Policy & Security)
opa eval --data policies/ --input composition.yaml "data.crossplane.violations"
trivy config composition.yaml \
--severity CRITICAL,HIGH \
--format json \
--output trivy-report.json
Hallucination Detection Checklist
Target metrics: >99% hallucination detection rate, >95% validation success rate
Security Patterns
Credential Management
REQUIRED: All provider configurations MUST use OIDC/IRSA or similar short-lived credentials:
apiVersion: aws.crossplane.io/v1beta1
kind: ProviderConfig
metadata:
name: aws-provider-config
spec:
credentials:
source: InjectedIdentity
assumeRoleChain:
- roleARN: arn:aws:iam::123456789012:role/crossplane-prod
apiVersion: gcp.crossplane.io/v1beta1
kind: ProviderConfig
metadata:
name: gcp-provider-config
spec:
credentials:
source: InjectedIdentity
projectID: my-gcp-project-id
apiVersion: azure.crossplane.io/v1beta1
kind: ProviderConfig
metadata:
name: azure-provider-config
spec:
credentials:
source: InjectedIdentity
apiVersion: aws.crossplane.io/v1beta1
kind: ProviderConfig
metadata:
name: aws-provider-config
spec:
credentials:
source: Secret
secretRef:
name: aws-credentials
namespace: crossplane-system
key: credentials
Secret References
Never hardcode secrets in compositions or XRDs. Use .env pattern:
- Provide
.env.example with placeholder values
- Document required secrets in README with rotation procedures
- Reference secrets from ProviderConfig or connection secrets
- Use Kubernetes RBAC to restrict secret access
- Scan for hardcoded credentials using Trivy
--scanners secret
RBAC Boundaries
Limit claim creation to specific namespaces with proper role separation:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: crossplane-xrd-admin
rules:
- apiGroups: ["apiextensions.crossplane.io"]
resources: ["compositeresourcedefinitions", "compositions"]
verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: crossplane-claim-user
namespace: dev-team-namespace
rules:
- apiGroups: ["database.example.com"]
resources: ["postgresqlclaims"]
verbs: ["create", "get", "list", "watch", "delete"]
Security Scanning Integration
Trivy Configuration (scan Crossplane YAML manifests):
trivy image --download-db-only
trivy config crossplane/compositions/ \
--severity CRITICAL,HIGH \
--ignore-unfixed \
--format json \
--exit-code 1
trivy config crossplane/ \
--format cyclonedx \
--output crossplane-sbom.json
Checkov Configuration (compliance frameworks):
checkov -d crossplane/compositions/ \
--framework kubernetes \
--compact \
--quiet
checkov -d crossplane/ \
--external-checks-dir ./policies/ \
--check CKV_CROSSPLANE_1
.trivyignore Example (document exceptions with expiration):
# CVE-2024-1234: False positive - not applicable to Crossplane compositions
# Reviewed: 2026-02-03, Expires: 2026-05-03, Approved: security-team@example.com
CVE-2024-1234
# MEDIUM severity findings accepted for dev environment
# Review quarterly for production promotions
CKV_K8S_20
Composition Structure
Standard Composition Layout
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
name: {resource-type}-{cloud-provider}-{variant}
labels:
crossplane.io/xrd: x{resourcetype}s.{group}
provider: {aws|azure|gcp}
environment: {dev|staging|prod}
cost-optimized: "true"
spec:
writeConnectionSecretsToNamespace: crossplane-system
compositeTypeRef:
apiVersion: {group}/{version}
kind: X{ResourceType}
mode: Pipeline
pipeline:
- step: patch-and-transform
functionRef:
name: function-patch-and-transform
input:
apiVersion: pt.fn.crossplane.io/v1beta1
kind: Resources
resources: []
resources:
- name: {logical-name}
base:
apiVersion: {provider-api}
kind: {ManagedResource}
spec:
forProvider:
providerConfigRef:
name: {provider-config-name}
deletionPolicy: Orphan
patches:
- type: FromCompositeFieldPath
fromFieldPath: spec.parameters.{field}
toFieldPath: spec.forProvider.{field}
transforms:
- type: string
string:
fmt: "prefix-%s-suffix"
- type: ToCompositeFieldPath
fromFieldPath: status.atProvider.{field}
toFieldPath: status.{field}
- type: CombineFromComposite
combine:
variables:
- fromFieldPath: spec.parameters.name
- fromFieldPath: spec.parameters.environment
strategy: string
string:
fmt: "%s-%s-resource"
toFieldPath: spec.forProvider.resourceName
readinessChecks:
- type: MatchString
fieldPath: status.atProvider.state
matchString: "ACTIVE"
connectionDetails:
- type: FromConnectionSecretKey
name: {output-key}
fromConnectionSecretKey: {provider-key}
Cost Optimization Patterns
Spot Instance Integration for Compute Resources
EKS Node Groups with Spot Instances (66-90% savings):
apiVersion: eks.aws.crossplane.io/v1alpha1
kind: NodeGroup
metadata:
name: spot-nodegroup
spec:
forProvider:
capacityType: SPOT
instanceTypes:
- t3a.medium
- t3.medium
- t2.medium
- t3a.large
scalingConfig:
desiredSize: 3
maxSize: 10
minSize: 1
updateConfig:
maxUnavailable: 1
GKE Node Pool with Spot VMs:
apiVersion: container.gcp.crossplane.io/v1beta2
kind: NodePool
metadata:
name: spot-nodepool
spec:
forProvider:
nodeConfig:
spot: true
machineType: e2-standard-4
diskSizeGb: 100
autoscaling:
enabled: true
minNodeCount: 1
maxNodeCount: 10
management:
autoRepair: true
autoUpgrade: true
Interruption Handling (include in composition documentation):
apiVersion: cloudwatchevents.aws.crossplane.io/v1alpha1
kind: Rule
metadata:
name: spot-interruption-handler
spec:
forProvider:
eventPattern: |
{
"source": ["aws.ec2"],
"detail-type": ["EC2 Spot Instance Interruption Warning"]
}
targets:
- arn: arn:aws:lambda:region:account:function:drain-node
id: spot-drain-lambda
Right-Sizing and Auto-Scaling
Auto-Scaling Policies (target 40-70% utilization):
apiVersion: autoscaling.aws.crossplane.io/v1alpha1
kind: AutoScalingGroup
metadata:
name: app-asg
spec:
forProvider:
minSize: 2
maxSize: 20
desiredCapacity: 5
targetTrackingConfiguration:
predefinedMetricSpecification:
predefinedMetricType: ASGAverageCPUUtilization
targetValue: 60.0
healthCheckGracePeriod: 300
cooldown: 300
Scheduled Scaling (70% savings for non-production):
apiVersion: autoscaling.aws.crossplane.io/v1alpha1
kind: ScheduledAction
metadata:
name: scale-down-after-hours
spec:
forProvider:
autoScalingGroupName: dev-asg
schedule: "0 18 * * MON-FRI"
minSize: 0
maxSize: 0
desiredCapacity: 0
---
apiVersion: autoscaling.aws.crossplane.io/v1alpha1
kind: ScheduledAction
metadata:
name: scale-up-business-hours
spec:
forProvider:
autoScalingGroupName: dev-asg
schedule: "0 8 * * MON-FRI"
minSize: 2
maxSize: 10
desiredCapacity: 3
Reserved Capacity and Savings Plans
Composition Annotations (document cost strategy):
metadata:
annotations:
cost.strategy: "mixed-spot-ondemand"
cost.spot-percentage: "70"
cost.savings-plan: "compute-savings-plan-1yr"
cost.estimated-monthly: "$1200"
cost.vs-ondemand-savings: "68%"
Modern Kubernetes Patterns
Gateway API Integration (v1 GA)
When generating Kubernetes manifests in compositions, use Gateway API instead of Ingress:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app-route
spec:
parentRefs:
- name: shared-gateway
namespace: gateway-system
rules:
- matches:
- path:
type: PathPrefix
value: /api
backendRefs:
- name: backend-service
port: 8080
weight: 80
- name: backend-service-canary
port: 8080
weight: 20
BackendTLSPolicy for mTLS:
apiVersion: gateway.networking.k8s.io/v1alpha3
kind: BackendTLSPolicy
metadata:
name: backend-tls
spec:
targetRef:
group: ''
kind: Service
name: backend-service
tls:
caCertificateRefs:
- name: backend-ca-cert
group: ''
kind: ConfigMap
hostname: backend.example.com
Native Sidecar Containers (Kubernetes 1.29+)
When compositions include Pod specs, use native sidecars:
spec:
template:
spec:
initContainers:
- name: log-forwarder
image: fluent/fluent-bit:2.1
restartPolicy: Always
startupProbe:
httpGet:
path: /api/v1/health
port: 2020
failureThreshold: 30
periodSeconds: 10
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Sidecar started"]
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 5"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
containers:
- name: main-app
image: app:v1.0
Benefits:
- Sidecars start before main containers and terminate after
- Jobs complete properly even with sidecars present
- Better resource management and termination ordering
Error Pattern Recognition
Common LLM-generated Crossplane errors (from research findings):
Factual Incorrectness (65% of technical errors)
Error: Invalid apiVersion or kind not matching provider CRDs
apiVersion: aws.crossplane.io/v1beta5
kind: RDSInstance
Fix: Validate against installed CRDs
kubectl get crds | grep rds
Contextual Reasoning Failure (47.6% of intent errors)
Error: Missing required dependencies or improper readiness checks
resources:
- name: subnet
base:
kind: Subnet
- name: instance
base:
kind: Instance
spec:
forProvider:
subnetId:
Fix: Use patches and readiness checks
resources:
- name: subnet
base:
kind: Subnet
readinessChecks:
- type: MatchString
fieldPath: status.atProvider.state
matchString: "available"
- name: instance
base:
kind: Instance
patches:
- type: FromCompositeFieldPath
fromFieldPath: status.subnet.id
toFieldPath: spec.forProvider.subnetId
Incomplete Specifications
Error: Missing required connection details or status fields
resources:
- name: database
base:
kind: RDSInstance
Fix: Expose necessary connection secrets
resources:
- name: database
connectionDetails:
- type: FromConnectionSecretKey
name: endpoint
fromConnectionSecretKey: endpoint
- type: FromConnectionSecretKey
name: password
fromConnectionSecretKey: password
- type: FromFieldPath
name: username
fromFieldPath: spec.forProvider.masterUsername
Validation Requirements
All generated Crossplane resources must:
- Pass Schema Validation:
kubectl apply --dry-run=server -f composition.yaml
- Include Required Labels: crossplane.io/xrd, provider, environment, cost-optimized
- Connection Secrets: Use proper secret propagation with RBAC
- Status Conditions: Report readiness and errors with proper condition types
- Security Scan: 0 CRITICAL/HIGH findings in Trivy/Checkov
- Hallucination Check: All resource types/attributes validated against provider schemas
- Policy Validation: Pass OPA/Rego policy checks for organizational requirements
- Cost Annotations: Document cost strategy and estimated expenses
Common Patterns
Multi-Resource Composition
For resources requiring multiple managed resources (e.g., VPC with subnets, security groups):
- Use
resources[*].name as logical identifiers
- Patch between managed resources using
FromCompositeFieldPath + ToCompositeFieldPath
- Define
readinessChecks to ensure creation order
- Use
dependsOn in function pipelines for explicit dependencies
Environment-Specific Compositions
Create separate compositions for dev/staging/prod with cost optimization:
metadata:
name: postgres-aws-dev
labels:
environment: dev
cost-optimized: "true"
annotations:
cost.strategy: "spot-instances-70-percent"
metadata:
name: postgres-aws-prod
labels:
environment: prod
cost-optimized: "false"
annotations:
cost.strategy: "reserved-instances-savings-plan"
Provider Abstraction
Create provider-agnostic XRDs that can be implemented by multiple clouds:
apiVersion: apiextensions.crossplane.io/v1
kind: CompositeResourceDefinition
metadata:
name: xdatabases.example.com
spec:
group: example.com
names:
kind: XDatabase
plural: xdatabases
versions:
- name: v1alpha1
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
parameters:
type: object
properties:
size:
type: string
enum: ["small", "medium", "large"]
costOptimized:
type: boolean
default: false
required: ["size"]
File Organization
When generating Crossplane resources, organize as:
crossplane/
├── definitions/
│ └── x{resource}.yaml # XRDs
├── compositions/
│ ├── {resource}-{provider}-{variant}.yaml
│ ├── {resource}-{provider}-cost-optimized.yaml # Spot/savings variants
│ └── ...
├── claims/
│ └── {resource}-claim.yaml # Example claims
├── provider-configs/
│ ├── aws-config.yaml # IRSA configuration
│ ├── azure-config.yaml # Managed Identity configuration
│ └── gcp-config.yaml # Workload Identity configuration
├── policies/
│ ├── opa/ # OPA/Rego policies for intent validation
│ └── .trivyignore # Documented security exceptions
├── tests/
│ └── composition-tests.yaml # Validation test cases
└── .env.example # Required secrets documentation
Progressive Disclosure
Core instructions above (~2000 tokens) cover 90% of use cases with modern patterns.
For detailed examples and advanced patterns, reference:
examples/database-composition.yaml - Full PostgreSQL RDS composition with cost optimization
examples/network-composition.yaml - Multi-resource VPC setup with Gateway API
examples/xrd-with-validation.yaml - Complex OpenAPI validation schemas
examples/cost-optimized-eks.yaml - EKS cluster with Spot node groups and interruption handling
templates/composition-template.yaml - Starter template with validation pipeline
templates/xrd-template.yaml - XRD boilerplate with security annotations
Usage Instructions
When Invoked
- Identify resource type: Database, network, compute, storage, etc.
- Determine cloud provider: AWS, Azure, GCP, or multi-cloud
- Assess cost requirements: Production (reliability) vs dev/test (cost-optimized)
- Select composition pattern: Single-resource, multi-resource, or abstraction
- Generate XRD first (if new resource type) with proper schema validation
- Generate Composition(s) implementing the XRD with validation pipeline
- Generate example Claim for testing
- Include ProviderConfig with OIDC/IRSA/Workload Identity configuration
- Run multi-phase validation:
- Technical:
kubectl apply --dry-run=server
- Intent:
opa eval + trivy config
- Hallucination check: Validate against provider schemas
- Document cost strategy in annotations
Generated Output Structure
For each resource request, generate:
- XRD (if new composite resource) with hallucination-resistant schemas
- Composition (1+ variants: standard + cost-optimized)
- Example claim for dev and production environments
- ProviderConfig with OIDC/IRSA/Workload Identity (no long-lived keys)
- OPA policies for intent validation
- .trivyignore with documented exceptions (if needed)
- .env.example documenting required secrets
- README section explaining usage, validation, and cost strategy
Quality Checks
Before completing generation:
Target metrics:
-
95% syntax validation success
-
99% hallucination detection
- 0 CRITICAL/HIGH security findings
- 0 policy violations
Boundaries
Use This Skill For:
- Generating Crossplane XRDs, Compositions, Claims
- Crossplane provider configurations with OIDC/IRSA/Workload Identity
- Multi-cloud infrastructure abstractions
- Connection secret patterns with security controls
- Crossplane RBAC configurations
- Cost-optimized composition variants (Spot instances, savings plans)
- Validation pipelines (technical + intent + security)
- Modern Kubernetes patterns (Gateway API v1, native sidecars)
Do NOT Use For:
- Raw Kubernetes manifests (unless Crossplane CRDs)
- Terraform/Pulumi/CloudFormation code (use terraform-modules or other skills)
- Helm charts (unless packaging Crossplane resources)
- Cloud provider SDKs or APIs directly
- Infrastructure not managed by Crossplane
- Ingress resources (use Gateway API v1 instead)
Integration with iac-generator
This skill is invoked by the iac-generator agent when:
- User requests Crossplane-based infrastructure
- Repository analysis identifies Crossplane as the IaC tool
- Composition pattern is needed for multi-cloud abstraction
- Cost optimization requirements specified
The iac-generator agent will:
- Call this skill for composition patterns with cost requirements
- Integrate generated resources into repository structure
- Run multi-phase validation:
- Technical:
kubectl apply --dry-run=server
- Intent: OPA policy validation
- Security: Trivy/Checkov scanning
- Hallucination: Provider schema validation
- Ensure security constraints are met (OIDC/IRSA, no hardcoded secrets)
- Document cost strategy and estimated savings
- Apply modern K8s patterns (Gateway API v1, native sidecars)
Examples
See examples/ directory for:
database-rds-composition.yaml - Complete PostgreSQL RDS setup with cost optimization
vpc-network-composition.yaml - Multi-resource networking with Gateway API v1
kubernetes-cluster-xrd.yaml - Complex XRD with validation and hallucination prevention
multi-cloud-database.yaml - Provider-agnostic abstraction with cost annotations
providerconfig-oidc.yaml - Secure authentication patterns (AWS IRSA, GCP Workload Identity)
cost-optimized-eks.yaml - EKS cluster with Spot node groups (70% cost savings)
native-sidecar-deployment.yaml - Pod spec with K8s 1.29+ native sidecars
validation-pipeline.yaml - Complete validation workflow (technical + intent)
References
For comprehensive Crossplane documentation: