Keycloak Realm Import

How to perform an automated Keyacloak Realm Import

Keycloak Realm Import

The Keycloak Operator ships with the feature of automatically perform a realm import for the Keycloak Deployment.

Note:
If a Realm with the same name already exists in Keycloak it will not be overwritten.
Note:
The Realm Import CR only supports creation of new realms and doesn’t updates or delete those.
Changes to the realm performed directly on Keycloak are not synched back in the CR.

Writing Realm Import CR

A Realm Import Custom Resource(CR) looks like follows:

apiVersion: k8s.keycloak.org/v2alpha1
kind: KeycloakRealmImport
metadata:
  name: my-realm-kc
spec:
  keycloakCRName: <name of the keycloak CR>
  realm:
    ...

This CR should be created in the same namespace as the Keycloak Deployment CR defined in the field keycloakCRName. The realm field accepts a full RealmRepresentation.

The suggested way to obtain a RealmRepresentation is leveraging the export functionality Importing and Exporting Realms

  • export the Realm to a single file

  • convert the json to yaml

  • copy-paste the obtained yaml as body for the realm key (make sure the indentation is correct)

Applying the Realm Import CR

Use kubectl to create the CR in the correct cluster namespace:

cat <<EOF >> example-realm-import.yaml
apiVersion: k8s.keycloak.org/v2alpha1
kind: KeycloakRealmImport
metadata:
  name: my-realm-kc
spec:
  keycloakCRName: <name of the keycloak CR>
  realm:
    id: example-realm
    realm: example-realm
    displayName: ExampleRealm
    enabled: true
EOF
kubectl apply -f example-realm-import.yaml

And you can check the progress of the Import by running:

kubectl get keycloakrealmimports/my-realm-kc -o go-template='{{range .status.conditions}}CONDITION: {{.type}}{{"\n"}}  STATUS: {{.status}}{{"\n"}}  MESSAGE: {{.message}}{{"\n"}}{{end}}'

When the import successfully completed the output will look like follow:

CONDITION: Done
  STATUS: true
  MESSAGE:
CONDITION: Started
  STATUS: false
  MESSAGE:
CONDITION: HasErrors
  STATUS: false
  MESSAGE:
On this page