Keycloak , an open source identity and access management solution, offers single sign-on, user federation, and strong authentication for web applications and services.
Deploying Keycloak in a Kubernetes environment using Helm has several benefits:
Scalability and high availability: As users or requests increase, Kubernetes can automatically scale Keycloak across multiple nodes to handle the load efficiently, ensuring consistent performance. Simplified deployment and management: Helm handles deployment configurations through a single customizable file, drastically reducing manual configuration mistakes and making it easier to manage upgrades, rollbacks, and scaling operations. Integration with cloud-native apps: Keycloak on Kubernetes integrates easily with other microservices, providing security and access management across your entire stack.
This tutorial guides you through installing Keycloak on Kubernetes using Helm, configuring it for secure usage, and managing users and realms through Helm.
Prerequisites
Before starting the installation process, make sure you have the following prerequisites installed on your local machine.
Setting Up Keycloak Using Helm
To start, you'll deploy the Keycloak stack to your local Kubernetes cluster using a Helm chart.
Adding the Helm Repository
First, add the Bitnami Helm repository to access the Keycloak Helm chart:
```bash
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
```
This step allows you to fetch and install the latest version of Keycloak from the Bitnami repository.
Configuring the Keycloak Values File To customize your Keycloak deployment, you need to configure the values.yaml
file for the Keycloak Helm chart. This file allows you to define environment variables, ingress settings, database configurations, and resource limits for your Keycloak deployment.
Create a values.yaml
file and populate it with the following code snippet:
```yaml
keycloak:
extraEnvVars:
- name: KEYCLOAK_LOG_LEVEL
value: DEBUG
persistence:
enabled: true
existingClaim: keycloak-pvc
ingress:
enabled: true
hostname: keycloak.example.com
ingressClassName: nginx
path: /
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
tls: false
postgresql:
enabled: true
postgresqlUsername: keycloak
postgresqlPassword: keycloakpassword
postgresqlDatabase: keycloakdb
service:
type: NodePort
nodePorts:
http: 30080
readinessProbe:
httpGet:
path: /realms/master
port: http
initialDelaySeconds: 60
timeoutSeconds: 5
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1"
```
The above configuration defines the environment variable KEYCLOAK_LOG_LEVEL
and sets its value to DEBUG
. This enables detailed logs for any issues you may encounter during deployment. You can use environment variables like this to configure Keycloak's runtime behavior and change settings like service ports or database credentials without directly modifying the application code.
It then sets up Ingress settings to expose your Keycloak service to external traffic and defines how ingress will route HTTP(S) requests to your Keycloak instance. The host name parameter specifies the domain name you'll use to access Keycloak. You can use any other domain name here, but make sure to map this URL to the external IP of your Kubernetes cluster in your DNS settings or local /etc/hosts
file.
The following part of the code exposes your Keycloak instance to external traffic through the domain keycloak.example.com
, with Nginx as the ingress controller managing the traffic:
```yaml
ingress:
enabled: true
hostname: keycloak.example.com
ingressClassName: nginx
path: /
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
tls: false
```
Keycloak stores its user data, realms, and configurations in a PostgreSQL database. It uses the postgresql
block in the values.yaml
file to set up this database and its credentials. The following part of the configuration enables the default database and sets up its credentials. You can use any other values for the credential:
```yaml
postgresql:
enabled: true
postgresqlUsername: keycloak
postgresqlPassword: keycloakpassword
postgresqlDatabase: keycloakdb
enabled: true
```
the Helm chart installation, the enabled: true
parameter enables this PostgreSQL database. You can set this to false
if you have an external database or want to use a different service. In that case, you'll need to provide the connection details.
In the resources section of the code, you set resource requests and limits to control the CPU and memory usage of your Keycloak deployment. This ensures that Keycloak has enough resources to run while preventing it from consuming too much of your cluster's resources:
```yaml
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1"
```
When you access Keycloak for the first time, you'll need to log in to the admin console using the administrator account user
and its password. You can set the admin password when deploying the Keycloak Helm chart or let Keycloak create an autogenerated password for you.
Use the second option for this tutorial to get a quick start.
Deploying Keycloak Using Helm
With the values.yaml
file configured, you can now deploy Keycloak using Helm:
```bash
helm install keycloak bitnami/keycloak -f values.yaml
```
This command installs the Keycloak chart using the values.yaml
file described above. It deploys Keycloak on your local Kubernetes cluster and creates all the necessary resources, including services, StatefulSets, and a PostgreSQL database.
To verify that Keycloak is running, check the status of the pods using the following kubectl command:
```bash
kubectl get pod
Make sure all Keycloak-related pods are ready (*ie*, they have at least one replica) and in a running state.
Accessing the Keycloak Admin Console Once Keycloak is successfully installed on your cluster, you need to obtain the URL of the deployed Keycloak instance by logging into the admin panel.
You can access Keycloak using the domain name set in the values.yaml
file. However, the latest versions of the Keycloak Helm chart implement advanced SSL security checks that prevent users from logging in to the admin panel using HTTP requests to the URL.
You can bypass this by using the IP address of the backend Keycloak server instead. Use the following commands to obtain this IP address:
```bash
export HTTP_NODE_PORT=$(kubectl get --namespace default -o jsonpath= "{.spec.ports[?(@.name=='http')].nodePort}" services keycloak)
export NODE_IP=$(kubectl get nodes --namespace default -o jsonpath= "{.items[0].status.addresses[0].address}" )
echo "http:// ${NODE_IP} : ${HTTP_NODE_PORT} /"
```
Use the URL provided in the output to access the Keycloak admin panel. The default admin username is user
. To retrieve the autogenerated password from the main Keycloak pod, use the command below, which spawns a shell inside the main pod and locates the admin password using grep:
```bash
kubectl exec -it keycloak-`0 -- printenv | grep KEYCLOAK_ADMIN_PASSWORD
```
Use these credentials to log in to the master realm, which is the default admin's realm from where you can create additional realms, security policies, users, and more.
Initial Security Measures When you're logged in to the master realm as the admin user, you can set up some initial security measures from the GUI interface. These settings will apply to all other realms and their identities.
Enable SSL Enabling SSL encrypts the data transferred between clients, such as browsers and applications, and the Keycloak server. This prevents attackers from intercepting sensitive data like – usernames, passwords, and access tokens – when users access Keycloak over the public internet.
Keycloak-SSl-configuration You can enable SSL by navigating to Configure > Realm settings > General . The Require SSL dropdown shows three options allowing you to configure SSL based on where the requests are coming from.
Set the Require SSL option to All requests to enforce HTTPS for all connections and protect sensitive data. Use External requests if only external IPs need encryption while allowing internal access without HTTPS; avoid using None in production for security.
Configure a Strong Password Policy A strong password policy safeguards access to your business resources.
The Keycloak GUI makes it very easy to configure password policies. Navigate to Configure > Authentication > Policies > Password policy and click the Add policy dropdown action.
Keycloak-password-policy
You can choose different attributes for user passwords, such as the minimum length, number of special characters and digits required, password expiry, and so on.
Keycloak-password-policy-setup
Enable Account Lockout After Failed Login Attempts
Setting up account lockout after a certain number of failed login attempts helps evade brute-force login attempts from malicious bots and thwarts DDoS attacks on the identity server.
You can enable account lockout in Keycloak by navigating to Configure > Realm settings > Security defenses > Brute force detection and setting the desired mode from the action menu.
Keycloak-account-lockout
Creating and Managing Realms with Helm
In Keycloak, a realm is a way to organize and isolate resources. It's a space where you manage users, roles, policies, and other settings specific to an application. Each realm is entirely isolated, meaning users and clients in one realm cannot access the resources of another realm. So realms allow you to isolate authentication and authorization settings for specific groups of users and applications.
Once in the master realm's admin console, you can create additional realms from the GUI interface.
Creating-realms-through-GUI
However, manually creating and configuring realms through the admin console can be repetitive and time-consuming, especially in larger deployments.
Helm simplifies this process by allowing you to define realms and their settings in its values.yaml
file using the "keycloakConfigCli" utility. This automates the deployment process and makes it reproducible and easy to manage. You can use the `values.yaml` file to define realms, users, and other Keycloak settings.
To create a new realm called "example-realm", add this configuration to your `values.yaml` file:
```yaml
keycloakConfigCli:
enabled: true
configuration:
example-realm.json: |
{
"realm": "example-realm",
"enabled": true,
"registrationAllowed": true
}
```
Apply the changes directly to your Keycloak installation using the following helm command:
```bash
helm upgrade --install keycloak bitnami/keycloak -f values.yaml
```
If you log in to the Keycloak admin console again and navigate to the realm dropdown at the top left, you'll see the newly created example-realm
.
Creating-new-realm-with-Helm
User Management Basics User management is one of Keycloak's core features. You can either create the various users for a realm through the Keycloak GUI interface or use Helm and "keycloakConfigCli" to automatically create users, groups, and roles in your realms during deployment.
By defining user configurations in the values.yaml
file, you ensure that Keycloak automatically sets up your users and groups, making the process consistent and repeatable across environments.
For example, if you update the keycloakConfigCli
section of your values.yaml
with the following code, it will create the "example-realm" alongside a user called "basicuser" and a group named "basicgroup" inside that realm:
```yaml
keycloakConfigCli:
enabled: true
configuration:
example-realm.json: |
{
"realm": "example-realm",
"enabled": true,
"registrationAllowed": true,
"users": [
{
"username": "basicuser",
"email": "basicuser@example.com",
"enabled": true,
"firstName": "Basic",
"lastName": "User",
"credentials": [
{
"type": "password",
"value": "basicpassword"
}
]
}
],
"groups": [
{
"name": "basicgroup"
}
]
}
```
Update the Keycloak installation to see the changes:
```bash
helm upgrade --install keycloak bitnami/keycloak -f values.yaml
```
Creating-users-with-helm
Conclusion Congrats! You now know how to deploy and manage Keycloak on Kubernetes using Helm. You've learned how to configure Keycloak's values file, handle post-installation security measures, and automate realm and user management using the keycloakConfigCli
utility and Helm.
While Keycloak's Helm chart helps you efficiently deploy and manage your identity and access management (IAM) needs, managing Kubernetes applications can still be challenging, especially at scale. mogenius enables you to take care of the entire lifecycle of your Kubernetes applications – from deployment to scaling and maintenance – so you can focus on development rather than infrastructure management.
Whether you use Keycloak or any other large-scale distributed application running on Kubernetes, mogenius abstracts Kubernetes complexity into easy-to-use workspaces, simplifies monitoring and maintenance, and provides seamless CI/CD pipelines to make application deployment a breeze. This reduces the need for DevOps support and increases productivity through developer self-service.