Keycloak realm SMTP settings with Ansible

February 27, 2023 


Ansible has reasonably good support for managing various aspects of Keycloak. You can use the community.general.keycloak_realm module to handle realm management, including Keycloak realm SMTP server settings. However, in the true Ansible fashion the documentation looks good, but does not help you much. In fact, documentation only mentions that the smtp_server parameter is a dictionary, but that's it. To be honest, that's about as helpful as the description of the RealmRepresentation for Keycloak. This article aims to fill this documentation void. I also want to share some general advise for similar cases that pop up when you manage Keycloak programmatically.

Getting the JSON for Keycloak realm SMTP server settings

First you need to figure out the correct JSON payload to pass to Keycloak. First create a test realm with SMTP settings. Then use to show the resulting JSON object:

$ get realms/test --no-config --server http://localhost:8080 --realm master --user keycloak --password secret
--- snip ---
  "smtpServer" : {
    "password" : "**********",
    "starttls" : "true",
    "port" : "587",
    "auth" : "true",
    "host" : "",
    "replyTo" : "[email protected]",
    "from" : "[email protected]",
    "fromDisplayName" : "Keycloak",
    "user" : "my-smtp-user"
--- snip ---

Managing Keycloak realm SMTP settings with Ansible

Now we have the correct JSON format for configuring Keycloak realm SMTP servers. We then pass the equivalent values to the keycloak_realm module:

- name: "Ensure realm test"
    auth_client_id: "admin-cli"
    auth_keycloak_url: "http://localhost:8080/auth"
    auth_realm: "master"
    auth_username: "keycloak"
    auth_password: "secret"
    enabled: true
    state: "present"
    realm: "test"
    id: "test"
    display_name: "Test realm"
      host: ""
      port: "587"
      starttls: "true"
      auth: "true"
      user: "my-smtp-user"
      password: "secret"
      from: "[email protected]"
      fromDisplayName: "Keycloak"
      replyTo: "[email protected]"

Notice how the parameters in the smtp_server dictionary is exactly as in the JSON payload (e.g. fromDisplayName). This is crucial because Keycloak Admin REST API silently ignores parameters it does not recognize. It will also happily create a partial SMTP server configuration for you. The only exception is if you're lucky enough to forget an essential parameter (e.g. "host"). Also note that all parameters in smtp_server have string values - even those that are really booleans. That is a feature of the Keycloak Admin REST API (see the JSON payload, above) and not a bug.

Other use-cases

While this article is about SMTP server settings, the basic process is applicable to many other Keycloak resources. The methods described here helps you manage Keycloak with Puppet, Terraform and commands as well.

Samuli Seppänen
Samuli Seppänen
Author archive