API Reference¶
This section documents the public Python modules of the operator.
Operator Entry Point¶
Keycloak Operator - Main entry point for the Kopf-based Keycloak operator.
This operator provides GitOps-compatible Keycloak management with: - Multi-namespace operation (watches all namespaces by default) - Dynamic client provisioning with RBAC-based authorization - Kubernetes-native security instead of Keycloak's built-in auth - Comprehensive secret management improvements
Usage
python -m keycloak_operator.operator
Or with kopf directly:¶
kopf run keycloak_operator.operator --verbose --all-namespaces
Environment Variables
KEYCLOAK_OPERATOR_NAMESPACES: Comma-separated list of namespaces to watch KEYCLOAK_OPERATOR_LOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR) KEYCLOAK_OPERATOR_DRY_RUN: Set to 'true' for dry-run mode
_setup_coverage_signal_handler ¶
Setup SIGUSR1 signal handler to flush coverage data on demand.
This allows graceful coverage data collection during integration tests by: 1. Sending SIGUSR1 to the operator process 2. Handler calls coverage.save() to flush data to disk 3. Coverage files can then be retrieved while operator continues running
Only enabled when COVERAGE_PROCESS_START environment variable is set.
Raises:
| Type | Description |
|---|---|
ImportError
|
If coverage module is not installed when coverage is enabled |
cleanup_handler
async
¶
Operator cleanup handler.
This runs when the operator is shutting down and can be used to perform cleanup tasks like: - Closing database connections - Cleaning up temporary resources - Stopping metrics server - Logging shutdown information
configure_logging ¶
Configure structured logging for the operator based on operator_settings.
drift_detection_timer
async
¶
Periodic drift detection task.
This task runs on a timer to check for drift between Keycloak state and Kubernetes CRs. It detects: - Orphaned resources (created by operator but CR deleted) - Configuration drift (CR exists but state differs) - Unmanaged resources (exist in Keycloak without operator ownership)
get_watched_namespaces ¶
health_check
async
¶
main ¶
Main entry point for the operator.
This function: 1. Configures logging 2. Determines namespace scope 3. Configures admission webhooks (must be before kopf.run()) 4. Runs the kopf operator with appropriate settings
readiness_check
async
¶
startup_handler
async
¶
Operator startup configuration.
This handler runs once when the operator starts up and configures global operator settings including: - Resource scanning behavior - Error handling policies - Networking settings - Performance tuning - Metrics and health check endpoints - Rate limiting for Keycloak API calls - Admission webhook server
Models¶
Pydantic models for Keycloak instance resources.
This module defines type-safe data models for Keycloak instance specifications and status. These models ensure proper validation and provide IDE support for the operator development.
Keycloak ¶
Bases: BaseModel
Complete Keycloak custom resource model.
This represents the full Kubernetes custom resource including metadata, spec, and status sections.
KeycloakCondition ¶
Bases: BaseModel
Status condition for Keycloak instance.
KeycloakDatabaseConfig ¶
Bases: BaseModel
Database configuration for Keycloak instance.
Production-ready configuration that enforces external database usage. For CloudNativePG clusters, use standard PostgreSQL connection details.
validate_database_configuration ¶
Validate complete database configuration with production-ready requirements.
KeycloakEndpoints ¶
Bases: BaseModel
Endpoints for accessing Keycloak instance.
KeycloakIngressConfig ¶
Bases: BaseModel
Ingress configuration for Keycloak instance.
KeycloakInstanceRef ¶
Bases: BaseModel
Reference to a Keycloak instance in any namespace.
KeycloakResourceRequirements ¶
Bases: BaseModel
Resource requirements for Keycloak pods.
KeycloakServiceConfig ¶
Bases: BaseModel
Service configuration for Keycloak instance.
KeycloakSpec ¶
Bases: BaseModel
Specification for a Keycloak instance.
This model defines all configurable aspects of a Keycloak deployment including resources, networking, persistence, and authentication.
KeycloakStatus ¶
Bases: BaseModel
Status of a Keycloak instance.
This model represents the current state and health of a Keycloak deployment as observed by the operator.
KeycloakTLSConfig ¶
Bases: BaseModel
TLS configuration for Keycloak instance.
RealmCapacity ¶
Bases: BaseModel
Capacity management for realms.
Controls how many realms can be managed by this Keycloak operator and whether new realm creation is allowed.
SecretReference ¶
Bases: BaseModel
Reference to a secret key for sensitive data.
The secret must be in the same namespace as the resource referencing it. Cross-namespace secret references are not supported for security reasons.
Pydantic models for KeycloakRealm resources.
This module defines type-safe data models for Keycloak realm specifications and status. These models enable comprehensive realm management including authentication flows, identity providers, and user federation.
KeycloakAuthenticationFlow ¶
Bases: BaseModel
Authentication flow configuration.
KeycloakClientScope ¶
Bases: BaseModel
Client scope definition.
KeycloakEventsConfig ¶
Bases: BaseModel
Event logging configuration.
KeycloakGroup ¶
Bases: BaseModel
Group definition.
KeycloakIdentityProvider ¶
Bases: BaseModel
Identity provider configuration.
model_post_init ¶
Validate that sensitive keys are only in configSecrets, not plaintext in config.
KeycloakIdentityProviderSecretRef ¶
Bases: BaseModel
Reference to Kubernetes secret containing identity provider secrets.
The secret must be in the same namespace as the KeycloakRealm. Cross-namespace secret references are not supported for security reasons.
KeycloakProtocolMapper ¶
Bases: BaseModel
Protocol mapper for client scopes.
KeycloakRealm ¶
Bases: BaseModel
Complete KeycloakRealm custom resource model.
This represents the full Kubernetes custom resource for comprehensive realm management with authentication flows and identity providers.
KeycloakRealmCondition ¶
Bases: BaseModel
Status condition for KeycloakRealm resource.
KeycloakRealmEndpoints ¶
Bases: BaseModel
Endpoints for the KeycloakRealm.
KeycloakRealmFeatures ¶
Bases: BaseModel
Features configured for the realm.
KeycloakRealmLocalization ¶
Bases: BaseModel
Localization configuration for a realm.
KeycloakRealmRole ¶
Bases: BaseModel
Realm role definition.
KeycloakRealmSecurity ¶
Bases: BaseModel
Security settings for a realm.
KeycloakRealmSpec ¶
Bases: BaseModel
Specification for a KeycloakRealm resource.
This model defines all configurable aspects of a Keycloak realm including security, authentication, and user management settings.
KeycloakRealmStatus ¶
Bases: BaseModel
Status of a KeycloakRealm resource.
This model represents the current state of a realm as managed by the operator.
KeycloakRealmTheme ¶
Bases: BaseModel
Theme configuration for a realm.
KeycloakRealmTokenSettings ¶
Bases: BaseModel
Token settings for a realm.
KeycloakRoles ¶
Bases: BaseModel
Realm and client role definitions.
KeycloakSMTPConfig ¶
KeycloakSMTPPasswordSecret ¶
Bases: BaseModel
Reference to Kubernetes secret containing SMTP password.
The secret must be in the same namespace as the KeycloakRealm. Cross-namespace secret references are not supported for security reasons.
KeycloakUserFederation ¶
Bases: BaseModel
User federation configuration.
OperatorRef ¶
Bases: BaseModel
Reference to the operator managing this realm.
Pydantic models for KeycloakClient resources.
This module defines type-safe data models for Keycloak client specifications and status. These models enable dynamic client provisioning across namespaces with proper validation and GitOps compatibility.
KeycloakClient ¶
Bases: BaseModel
Complete KeycloakClient custom resource model.
This represents the full Kubernetes custom resource for dynamic client provisioning with cross-namespace support.
KeycloakClientAuthenticationFlow ¶
Bases: BaseModel
Configuration for client authentication flows.
KeycloakClientCondition ¶
Bases: BaseModel
Status condition for KeycloakClient resource.
KeycloakClientEndpoints ¶
Bases: BaseModel
Endpoints for the KeycloakClient.
KeycloakClientProtocolMapper ¶
Bases: BaseModel
Configuration for protocol mappers.
KeycloakClientScope ¶
Bases: BaseModel
Configuration for client scopes.
KeycloakClientSettings ¶
Bases: BaseModel
Advanced client settings.
KeycloakClientSpec ¶
Bases: BaseModel
Specification for a KeycloakClient resource.
This model defines all configurable aspects of a Keycloak client including authentication, authorization, and protocol settings.
to_keycloak_config ¶
validate_redirect_uris
classmethod
¶
Validate redirect URIs follow Keycloak wildcard rules.
Keycloak allows wildcards () in specific locations: - ✓ In path: http://localhost:3000/ or https://example.com/app/ - ✓ Custom schemes: custom: or mycustomscheme: - ✗ In domain: https://.example.com or http://example*.com - ✗ Bare wildcard: * (too permissive, blocked since Keycloak 22.x)
Wildcards can only appear at the END of the URI.
KeycloakClientStatus ¶
Bases: BaseModel
Status of a KeycloakClient resource.
This model represents the current state of a client as managed by the operator.
RealmRef ¶
Bases: BaseModel
Reference to a parent KeycloakRealm.
ServiceAccountRoles ¶
Bases: BaseModel
Role mappings for service account users.
Handlers¶
Keycloak instance handlers - Manages the core Keycloak deployment and services.
This module handles the lifecycle of Keycloak instances including: - Creating Keycloak deployments with proper configuration - Managing services and ingress for external access - Setting up persistent storage for Keycloak data - Configuring initial admin users and realms - Health monitoring and status reporting
The handlers in this module are designed to be idempotent and GitOps-friendly, ensuring that the desired state is maintained regardless of restart or failure.
StatusProtocol ¶
Bases: Protocol
Protocol for kopf Status objects that allow dynamic attribute assignment.
Wrapped by StatusWrapper to allow safe mutation irrespective of kopf internal status object semantics.
StatusWrapper ¶
Bases: MutableMapping[str, Any]
Safe mutable wrapper around kopf patch.status for both item & attribute access.
Automatically converts snake_case Python attribute names to camelCase for K8s API.
delete_keycloak_instance
async
¶
Handle Keycloak instance deletion with proper finalizer management.
This handler performs comprehensive cleanup of all associated resources and removes the finalizer only after cleanup is complete, preventing data loss and orphaned resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Keycloak resource specification |
required |
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
StatusProtocol
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
ensure_keycloak_instance
async
¶
Ensure Keycloak instance exists and is properly configured.
This is the main handler for Keycloak instance creation and resumption. It implements idempotent logic that works for both initial creation and operator restarts (resume).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Keycloak resource specification |
required |
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
StatusProtocol
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
None
|
Dictionary with status information for the resource |
monitor_keycloak_health
async
¶
Periodic health check for Keycloak instances.
This timer handler runs every 60 seconds to check the health
of Keycloak instances and update their status accordingly.
Args:
spec: Keycloak resource specification
name: Name of the Keycloak resource
namespace: Namespace where the resource exists
status: Current status of the resource
Returns:
Dictionary with updated status information, or None if no changes
Implementation includes
✅ Check if Keycloak deployment is running and ready ✅ Verify that Keycloak is responding to health checks ✅ Check resource utilization (CPU, memory, storage) ✅ Validate that Keycloak Admin API is accessible and master realm exists ✅ Update status with current health information ⚠️ Generate events for significant status changes - Future enhancement ⚠️ Implement alerting for persistent failures - Future enhancement
update_keycloak_instance
async
¶
Handle updates to Keycloak instance specifications.
This handler is called when the Keycloak resource specification changes. It delegates to the reconciler service layer for all business logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old
|
dict[str, Any]
|
Previous specification |
required |
new
|
dict[str, Any]
|
New specification |
required |
diff
|
Diff
|
List of changes between old and new |
required |
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
StatusProtocol
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
None to avoid Kopf creating status subpaths |
KeycloakRealm handlers - Manages realm lifecycle and configuration.
This module handles realm management within Keycloak instances, including: - Creating and configuring realms - Setting up authentication flows and identity providers - Managing realm-level settings and policies - Configuring user federation and storage - Setting up realm-specific themes and localization
Realms provide isolation between different applications or tenants and can be managed independently across different namespaces.
StatusProtocol ¶
StatusWrapper ¶
Wrapper to make kopf patch.status compatible with StatusProtocol.
This wrapper provides both attribute and dict-like access to patch.status, ensuring all updates are written directly to the underlying patch object.
Automatically converts snake_case Python attribute names to camelCase for K8s API.
_test_user_federation
async
¶
Test user federation connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
admin_client
|
Any
|
Keycloak admin client |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Namespace for rate limiting |
required |
federation_specs
|
list
|
List of user federation specifications |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if federation is healthy, False otherwise |
_verify_authentication_flows
async
¶
Verify that authentication flows exist and are configured correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
admin_client
|
Any
|
Keycloak admin client |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Namespace for rate limiting |
required |
flow_specs
|
list
|
List of expected authentication flow specifications |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if flows are valid, False otherwise |
_verify_identity_providers
async
¶
Verify that identity providers exist and are configured correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
admin_client
|
Any
|
Keycloak admin client |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Namespace for rate limiting |
required |
idp_specs
|
list
|
List of expected identity provider specifications |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if identity providers are valid, False otherwise |
_verify_realm_config ¶
Verify that the current realm configuration matches the spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_realm
|
dict[str, Any]
|
Current realm configuration from Keycloak |
required |
realm_spec
|
KeycloakRealmSpec
|
Desired realm specification |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if configuration matches, False otherwise |
delete_keycloak_realm
async
¶
Handle KeycloakRealm deletion with proper finalizer management.
This handler performs comprehensive cleanup of the realm from Keycloak and any associated Kubernetes resources, removing the finalizer only after cleanup is complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakRealm resource specification |
required |
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
ensure_keycloak_realm
async
¶
Ensure KeycloakRealm exists in the target Keycloak instance.
This handler creates and configures realms in Keycloak instances. Realms can be created in Keycloak instances across namespaces, subject to RBAC permissions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakRealm resource specification |
required |
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace where the KeycloakRealm resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
None
|
Dictionary with status information for the resource |
monitor_realm_health
async
¶
Periodic health check for KeycloakRealms.
This timer verifies that realms still exist in Keycloak and that their configuration matches the desired state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakRealm resource specification |
required |
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
update_keycloak_realm
async
¶
Handle updates to KeycloakRealm specifications.
This handler processes changes to realm configurations and applies them to the target Keycloak instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old
|
dict[str, Any]
|
Previous specification |
required |
new
|
dict[str, Any]
|
New specification |
required |
diff
|
Diff
|
List of changes |
required |
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
None to avoid Kopf creating status subpaths |
KeycloakClient handlers - Manages dynamic client provisioning across namespaces.
This module implements the core feature of dynamic client provisioning that enables GitOps-compatible client management. Key features:
- Cross-namespace client creation: Clients can reference Keycloak instances in different namespaces (subject to RBAC permissions)
- RBAC-based authorization: Uses Kubernetes RBAC instead of Keycloak's built-in security mechanisms
- Secure secret management: Client credentials stored in Kubernetes secrets with proper access controls
- GitOps compatibility: All client configuration is declarative
The handlers support various client types including: - Public clients (SPAs, mobile apps) - Confidential clients (backend services) - Service accounts for machine-to-machine communication
StatusWrapper ¶
Wrapper to make kopf patch.status compatible with StatusProtocol.
This wrapper provides both attribute and dict-like access to patch.status, ensuring all updates are written directly to the underlying patch object.
Automatically converts snake_case Python attribute names to camelCase for K8s API.
delete_keycloak_client
async
¶
Handle KeycloakClient deletion with proper finalizer management.
This handler performs comprehensive cleanup of the client from Keycloak and any associated Kubernetes resources, removing the finalizer only after cleanup is complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakClient resource specification |
required |
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
ensure_keycloak_client
async
¶
Ensure KeycloakClient exists in the target Keycloak instance.
This handler implements dynamic client provisioning across namespaces. It can create clients in Keycloak instances located in any namespace, subject to RBAC permissions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakClient resource specification |
required |
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace where the KeycloakClient resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
None
|
Dictionary with status information for the resource |
monitor_client_health
async
¶
Periodic health check for KeycloakClients.
This timer verifies that clients still exist in Keycloak and that their configuration matches the desired state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
KeycloakClient resource specification |
required |
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
Returns:
| Type | Description |
|---|---|
None
|
Dictionary with updated status, or None if no changes needed |
update_keycloak_client
async
¶
Handle updates to KeycloakClient specifications.
This handler processes changes to client configurations and applies them to the target Keycloak instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old
|
dict[str, Any]
|
Previous specification |
required |
new
|
dict[str, Any]
|
New specification |
required |
diff
|
Diff
|
List of changes |
required |
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
dict[str, Any]
|
Current status of the resource |
required |
patch
|
Patch
|
Kopf patch object for modifying the resource |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
None to avoid Kopf creating status subpaths |
Services¶
Keycloak instance reconciler for managing core Keycloak deployments.
This module handles the lifecycle of Keycloak instances including deployment, services, persistence, and administrative access.
KeycloakInstanceReconciler ¶
Bases: BaseReconciler
Reconciler for Keycloak instance resources.
Manages the complete lifecycle of Keycloak instances including: - Kubernetes deployment and scaling - Service and ingress configuration - Persistent storage setup - Admin user initialization - Production environment validation
Initialize Keycloak instance reconciler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k8s_client
|
ApiClient | None
|
Kubernetes API client |
None
|
keycloak_admin_factory
|
Any
|
Factory function for creating Keycloak admin clients |
None
|
rate_limiter
|
Any
|
Rate limiter for Keycloak API calls |
None
|
_create_backup
async
¶
Create a backup of Keycloak data before deletion.
_delete_configuration_resources
async
¶
Delete secrets and configmaps associated with the Keycloak instance.
_delete_dependent_resources
async
¶
Delete all CRD resources that depend on this Keycloak instance.
This implements cascading deletion by finding and deleting: 1. KeycloakClients that reference this Keycloak instance 2. KeycloakRealms that reference this Keycloak instance
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keycloak_name
|
str
|
Name of the Keycloak instance being deleted |
required |
keycloak_namespace
|
str
|
Namespace of the Keycloak instance |
required |
_delete_deployment
async
¶
Delete deployment and wait for pods to terminate.
_delete_ingress
async
¶
Delete ingress resource.
_delete_persistent_storage
async
¶
Delete persistent volume claims associated with the Keycloak instance.
_store_keycloak_backup_in_secret
async
¶
_update_capacity_status
async
¶
Update realm capacity status fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status
|
StatusProtocol
|
Status object to update |
required |
spec
|
KeycloakSpec
|
Keycloak specification |
required |
namespace
|
str
|
Keycloak namespace |
required |
_update_deployment
async
¶
Update deployment with changes.
_update_ingress
async
¶
Update ingress configuration.
_validate_database_connectivity
async
¶
Validate database connectivity using the new database connection manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with resolved database connection details |
Raises:
| Type | Description |
|---|---|
ExternalServiceError
|
If database connectivity validation fails |
_validate_database_production_readiness
async
¶
Validate database configuration for production readiness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
namespace
|
str
|
Resource namespace |
required |
Raises:
| Type | Description |
|---|---|
DatabaseValidationError
|
If database configuration is not production-ready |
_validate_database_secret
async
¶
Validate that database credentials secret exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
namespace
|
str
|
Resource namespace |
required |
Raises:
| Type | Description |
|---|---|
ExternalServiceError
|
If database secret is missing or invalid |
_validate_security_requirements
async
¶
Validate security requirements for production deployments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
namespace
|
str
|
Resource namespace |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If security requirements are not met |
_validate_spec ¶
Validate and parse Keycloak specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Raw specification dictionary |
required |
Returns:
| Type | Description |
|---|---|
KeycloakSpec
|
Validated KeycloakSpec object |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If specification is invalid |
_wait_for_rollout
async
¶
Wait for deployment rollout to complete.
cleanup_resources
async
¶
Clean up all resources associated with a Keycloak instance.
This method performs comprehensive cleanup in the proper order to prevent data loss and ensure all associated resources are properly removed.
Implements cascading deletion: 1. Delete dependent KeycloakClients 2. Delete dependent KeycloakRealms 3. Delete Kubernetes resources (deployments, services, etc.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak instance |
required |
namespace
|
str
|
Namespace containing the resources |
required |
spec
|
dict[str, Any]
|
Keycloak specification for understanding deletion requirements |
required |
Raises:
| Type | Description |
|---|---|
TemporaryError
|
If cleanup fails but should be retried |
do_reconcile
async
¶
Reconcile Keycloak instance to desired state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Keycloak resource specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
status
|
StatusProtocol
|
Resource status object |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Status dictionary for the resource |
do_update
async
¶
Handle updates to Keycloak instance specifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_spec
|
dict[str, Any]
|
Previous specification |
required |
new_spec
|
dict[str, Any]
|
New specification |
required |
diff
|
Any
|
List of changes between old and new |
required |
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Namespace where the resource exists |
required |
status
|
StatusProtocol
|
Current status of the resource |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Dictionary with updated status information, or None if no changes needed |
ensure_admin_access
async
¶
Ensure admin user is configured and accessible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
ensure_deployment
async
¶
Ensure Keycloak deployment exists and is up to date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
db_connection_info
|
dict[str, Any] | None
|
Optional resolved database connection details |
None
|
ensure_ingress
async
¶
Ensure ingress is configured for external access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
ensure_service
async
¶
Ensure Keycloak service exists and is properly configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
validate_production_settings
async
¶
Validate configuration for production readiness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakSpec
|
Keycloak specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Dictionary with resolved database connection details, or None if database not configured |
Raises:
| Type | Description |
|---|---|
DatabaseValidationError
|
If using H2 database inappropriately |
ValidationError
|
If other production requirements not met |
wait_for_deployment_ready
async
¶
Keycloak realm reconciler for managing realm configuration and features.
This module handles the lifecycle of Keycloak realms including themes, authentication flows, identity providers, and user federation.
KeycloakRealmReconciler ¶
Bases: BaseReconciler
Reconciler for Keycloak realm resources.
Manages the complete configuration of Keycloak realms including: - Basic realm creation and settings - Theme and branding configuration - Authentication flows and security - Identity provider integration - User federation setup - Cross-namespace RBAC validation
Initialize Keycloak realm reconciler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k8s_client
|
ApiClient | None
|
Kubernetes API client |
None
|
keycloak_admin_factory
|
Any
|
Factory function for creating Keycloak admin clients |
None
|
rate_limiter
|
Any
|
Rate limiter for Keycloak API calls |
None
|
_check_realm_capacity
async
¶
Check if Keycloak operator has capacity for new realms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keycloak_namespace
|
str
|
Namespace containing the Keycloak instance |
required |
keycloak_name
|
str
|
Name of the Keycloak instance |
required |
realm_name
|
str
|
Name of the realm being created |
required |
Raises:
| Type | Description |
|---|---|
PermanentError
|
If capacity is exhausted and new realms are not allowed |
_create_realm_backup
async
¶
Create a backup of realm data before deletion.
_delete_realm_k8s_resources
async
¶
Delete Kubernetes resources associated with the realm.
_fetch_secret_value
async
¶
Fetch secret value from Kubernetes secret with RBAC validation.
This method enforces namespace access control and secret labeling requirements. The secret must: 1. Be accessible via RoleBinding granting operator access to the namespace 2. Have the label: vriesdemichael.github.io/keycloak-allow-operator-read=true
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Namespace containing the secret |
required |
secret_name
|
str
|
Name of the secret |
required |
secret_key
|
str
|
Key in secret data |
required |
Returns:
| Type | Description |
|---|---|
str
|
Decoded secret value string |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If RBAC validation fails, secret not found, or key missing |
_store_backup_in_secret
async
¶
_validate_spec ¶
Validate and parse Keycloak realm specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Raw specification dictionary |
required |
Returns:
| Type | Description |
|---|---|
KeycloakRealmSpec
|
Validated KeycloakRealmSpec object |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If specification is invalid |
check_resource_exists
async
¶
Check if realm resource actually exists in Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace containing the resource |
required |
spec
|
dict[str, Any]
|
Realm specification |
required |
status
|
StatusProtocol
|
Resource status |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if realm exists in Keycloak, False otherwise |
cleanup_resources
async
¶
Clean up realm from Keycloak and associated Kubernetes resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the KeycloakRealm resource |
required |
namespace
|
str
|
Namespace containing the resource |
required |
spec
|
dict[str, Any]
|
Realm specification |
required |
status
|
StatusProtocol
|
Resource status for tracking cleanup progress |
required |
Raises:
| Type | Description |
|---|---|
TemporaryError
|
If cleanup fails but should be retried |
configure_authentication
async
¶
Configure authentication flows and security settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
configure_identity_providers
async
¶
Configure external identity providers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
configure_themes
async
¶
Configure themes and branding for the realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
configure_user_federation
async
¶
Configure user federation (LDAP, Active Directory, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
do_reconcile
async
¶
Reconcile Keycloak realm to desired state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Keycloak realm resource specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
status
|
StatusProtocol
|
Resource status object |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Status dictionary for the resource |
do_update
async
¶
Handle updates to Keycloak realm specifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_spec
|
dict[str, Any]
|
Previous specification dictionary |
required |
new_spec
|
dict[str, Any]
|
New specification dictionary |
required |
diff
|
Any
|
List of changes between old and new specs |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
status
|
StatusProtocol
|
Resource status object |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Updated status dictionary or None if no changes needed |
ensure_realm_exists
async
¶
Ensure the basic realm exists in Keycloak with ownership tracking.
This method implements ownership tracking to prevent multiple CRs from managing the same realm and to handle orphaned realms properly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
**kwargs
|
Any
|
Additional handler arguments (uid, meta, etc.) |
{}
|
manage_realm_backup
async
¶
Manage realm backup operations based on spec configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
validate_cross_namespace_access
async
¶
Validate RBAC permissions for cross-namespace operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakRealmSpec
|
Keycloak realm specification |
required |
namespace
|
str
|
Current namespace |
required |
Raises:
| Type | Description |
|---|---|
RBACError
|
If insufficient permissions for cross-namespace access |
Keycloak client reconciler for managing OAuth2/OIDC client configuration.
This module handles the lifecycle of Keycloak clients including client creation, credential management, and OAuth2 configuration.
KeycloakClientReconciler ¶
Bases: BaseReconciler
Reconciler for Keycloak client resources.
Manages the complete lifecycle of OAuth2/OIDC clients including: - Client creation and basic configuration - OAuth2/OIDC parameter setup - Credential generation and rotation - Protocol mapper configuration - Client role management - Cross-namespace RBAC validation
Initialize Keycloak client reconciler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k8s_client
|
ApiClient | None
|
Kubernetes API client |
None
|
keycloak_admin_factory
|
Any
|
Factory function for creating Keycloak admin clients |
None
|
rate_limiter
|
Any
|
Rate limiter for Keycloak API calls |
None
|
_client_role_needs_update ¶
_delete_client_k8s_resources
async
¶
Delete Kubernetes resources associated with the client.
_get_keycloak_instance_from_realm ¶
Get Keycloak instance name and namespace from a realm's status.
DEPRECATED: Use _get_realm_info instead for new code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_resource_name
|
str
|
Name of the realm resource |
required |
realm_namespace
|
str
|
Namespace of the realm resource |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
Tuple of (keycloak_namespace, keycloak_name) |
_get_realm_info ¶
Get realm information including actual realm name and Keycloak instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_resource_name
|
str
|
Name of the realm Kubernetes resource |
required |
realm_namespace
|
str
|
Namespace of the realm resource |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str, str, str]
|
Tuple of (actual_realm_name, keycloak_namespace, keycloak_name, realm_resource_name) |
Raises:
| Type | Description |
|---|---|
ApiException
|
If realm resource cannot be retrieved |
PermanentError
|
If realm spec is invalid |
_protocol_mapper_needs_update ¶
Check if a protocol mapper needs to be updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
existing
|
dict[str, Any]
|
Existing protocol mapper from Keycloak |
required |
desired
|
dict[str, Any]
|
Desired protocol mapper configuration |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if update is needed, False otherwise |
_validate_namespace_authorization
async
¶
_validate_namespace_authorization(
realm_resource,
realm_name,
realm_namespace,
client_namespace,
client_id,
)
Validate that client's namespace is authorized via realm's grant list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_resource
|
dict[str, Any]
|
The KeycloakRealm custom resource |
required |
realm_name
|
str
|
Name of the realm |
required |
realm_namespace
|
str
|
Namespace of the realm |
required |
client_namespace
|
str
|
Namespace of the client |
required |
client_id
|
str
|
ID of the client |
required |
Raises:
| Type | Description |
|---|---|
PermanentError
|
If namespace is not in grant list |
_validate_spec ¶
Validate and parse Keycloak client specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Raw specification dictionary |
required |
Returns:
| Type | Description |
|---|---|
KeycloakClientSpec
|
Validated KeycloakClientSpec object |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If specification is invalid |
check_resource_exists
async
¶
Check if client resource actually exists in Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace containing the resource |
required |
spec
|
dict[str, Any]
|
Client specification |
required |
status
|
StatusProtocol
|
Resource status |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if client exists in Keycloak, False otherwise |
cleanup_resources
async
¶
Clean up client from Keycloak and associated Kubernetes resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the KeycloakClient resource |
required |
namespace
|
str
|
Namespace containing the resource |
required |
spec
|
dict[str, Any]
|
Client specification |
required |
status
|
StatusProtocol
|
Resource status for tracking cleanup progress |
required |
Raises:
| Type | Description |
|---|---|
TemporaryError
|
If cleanup fails but should be retried |
configure_oauth_settings
async
¶
Configure OAuth2/OIDC parameters for the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
client_uuid
|
str
|
Client UUID in Keycloak |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
configure_protocol_mappers
async
¶
Configure protocol mappers for claims and token customization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
client_uuid
|
str
|
Client UUID in Keycloak |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
do_reconcile
async
¶
Reconcile Keycloak client to desired state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Keycloak client resource specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
status
|
StatusProtocol
|
Resource status object |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Status dictionary for the resource |
do_update
async
¶
Handle updates to Keycloak client specifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_spec
|
dict[str, Any]
|
Previous specification dictionary |
required |
new_spec
|
dict[str, Any]
|
New specification dictionary |
required |
diff
|
Any
|
List of changes between old and new specs |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
status
|
StatusProtocol
|
Resource status object |
required |
**kwargs
|
Any
|
Additional handler arguments |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Updated status dictionary or None if no changes needed |
ensure_client_exists
async
¶
Ensure the OAuth2/OIDC client exists in Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
Returns:
| Type | Description |
|---|---|
str
|
Client UUID from Keycloak |
manage_client_credentials
async
¶
Generate and manage client credentials (secret).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
client_uuid
|
str
|
Client UUID in Keycloak |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
manage_client_roles
async
¶
Manage client-specific roles and permissions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
client_uuid
|
str
|
Client UUID in Keycloak |
required |
name
|
str
|
Resource name |
required |
namespace
|
str
|
Resource namespace |
required |
manage_service_account_roles
async
¶
Manage role mappings for the client's service account user.
validate_cross_namespace_access
async
¶
Validate RBAC permissions for cross-namespace operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
KeycloakClientSpec
|
Keycloak client specification |
required |
namespace
|
str
|
Current namespace |
required |
Raises:
| Type | Description |
|---|---|
RBACError
|
If insufficient permissions for cross-namespace access |
Utilities¶
Kubernetes utilities for the Keycloak operator.
This module provides helper functions for interacting with the Kubernetes API, including resource management, RBAC validation, and cluster operations.
Key functionality: - Kubernetes client management and configuration - Resource creation and management (deployments, services, secrets) - RBAC permission validation - Cross-namespace resource discovery - Status and health monitoring
backup_keycloak_data ¶
Create a Kubernetes Job to backup Keycloak data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Target namespace |
required |
spec
|
Any
|
Keycloak specification |
required |
k8s_client
|
ApiClient
|
Kubernetes API client |
required |
Returns:
| Type | Description |
|---|---|
V1Job
|
Created Job object |
check_http_health
async
¶
check_rbac_permissions ¶
check_rbac_permissions(
namespace,
target_namespace,
resource="keycloaks",
verb="get",
api_group=None,
)
Check if the current service account has RBAC permissions for cross-namespace access.
This function performs a Kubernetes SubjectAccessReview to validate that the operator has the necessary permissions to access resources in other namespaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Source namespace (where the request originates) |
required |
target_namespace
|
str
|
Target namespace to access |
required |
resource
|
str
|
Kubernetes resource type to check |
'keycloaks'
|
verb
|
str
|
Action to perform (get, create, update, delete, etc.) |
'get'
|
api_group
|
str | None
|
API group for the resource (None for auto-detection) |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if permission is granted, False otherwise |
create_admin_secret ¶
Create a secret containing Keycloak admin credentials.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak instance |
required |
namespace
|
str
|
Target namespace |
required |
username
|
str
|
Admin username |
'admin'
|
password
|
str | None
|
Admin password (generated if not provided) |
None
|
Returns:
| Type | Description |
|---|---|
V1Secret
|
Created Secret object |
Creates a secret with admin credentials, generating secure passwords when needed. Sets proper labels and ownership for the secret.
create_client_secret ¶
create_client_secret(
secret_name,
namespace,
client_id,
client_secret,
keycloak_url,
realm,
update_existing=False,
)
Create or update a Kubernetes secret containing client credentials.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret_name
|
str
|
Name of the secret to create |
required |
namespace
|
str
|
Target namespace |
required |
client_id
|
str
|
Keycloak client ID |
required |
client_secret
|
str | None
|
Client secret (None for public clients) |
required |
keycloak_url
|
str
|
Keycloak server URL |
required |
realm
|
str
|
Realm name |
required |
update_existing
|
bool
|
Whether to update if secret already exists |
False
|
Returns:
| Type | Description |
|---|---|
V1Secret
|
Created or updated Secret object |
Creates a Kubernetes secret containing client credentials and connection info. Handles both creation and updates with proper encoding and metadata.
create_keycloak_deployment ¶
Create Kubernetes Deployment for a Keycloak instance.
Args:
name: Name of the Keycloak resource
namespace: Target namespace
spec: Keycloak specification
k8s_client: Kubernetes API client
db_connection_info: Optional resolved database connection details (for CNPG)
Returns:
Created Deployment object
This function creates a complete Keycloak deployment with proper configuration.
create_keycloak_ingress ¶
Create Kubernetes Ingress for a Keycloak instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Target namespace |
required |
spec
|
Any
|
Keycloak specification |
required |
k8s_client
|
ApiClient
|
Kubernetes API client |
required |
Returns:
| Type | Description |
|---|---|
V1Ingress
|
Created Ingress object |
create_keycloak_service ¶
Create Kubernetes Service for a Keycloak instance.
Args:
name: Name of the Keycloak resource
namespace: Target namespace
spec: Keycloak specification
k8s_client: Kubernetes API client
Returns:
Created Service object
This function creates a Kubernetes service with proper port configuration and selectors.
create_persistent_volume_claim ¶
Create a PersistentVolumeClaim for Keycloak data storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak instance |
required |
namespace
|
str
|
Target namespace |
required |
size
|
str
|
Storage size (e.g., "10Gi") |
'10Gi'
|
storage_class
|
str | None
|
Storage class name (optional) |
None
|
Returns:
| Type | Description |
|---|---|
V1PersistentVolumeClaim
|
Created PersistentVolumeClaim object |
find_keycloak_instances ¶
Find Keycloak instances across namespaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str | None
|
Specific namespace to search, or None for cluster-wide |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of Keycloak instance dictionaries |
Searches for Keycloak custom resources and returns instances with status information. Handles API errors gracefully and supports both namespace-specific and cluster-wide searches.
get_admin_credentials ¶
Get admin credentials for a Keycloak instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak instance |
required |
namespace
|
str
|
Namespace where the instance is deployed |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
Tuple of (username, password) |
Raises:
| Type | Description |
|---|---|
Exception
|
If credentials cannot be retrieved |
get_current_service_account_info ¶
get_kubernetes_client ¶
Get configured Kubernetes API client.
This function handles both in-cluster and local development configurations.
Returns:
Configured Kubernetes API client
This function handles both in-cluster and local development configurations.
get_pod_resource_usage ¶
Get resource usage metrics for Keycloak pods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Target namespace |
required |
k8s_client
|
ApiClient
|
Kubernetes API client |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with resource usage information |
set_owner_reference ¶
set_owner_reference(
resource,
owner_name,
owner_uid,
owner_kind="Keycloak",
api_version="vriesdemichael.github.io/v1",
)
Set owner reference for garbage collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource
|
Any
|
Kubernetes resource to set owner reference on |
required |
owner_name
|
str
|
Name of the owner resource |
required |
owner_uid
|
str
|
UID of the owner resource |
required |
owner_kind
|
str
|
Kind of the owner resource |
'Keycloak'
|
api_version
|
str
|
API version of the owner resource |
'vriesdemichael.github.io/v1'
|
validate_keycloak_reference ¶
Validate that a Keycloak instance reference is valid and ready.
Args:
keycloak_name: Name of the Keycloak instance
namespace: Namespace where the instance should exist
Returns:
Keycloak instance details if valid and ready, None otherwise
This function validates Keycloak instance readiness and availability.
Keycloak Admin API client utilities.
This module provides a high-level interface to the Keycloak Admin REST API for managing Keycloak instances, realms, clients, and other resources.
The client handles: - Authentication with Keycloak admin credentials - Session management and token refresh - Error handling and retry logic - Type-safe API interactions - Rate limiting for API protection
KeycloakAdminClient ¶
KeycloakAdminClient(
server_url,
username,
password,
realm="master",
client_id="admin-cli",
verify_ssl=True,
timeout=60,
rate_limiter=None,
)
High-level client for Keycloak Admin API operations.
This client provides methods for managing Keycloak resources including
realms, clients, users, and configuration. It handles authentication,
session management, and provides a clean interface for the operator.
This client provides comprehensive Keycloak Admin API operations with authentication, error handling, and retry logic.
Initialize Keycloak Admin client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_url
|
str
|
Base URL of the Keycloak server |
required |
username
|
str
|
Admin username |
required |
password
|
str
|
Admin password |
required |
realm
|
str
|
Admin realm (default: master) |
'master'
|
client_id
|
str
|
Client ID for admin API access |
'admin-cli'
|
verify_ssl
|
bool
|
Whether to verify SSL certificates |
True
|
timeout
|
int
|
Request timeout in seconds |
60
|
rate_limiter
|
RateLimiter | None
|
Optional rate limiter for API call throttling |
None
|
__aexit__
async
¶
Async context manager exit - ensures session cleanup.
_ensure_authenticated
async
¶
Ensure we have a valid access token, refreshing if necessary.
_get_client
async
¶
Get or create httpx client (lazy initialization with caching).
The client is cached per (server_url, verify_ssl) combination. We also track the event loop ID to detect when a cached client was created in a different event loop (which can happen in tests).
_make_request
async
¶
Make an authenticated request to the Keycloak Admin API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method (GET, POST, PUT, DELETE) |
required |
endpoint
|
str
|
API endpoint (relative to admin base) |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
data
|
dict[str, Any] | None
|
Request body data (deprecated, use json parameter) |
None
|
json
|
dict[str, Any] | None
|
JSON request body data |
None
|
params
|
dict[str, Any] | None
|
Query parameters |
None
|
Returns:
| Type | Description |
|---|---|
Response
|
Response object (httpx.Response) with body already buffered |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
On API errors or rate limit timeouts |
_make_validated_request
async
¶
_make_validated_request(
method,
endpoint,
namespace,
request_model=None,
response_model=None,
**kwargs
)
Make an authenticated request with automatic Pydantic validation.
This method wraps _make_request to provide automatic validation of request and response data using Pydantic models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method (GET, POST, PUT, DELETE) |
required |
endpoint
|
str
|
API endpoint (relative to admin base) |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
request_model
|
BaseModel | None
|
Pydantic model instance to serialize as request body |
None
|
response_model
|
type[BaseModel] | None
|
Pydantic model class to validate response data |
None
|
**kwargs
|
Any
|
Additional arguments passed to _make_request |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Validated response model instance if response_model is provided, |
Any
|
otherwise the raw Response object |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If the API request fails |
ValidationError
|
If response data doesn't match the expected model |
assign_client_roles_to_user
async
¶
Assign client-level roles to a user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
UUID of the user in Keycloak |
required |
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
role_names
|
list[str]
|
List of role names to assign |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If assignment fails |
Example
await admin_client.assign_client_roles_to_user( user_id="123-456-789", client_uuid="abc-def-ghi", role_names=["admin", "user"], realm_name="my-realm", namespace="default" )
assign_realm_roles_to_user
async
¶
Assign realm-level roles to a user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
UUID of the user in Keycloak |
required |
role_names
|
list[str]
|
List of role names to assign |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If assignment fails |
Example
await admin_client.assign_realm_roles_to_user( user_id="123-456-789", role_names=["admin", "user"], realm_name="my-realm", namespace="default" )
authenticate
async
¶
Authenticate with Keycloak and obtain access tokens.
Uses username/password grant to obtain access and refresh tokens.
backup_realm
async
¶
close
async
¶
Close method for compatibility with async context manager.
Note: With the caching strategy, we don't actually close the httpx client here as it's shared across multiple KeycloakAdminClient instances. The cached client will be reused until the operator shuts down.
configure_authentication_flow
async
¶
Configure authentication flow for a realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm |
required |
flow_config
|
AuthenticationFlowRepresentation | dict[str, Any]
|
Authentication flow configuration as AuthenticationFlowRepresentation or dict |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
from keycloak_operator.models.keycloak_api import AuthenticationFlowRepresentation
flow = AuthenticationFlowRepresentation( alias="browser-custom", description="Custom browser flow" ) success = admin_client.configure_authentication_flow("my-realm", flow)
configure_identity_provider
async
¶
Configure identity provider for a realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm |
required |
provider_config
|
IdentityProviderRepresentation | dict[str, Any]
|
Identity provider configuration as IdentityProviderRepresentation or dict |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
from keycloak_operator.models.keycloak_api import IdentityProviderRepresentation
provider = IdentityProviderRepresentation( alias="google", provider_id="google", enabled=True ) success = await admin_client.configure_identity_provider("my-realm", provider, "my-namespace")
configure_user_federation
async
¶
Configure user federation for a realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm |
required |
federation_config
|
ComponentRepresentation | dict[str, Any]
|
User federation configuration as ComponentRepresentation or dict |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
from keycloak_operator.models.keycloak_api import ComponentRepresentation
federation = ComponentRepresentation( name="ldap", provider_id="ldap" ) success = admin_client.configure_user_federation("my-realm", federation)
create_client
async
¶
Create a new client in the specified realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_config
|
ClientRepresentation | dict[str, Any]
|
Client configuration as ClientRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Client UUID if successful, None otherwise |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If client creation fails |
create_client_protocol_mapper
async
¶
Create a protocol mapper for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
mapper_config
|
ProtocolMapperRepresentation | dict[str, Any]
|
Protocol mapper configuration as ProtocolMapperRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
ProtocolMapperRepresentation | None
|
Created mapper configuration as ProtocolMapperRepresentation or None on error |
Example
from keycloak_operator.models.keycloak_api import ProtocolMapperRepresentation
mapper = ProtocolMapperRepresentation( name="email", protocol="openid-connect", protocol_mapper="oidc-usermodel-property-mapper" ) created = admin_client.create_client_protocol_mapper( client_uuid, mapper, "my-realm" )
create_client_role
async
¶
Create a role for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
role_config
|
RoleRepresentation | dict[str, Any]
|
Role configuration as RoleRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
from keycloak_operator.models.keycloak_api import RoleRepresentation
role = RoleRepresentation( name="admin", description="Administrator role" ) success = admin_client.create_client_role(client_uuid, role, "my-realm")
create_realm
async
¶
Create a new realm in Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_config
|
RealmRepresentation | dict[str, Any]
|
Realm configuration as RealmRepresentation or dict |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RealmRepresentation
|
Created realm information as RealmRepresentation |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If realm creation fails |
delete_client
async
¶
delete_client_protocol_mapper
async
¶
delete_client_role
async
¶
delete_realm
async
¶
export_realm
async
¶
Export realm configuration from Keycloak.
Based on OpenAPI spec: GET /admin/realms/{realm} Returns the complete realm representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm to export |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RealmRepresentation | None
|
Complete realm configuration as RealmRepresentation or None if not found |
Example
realm = await client.export_realm("my-realm", "default") if realm: print(f"Realm {realm.realm} has {len(realm.clients or [])} clients")
get_client_by_name
async
¶
Get a client by its client ID in the specified realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The client ID to search for |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
ClientRepresentation | None
|
Client data as ClientRepresentation if found, None otherwise |
Example
client = await admin_client.get_client_by_name("my-client", "my-realm", "default") if client: print(f"Client UUID: {client.id}, Enabled: {client.enabled}")
get_client_protocol_mappers
async
¶
Get all protocol mappers for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
list[ProtocolMapperRepresentation] | None
|
List of protocol mapper configurations as ProtocolMapperRepresentation or None on error |
Example
mappers = admin_client.get_client_protocol_mappers(client_uuid, "my-realm") for mapper in mappers: print(f"Mapper: {mapper.name}, Protocol: {mapper.protocol}")
get_client_role
async
¶
Get a client role by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
role_name
|
str
|
Name of the role to retrieve |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RoleRepresentation | None
|
Role representation as RoleRepresentation or None if not found |
Example
role = await admin_client.get_client_role(client_uuid, "admin", "my-realm", "default") if role: print(f"Client role: {role.name}, ID: {role.id}")
get_client_roles
async
¶
Get all roles for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
list[RoleRepresentation] | None
|
List of client role configurations as RoleRepresentation or None on error |
Example
roles = admin_client.get_client_roles(client_uuid, "my-realm") for role in roles: print(f"Role: {role.name}, ID: {role.id}")
get_client_secret
async
¶
get_client_uuid
async
¶
Get client UUID by client ID in the specified realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The client ID to search for |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Client UUID if found, None otherwise |
get_realm
async
¶
Get realm configuration from Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm to retrieve |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RealmRepresentation | None
|
Realm configuration as RealmRepresentation or None if not found |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If the request fails (except 404) |
get_realm_clients
async
¶
Get all clients in a realm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm |
required |
Returns:
| Type | Description |
|---|---|
list[ClientRepresentation]
|
List of client configurations as ClientRepresentation |
Example
clients = admin_client.get_realm_clients("my-realm") for client in clients: print(f"Client: {client.client_id}, Enabled: {client.enabled}")
get_realm_role
async
¶
Get a realm role by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_name
|
str
|
Name of the role to retrieve |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RoleRepresentation | None
|
Role representation as RoleRepresentation or None if not found |
Example
role = await admin_client.get_realm_role("admin", "my-realm", "default") if role: print(f"Role: {role.name}, ID: {role.id}")
get_realms
async
¶
Get all accessible realms from Keycloak.
Based on OpenAPI spec: GET /admin/realms Returns a list of accessible realms filtered by what the caller is allowed to view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Origin namespace for rate limiting |
required |
brief_representation
|
bool
|
If True, return brief representation of realms |
False
|
Returns:
| Type | Description |
|---|---|
list[RealmRepresentation] | None
|
List of realm configurations as RealmRepresentation or None on error |
Example
realms = await client.get_realms("default") for realm in realms: print(f"Realm: {realm.realm}, Enabled: {realm.enabled}")
get_service_account_user
async
¶
Get the service account user for a client.
Based on OpenAPI spec: GET /admin/realms/{realm}/clients/{id}/service-account-user
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
Client UUID in Keycloak |
required |
realm_name
|
str
|
Target realm name |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
UserRepresentation
|
Service account user representation as UserRepresentation |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If retrieval fails or service account is disabled |
Example
user = await admin_client.get_service_account_user(client_uuid, "my-realm", "default") print(f"Service account user: {user.username}, ID: {user.id}")
regenerate_client_secret
async
¶
update_client
async
¶
Update an existing client configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
The UUID of the client to update |
required |
client_config
|
ClientRepresentation | dict[str, Any]
|
Updated client configuration as ClientRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If client update fails |
update_client_protocol_mapper
async
¶
Update a protocol mapper for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
mapper_id
|
str
|
ID of the protocol mapper |
required |
mapper_config
|
ProtocolMapperRepresentation | dict[str, Any]
|
Updated protocol mapper configuration as ProtocolMapperRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
mappers = admin_client.get_client_protocol_mappers(client_uuid, "my-realm") mapper = mappers[0] mapper.protocol = "saml" success = admin_client.update_client_protocol_mapper( client_uuid, mapper.id, mapper, "my-realm" )
update_client_role
async
¶
Update a role for a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_uuid
|
str
|
UUID of the client in Keycloak |
required |
role_name
|
str
|
Name of the role to update |
required |
role_config
|
RoleRepresentation | dict[str, Any]
|
Updated role configuration as RoleRepresentation or dict |
required |
realm_name
|
str
|
Name of the realm |
'master'
|
Returns:
| Type | Description |
|---|---|
bool
|
True if successful, False otherwise |
Example
role = admin_client.get_client_role(client_uuid, "admin", "my-realm") role.description = "Updated description" success = admin_client.update_client_role( client_uuid, "admin", role, "my-realm" )
update_realm
async
¶
Update realm configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Name of the realm to update |
required |
realm_config
|
RealmRepresentation | dict[str, Any]
|
Updated realm configuration as RealmRepresentation or dict |
required |
namespace
|
str
|
Origin namespace for rate limiting |
required |
Returns:
| Type | Description |
|---|---|
RealmRepresentation
|
Updated realm configuration as RealmRepresentation |
Raises:
| Type | Description |
|---|---|
KeycloakAdminError
|
If realm update fails |
update_realm_themes
async
¶
KeycloakAdminError ¶
get_keycloak_admin_client
async
¶
Factory function to create KeycloakAdminClient for a specific instance.
This function handles: - Looking up Keycloak instance details from Kubernetes - Retrieving admin credentials from secrets - Creating configured admin client with rate limiting
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keycloak_name
|
str
|
Name of the Keycloak instance |
required |
namespace
|
str
|
Namespace where the Keycloak instance exists |
required |
rate_limiter
|
RateLimiter | None
|
Optional rate limiter for API throttling |
None
|
verify_ssl
|
bool
|
Whether to verify SSL certificates (default: False for development) |
False
|
Returns:
| Type | Description |
|---|---|
KeycloakAdminClient
|
Configured KeycloakAdminClient instance |
Validation utilities for the Keycloak operator.
This module provides validation functions for Keycloak resources, configurations, and operator settings. It includes:
- Resource specification validation
- Configuration consistency checks
- Security and best practice validations
- Cross-resource dependency validation
ValidationError ¶
_extract_version_from_image ¶
_parse_kubernetes_quantity ¶
Parse a Kubernetes quantity string into a numeric value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantity
|
str
|
Kubernetes quantity string (e.g., "100m", "1Gi", "2") |
required |
Returns:
| Type | Description |
|---|---|
float
|
Numeric value in base units |
Raises:
| Type | Description |
|---|---|
ValueError
|
If quantity format is invalid |
_parse_version ¶
Parse a semantic version string into major, minor, patch tuple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
version_string
|
str
|
Version string like "25.0.1" or "26.4.0" |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, int, int]
|
Tuple of (major, minor, patch) as integers |
Raises:
| Type | Description |
|---|---|
ValueError
|
If version format is invalid |
validate_client_id ¶
Validate Keycloak client ID format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
Client ID to validate |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If client ID is invalid |
validate_complete_resource ¶
Perform complete validation of a resource specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource
|
dict[str, Any]
|
Complete resource definition |
required |
resource_type
|
str
|
Type of resource |
required |
namespace
|
str
|
Target namespace |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str]]
|
List of dependencies found during validation |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If resource is invalid |
validate_cross_resource_references ¶
Validate cross-resource references and return list of dependencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource_spec
|
dict[str, Any]
|
Resource specification |
required |
resource_type
|
str
|
Type of the resource being validated |
required |
namespace
|
str
|
Current namespace |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str]]
|
List of (resource_type, name, namespace) tuples for dependencies |
validate_environment_variables ¶
Validate environment variable configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env_vars
|
dict[str, Any]
|
Environment variables dictionary |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If environment variable configuration is invalid |
validate_image_reference ¶
Validate container image reference format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
str
|
Container image reference |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If image reference is invalid |
validate_keycloak_version ¶
Validate Keycloak version supports required features (management port).
The management interface with separate port 9000 was introduced in Keycloak 25.0.0. Earlier versions do not support KC_HTTP_MANAGEMENT_PORT and will fail health checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
str
|
Container image reference |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If Keycloak version is too old and doesn't support management port |
validate_namespace_name ¶
Validate Kubernetes namespace name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Namespace name to validate |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If namespace name is invalid |
validate_realm_name ¶
Validate Keycloak realm name format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm_name
|
str
|
Realm name to validate |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If realm name is invalid |
validate_redirect_uris ¶
Validate OAuth2 redirect URIs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redirect_uris
|
list[str]
|
List of redirect URIs to validate |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If any URI is invalid |
validate_resource_limits ¶
Validate Kubernetes resource limits and requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resources
|
dict[str, Any]
|
Resource specification dictionary |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If resource specification is invalid |
validate_resource_name ¶
Validate Kubernetes resource name according to DNS-1123 subdomain rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Resource name to validate |
required |
resource_type
|
str
|
Type of resource for error messages |
'resource'
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If name is invalid |
validate_security_settings ¶
validate_url ¶
Validate URL format and basic security checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to validate |
required |
url_type
|
str
|
Type of URL for error messages |
'URL'
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If URL is invalid |
Observability¶
Prometheus metrics for the Keycloak operator.
This module provides comprehensive metrics collection for monitoring operator performance, resource reconciliation, and system health.
MetricsCollector ¶
Collects and manages metrics for the Keycloak operator.
Initialize metrics collector.
record_database_connection_test ¶
Record database connection test results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource_name
|
str
|
Name of the Keycloak resource |
required |
namespace
|
str
|
Namespace of the resource |
required |
database_type
|
str
|
Type of database |
required |
success
|
bool
|
Whether the connection test succeeded |
required |
duration
|
float
|
Time taken for the test |
required |
record_leader_election_change ¶
record_lease_renewal ¶
Record a leader election lease renewal attempt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance_id
|
str
|
Unique identifier for this operator instance |
required |
namespace
|
str
|
Namespace where the operator is running |
required |
success
|
bool
|
Whether the lease renewal succeeded |
required |
duration
|
float
|
Time taken for the renewal operation |
required |
record_rbac_validation ¶
record_reconciliation_skip ¶
Record a skipped reconciliation due to generation match.
This is called when a resource is already reconciled at the current generation and in Ready state, avoiding redundant API calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource_type
|
str
|
Type of resource (e.g., 'keycloak', 'realm', 'client') |
required |
namespace
|
str
|
Namespace of the resource |
required |
name
|
str
|
Name of the resource |
required |
track_reconciliation
async
¶
Context manager to track reconciliation operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource_type
|
str
|
Type of resource being reconciled |
required |
namespace
|
str
|
Namespace of the resource |
required |
name
|
str
|
Name of the resource |
required |
operation
|
str
|
Type of operation being performed |
'reconcile'
|
update_cnpg_cluster_status ¶
update_keycloak_instance_status ¶
update_leader_election_status ¶
update_resource_status ¶
MetricsServer ¶
HTTP server for exposing Prometheus metrics.
Initialize metrics server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
port
|
int
|
Port to serve metrics on |
8081
|
host
|
str
|
Host interface to bind to |
'0.0.0.0'
|
Health check utilities for the Keycloak operator.
This module provides comprehensive health checking capabilities for monitoring operator and system component health.
HealthCheckResult
dataclass
¶
Result of a health check operation.
HealthChecker ¶
Performs comprehensive health checks for the operator.
Initialize health checker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k8s_client
|
ApiClient | None
|
Kubernetes API client |
None
|
_check_operator_resources
async
¶
Check operator's own resources (deployment, service account, etc.).
_check_rbac_permissions
async
¶
Check if the operator has required RBAC permissions.
check_all
async
¶
Run all health checks.
Returns:
| Type | Description |
|---|---|
dict[str, HealthCheckResult]
|
Dictionary of health check results |
get_overall_health ¶
Determine overall health status from individual check results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict[str, HealthCheckResult]
|
Dictionary of health check results |
required |
Returns:
| Type | Description |
|---|---|
str
|
Overall health status |