This commit is contained in:
Madzone
2026-09-08 17:05:36 +02:00
parent d4ea6e5417
commit a6a3e72659
19 changed files with 760 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
- name: Read existing PVE groups
ansible.builtin.command: pveum group list --output-format json
register: acl_groups
changed_when: false
check_mode: false
- name: Read existing PVE roles
ansible.builtin.command: pveum role list --output-format json
register: acl_roles
changed_when: false
check_mode: false
- name: Validate configured roles
ansible.builtin.assert:
that:
- "'NoAccess' not in pve_roles"
- pve_roles | difference(acl_roles.stdout | from_json | map(attribute='roleid') | list) | length == 0
- name: Read existing PVE ACLs
ansible.builtin.command: pveum acl list --output-format json
register: acl_current
changed_when: false
check_mode: false
- name: Map each existing group on root with propagation
ansible.builtin.command:
argv: [pveum, acl, modify, /, --groups, "{{ item }}-{{ pve_realm }}", --roles, "{{ item }}", --propagate, '1']
loop: "{{ pve_roles }}"
when:
- (item ~ '-' ~ pve_realm) in (acl_groups.stdout | from_json | map(attribute='groupid') | list)
- acl_current.stdout | from_json | selectattr('path', 'equalto', '/') | selectattr('type', 'equalto', 'group') | selectattr('ugid', 'equalto', item ~ '-' ~ pve_realm) | selectattr('roleid', 'equalto', item) | selectattr('propagate', 'equalto', 1) | list | length == 0
changed_when: true
- name: Show groups awaiting their first OIDC login
ansible.builtin.debug:
msg: "{{ item }}-{{ pve_realm }} does not exist yet; log in a member through OIDC, then run playbook/acl.yml."
loop: "{{ pve_roles }}"
when: (item ~ '-' ~ pve_realm) not in (acl_groups.stdout | from_json | map(attribute='groupid') | list)
+31
View File
@@ -0,0 +1,31 @@
- name: Install OS trust tools
ansible.builtin.apt:
name: [ca-certificates, openssl]
state: present
- name: Copy public root CA
ansible.builtin.copy:
src: "{{ heimlan_ca_src }}"
dest: /usr/local/share/ca-certificates/HEIMLAN_RootCA.crt
owner: root
group: root
mode: '0644'
register: ca_copy
- name: Check CA validity
ansible.builtin.command:
argv: [openssl, x509, -in, /usr/local/share/ca-certificates/HEIMLAN_RootCA.crt, -noout, -checkend, '0']
changed_when: false
- name: Read CA fingerprint
ansible.builtin.command:
argv: [openssl, x509, -in, /usr/local/share/ca-certificates/HEIMLAN_RootCA.crt, -noout, -fingerprint, -sha256]
register: ca_fingerprint
changed_when: false
- name: Verify expected fingerprint when supplied
ansible.builtin.assert:
that: ca_fingerprint.stdout.split('=')[-1] | lower == heimlan_ca_sha256 | lower
when: heimlan_ca_sha256 | length > 0
- name: Update system trust (also repairs an interrupted previous run)
ansible.builtin.command: update-ca-certificates
environment:
LC_ALL: C
register: ca_update
changed_when: "ca_copy.changed or '0 added, 0 removed' not in ca_update.stdout"
+67
View File
@@ -0,0 +1,67 @@
- name: Check actual Java truststore and Keycloak installation
ansible.builtin.stat:
path: "{{ item }}"
loop:
- "{{ java_cacerts_path }}"
- "{{ java_keytool }}"
- "{{ keycloak_home }}/bin/kc.sh"
register: java_paths
- name: Require installed JVM and Keycloak
ansible.builtin.assert:
that: item.stat.exists
fail_msg: 'Adjust Java/Keycloak paths to the existing installation.'
loop: "{{ java_paths.results }}"
loop_control:
label: "{{ item.item }}"
- name: Install CA in Keycloak system trust directory
ansible.builtin.file:
path: "{{ keycloak_home }}/conf/truststores"
state: directory
owner: "{{ keycloak_user }}"
group: "{{ keycloak_group }}"
mode: '0755'
- name: Copy CA for Keycloak truststore discovery
ansible.builtin.copy:
src: "{{ heimlan_ca_src }}"
dest: "{{ keycloak_home }}/conf/truststores/HEIMLAN_RootCA.pem"
owner: "{{ keycloak_user }}"
group: "{{ keycloak_group }}"
mode: '0644'
notify: Restart Keycloak
- name: Inspect existing managed Java CA alias
ansible.builtin.command:
argv: ["{{ java_keytool }}", -exportcert, -rfc, -alias, "{{ java_ca_alias }}", -keystore, "{{ java_cacerts_path }}", '-storepass:env', ANSIBLE_JAVA_STOREPASS]
environment:
ANSIBLE_JAVA_STOREPASS: "{{ java_cacerts_password }}"
LC_ALL: C
register: java_export
changed_when: false
failed_when: java_export.rc != 0 and 'does not exist' not in (java_export.stdout ~ java_export.stderr)
no_log: true
- name: Read existing Java CA fingerprint
ansible.builtin.command:
argv: [openssl, x509, -noout, -fingerprint, -sha256]
stdin: "{{ java_export.stdout }}"
register: java_fingerprint
changed_when: false
when: java_export.rc == 0
- name: Rotate managed Java CA alias if certificate changed
ansible.builtin.command:
argv: ["{{ java_keytool }}", -delete, -alias, "{{ java_ca_alias }}", -keystore, "{{ java_cacerts_path }}", '-storepass:env', ANSIBLE_JAVA_STOREPASS]
environment:
ANSIBLE_JAVA_STOREPASS: "{{ java_cacerts_password }}"
LC_ALL: C
when: java_export.rc == 0 and java_fingerprint.stdout != ca_fingerprint.stdout
no_log: true
notify: Restart Keycloak
- name: Import CA into the JVM used by Keycloak
ansible.builtin.command:
argv: ["{{ java_keytool }}", -importcert, -noprompt, -trustcacerts, -alias, "{{ java_ca_alias }}", -file, /usr/local/share/ca-certificates/HEIMLAN_RootCA.crt, -keystore, "{{ java_cacerts_path }}", '-storepass:env', ANSIBLE_JAVA_STOREPASS]
environment:
ANSIBLE_JAVA_STOREPASS: "{{ java_cacerts_password }}"
LC_ALL: C
when: java_export.rc != 0 or java_fingerprint.stdout | default('') != ca_fingerprint.stdout
no_log: true
notify: Restart Keycloak
- name: Apply trust before API access
ansible.builtin.meta: flush_handlers
+176
View File
@@ -0,0 +1,176 @@
- name: Configure Keycloak through verified HTTPS
no_log: true
module_defaults:
ansible.builtin.uri:
validate_certs: true
ca_path: "{{ system_ca_bundle }}"
use_proxy: false
follow_redirects: none
unredirected_headers: [Authorization]
timeout: 30
block:
- name: Obtain short-lived admin token
ansible.builtin.uri:
url: "{{ keycloak_base_url }}/realms/{{ keycloak_admin_realm }}/protocol/openid-connect/token"
method: POST
body_format: form-urlencoded
body:
grant_type: password
client_id: "{{ keycloak_admin_client_id }}"
username: "{{ keycloak_admin_username }}"
password: "{{ keycloak_admin_password }}"
status_code: 200
register: kc_token
until: kc_token.status | default(0) == 200
retries: 20
delay: 3
changed_when: false
- name: Define admin headers and realm settings
ansible.builtin.set_fact:
kc_headers:
Authorization: "Bearer {{ kc_token.json.access_token }}"
kc_api: "{{ keycloak_base_url }}/admin/realms/{{ keycloak_realm }}"
kc_realm_desired:
realm: "{{ keycloak_realm }}"
enabled: true
ssoSessionIdleTimeout: "{{ keycloak_sso_idle | int }}"
ssoSessionMaxLifespan: "{{ keycloak_sso_max | int }}"
clientSessionIdleTimeout: "{{ keycloak_client_idle | int }}"
clientSessionMaxLifespan: "{{ keycloak_client_max | int }}"
- name: Read realm
ansible.builtin.uri:
url: "{{ kc_api }}"
headers: "{{ kc_headers }}"
status_code: [200, 404]
register: kc_realm_current
- name: Create realm if missing
ansible.builtin.uri:
url: "{{ keycloak_base_url }}/admin/realms"
headers: "{{ kc_headers }}"
method: POST
body_format: json
body: "{{ kc_realm_desired }}"
status_code: 201
when: kc_realm_current.status == 404
changed_when: true
- name: Determine realm drift
ansible.builtin.set_fact:
kc_realm_drift: "{{ (kc_realm_current.json | default({}) | combine(kc_realm_desired)) != (kc_realm_current.json | default({})) }}"
- name: Update only managed realm fields
ansible.builtin.uri:
url: "{{ kc_api }}"
headers: "{{ kc_headers }}"
method: PUT
body_format: json
body: "{{ kc_realm_desired }}"
status_code: 204
when: kc_realm_current.status == 200 and kc_realm_drift
changed_when: true
- name: Ensure each top-level group exists
ansible.builtin.include_tasks: keycloak_group.yml
loop: "{{ pve_roles }}"
loop_control:
loop_var: kc_group_name
- name: Find client by exact ID
ansible.builtin.uri:
url: "{{ kc_api }}/clients?clientId={{ keycloak_client_id | urlencode }}"
headers: "{{ kc_headers }}"
register: kc_clients
- name: Select exact match
ansible.builtin.set_fact:
kc_matches: "{{ kc_clients.json | selectattr('clientId', 'equalto', keycloak_client_id) | list }}"
- name: Require unique client
ansible.builtin.assert:
that: kc_matches | length <= 1
- name: Define client settings
ansible.builtin.set_fact:
kc_client_desired:
clientId: "{{ keycloak_client_id }}"
protocol: openid-connect
enabled: true
publicClient: false
bearerOnly: false
clientAuthenticatorType: client-secret
standardFlowEnabled: true
implicitFlowEnabled: false
directAccessGrantsEnabled: false
serviceAccountsEnabled: false
redirectUris: "{{ pve_redirect_uris }}"
webOrigins: []
kc_session_attributes:
client.session.idle.timeout: "{{ keycloak_client_idle | string }}"
client.session.max.lifespan: "{{ keycloak_client_max | string }}"
- name: Create confidential PVE client
ansible.builtin.uri:
url: "{{ kc_api }}/clients"
headers: "{{ kc_headers }}"
method: POST
body_format: json
body: "{{ kc_client_desired | combine({'secret': keycloak_client_secret, 'attributes': kc_session_attributes, 'defaultClientScopes': ['profile', 'email']}) }}"
status_code: 201
when: kc_matches | length == 0
changed_when: true
- name: Read client after creation
ansible.builtin.uri:
url: "{{ kc_api }}/clients?clientId={{ keycloak_client_id | urlencode }}"
headers: "{{ kc_headers }}"
register: kc_clients
- name: Store client representation
ansible.builtin.set_fact:
kc_client_current: "{{ kc_clients.json | selectattr('clientId', 'equalto', keycloak_client_id) | first }}"
- name: Read actual client secret (not masked representation)
ansible.builtin.uri:
url: "{{ kc_api }}/clients/{{ kc_client_current.id }}/client-secret"
headers: "{{ kc_headers }}"
register: kc_secret
- name: Merge managed attributes preserving other client settings
ansible.builtin.set_fact:
kc_client_update: "{{ kc_client_desired | combine({'attributes': (kc_client_current.attributes | default({}) | combine(kc_session_attributes))}) }}"
- name: Update client only on drift or secret rotation
ansible.builtin.uri:
url: "{{ kc_api }}/clients/{{ kc_client_current.id }}"
headers: "{{ kc_headers }}"
method: PUT
body_format: json
body: "{{ kc_client_update | combine({'secret': keycloak_client_secret}) }}"
status_code: 204
when: (kc_client_current | combine(kc_client_update)) != kc_client_current or kc_secret.json.value != keycloak_client_secret
changed_when: true
- name: Ensure username claim independent of inherited client scopes
ansible.builtin.include_tasks: keycloak_mapper.yml
vars:
kc_mapper_desired:
name: pve-preferred-username
protocol: openid-connect
protocolMapper: oidc-usermodel-property-mapper
consentRequired: false
config:
user.attribute: username
claim.name: preferred_username
jsonType.label: String
id.token.claim: 'true'
access.token.claim: 'true'
userinfo.token.claim: 'true'
- name: Ensure flat group membership mapper
ansible.builtin.include_tasks: keycloak_mapper.yml
vars:
kc_mapper_desired:
name: groups
protocol: openid-connect
protocolMapper: oidc-group-membership-mapper
consentRequired: false
config:
claim.name: groups
full.path: 'false'
id.token.claim: 'true'
access.token.claim: 'true'
userinfo.token.claim: 'true'
always:
- name: Clear authentication facts
ansible.builtin.set_fact:
kc_headers: {}
kc_token: {}
kc_secret: {}
kc_client_current: {}
kc_clients: {}
kc_matches: []
+16
View File
@@ -0,0 +1,16 @@
- name: Find exact top-level Keycloak group
ansible.builtin.uri:
url: "{{ kc_api }}/groups?search={{ kc_group_name | urlencode }}&exact=true&first=0&max=100&briefRepresentation=true"
headers: "{{ kc_headers }}"
register: kc_group_search
- name: Create missing top-level Keycloak group
ansible.builtin.uri:
url: "{{ kc_api }}/groups"
headers: "{{ kc_headers }}"
method: POST
body_format: json
body:
name: "{{ kc_group_name }}"
status_code: 201
when: kc_group_search.json | selectattr('path', 'equalto', '/' ~ kc_group_name) | list | length == 0
changed_when: true
+33
View File
@@ -0,0 +1,33 @@
- name: Read client protocol mappers
ansible.builtin.uri:
url: "{{ kc_api }}/clients/{{ kc_client_current.id }}/protocol-mappers/models"
headers: "{{ kc_headers }}"
register: kc_mappers
- name: Select mapper by name
ansible.builtin.set_fact:
kc_mapper_matches: "{{ kc_mappers.json | selectattr('name', 'equalto', kc_mapper_desired.name) | list }}"
- name: Check mapper uniqueness
ansible.builtin.assert:
that: kc_mapper_matches | length <= 1
- name: Create mapper
ansible.builtin.uri:
url: "{{ kc_api }}/clients/{{ kc_client_current.id }}/protocol-mappers/models"
headers: "{{ kc_headers }}"
method: POST
body_format: json
body: "{{ kc_mapper_desired }}"
status_code: 201
when: kc_mapper_matches | length == 0
changed_when: true
- name: Update existing mapper on drift
ansible.builtin.uri:
url: "{{ kc_api }}/clients/{{ kc_client_current.id }}/protocol-mappers/models/{{ kc_mapper_matches[0].id }}"
headers: "{{ kc_headers }}"
method: PUT
body_format: json
body: "{{ kc_mapper_matches[0] | combine(kc_mapper_desired, recursive=true) }}"
status_code: 204
when:
- kc_mapper_matches | length == 1
- (kc_mapper_matches[0] | combine(kc_mapper_desired, recursive=true)) != kc_mapper_matches[0]
changed_when: true
+37
View File
@@ -0,0 +1,37 @@
- name: Check platform and required configuration
ansible.builtin.assert:
that:
- ansible_facts.os_family == 'Debian'
- not ansible_check_mode
- groups['keycloak'] | length == 1
- keycloak_base_url is match('^https://[^/]+$')
- pve_oidc_issuer == keycloak_base_url ~ '/realms/' ~ keycloak_realm
- pve_realm is match('^[A-Za-z0-9][A-Za-z0-9._-]*$')
- keycloak_realm is match('^[A-Za-z0-9][A-Za-z0-9._-]*$')
- pve_roles | length == pve_roles | unique | length
- "'NoAccess' not in pve_roles"
- keycloak_sso_idle | int > 0
- keycloak_sso_max | int >= keycloak_sso_idle | int
- keycloak_client_idle | int > 0
- keycloak_client_max | int >= keycloak_client_idle | int
- keycloak_client_idle | int <= keycloak_sso_idle | int
- keycloak_client_max | int <= keycloak_sso_max | int
- pve_redirect_uris | length > 0
fail_msg: 'Debian/Ubuntu, one Keycloak host, consistent HTTPS issuer and positive session values required. Check mode is unsupported.'
- name: Validate secret variables without logging their values
ansible.builtin.assert:
that:
- keycloak_admin_username | length > 0
- keycloak_admin_password | length > 0
- keycloak_client_secret | length >= 16
- keycloak_client_secret | length <= 256
- keycloak_client_secret == keycloak_client_secret | trim
- "'\\n' not in keycloak_client_secret"
- java_cacerts_password | length > 0
no_log: true
- name: Require exact HTTPS redirect URIs
ansible.builtin.assert:
that:
- item is match('^https://[^/]+/$')
- "'*' not in item"
loop: "{{ pve_redirect_uris }}"
+70
View File
@@ -0,0 +1,70 @@
- name: Check PVE version
ansible.builtin.command: pveversion
register: pve_version
changed_when: false
- name: Require PVE 9
ansible.builtin.assert:
that: "'pve-manager/9.' in pve_version.stdout"
- name: Verify OIDC discovery using PVE system CA trust
ansible.builtin.uri:
url: "{{ pve_oidc_issuer }}/.well-known/openid-configuration"
validate_certs: true
ca_path: "{{ system_ca_bundle }}"
use_proxy: false
follow_redirects: none
register: oidc_discovery
- name: Require exact issuer match
ansible.builtin.assert:
that: oidc_discovery.json.issuer == pve_oidc_issuer
- name: Read PVE realms
ansible.builtin.command: pveum realm list --output-format json
register: pve_realms
changed_when: false
- name: Select existing realm
ansible.builtin.set_fact:
pve_realm_matches: "{{ pve_realms.stdout | from_json | selectattr('realm', 'equalto', pve_realm) | list }}"
- name: Prevent changing another realm type
ansible.builtin.assert:
that: pve_realm_matches | length == 0 or pve_realm_matches[0].type == 'openid'
- name: Read full existing realm configuration
ansible.builtin.command:
argv: [pvesh, get, "/access/domains/{{ pve_realm }}", --output-format, json]
register: pve_realm_read
when: pve_realm_matches | length > 0
changed_when: false
no_log: true
- name: Define managed PVE realm settings
ansible.builtin.set_fact:
pve_desired:
issuer-url: "{{ pve_oidc_issuer }}"
client-id: "{{ keycloak_client_id }}"
autocreate: 1
groups-claim: groups
groups-autocreate: 1
groups-overwrite: 1
query-userinfo: 1
username-claim: preferred_username
pve_existing: "{{ (pve_realm_read.stdout | default('{}')) | from_json }}"
pve_drift: false
no_log: true
- name: Compare managed PVE fields
ansible.builtin.set_fact:
pve_drift: true
when: pve_existing.get(item.key, '') | string != item.value | string
loop: "{{ pve_desired | dict2items }}"
no_log: true
- name: Require compatible immutable username claim
ansible.builtin.assert:
that: pve_realm_matches | length == 0 or pve_existing.get('username-claim', '') == 'preferred_username'
fail_msg: 'Existing realm has a different immutable username-claim. See README migration guidance; automatic realm deletion is disabled.'
- name: Create or update PVE realm when configuration or key differs
ansible.builtin.command:
argv: "{{ ['pveum', 'realm', ('modify' if pve_realm_matches | length > 0 else 'add'), pve_realm] + ([] if pve_realm_matches | length > 0 else ['--type', 'openid', '--username-claim', 'preferred_username']) + ['--issuer-url', pve_oidc_issuer, '--client-id', keycloak_client_id, '--client-key', keycloak_client_secret, '--autocreate', '1', '--groups-claim', 'groups', '--groups-autocreate', '1', '--groups-overwrite', '1', '--query-userinfo', '1'] }}"
when: pve_realm_matches | length == 0 or pve_drift or pve_existing.get('client-key', '') != keycloak_client_secret
no_log: true
changed_when: true
- name: Clear in-memory key result
ansible.builtin.set_fact:
pve_existing: {}
pve_realm_read: {}
no_log: true