# roles/web-app-mediawiki/tasks/03_patch_settings.yml - name: "MEDIAWIKI | Normalize base settings in LocalSettings.php (clean + append once)" vars: _lsp_path: "{{ MEDIAWIKI_HTML_DIR }}/LocalSettings.php" _server_url: "{{ MEDIAWIKI_URL | regex_replace('/+$', '') }}" # Pre-escape single quotes for safe insertion into PHP single-quoted strings: _server_url_sq: "{{ _server_url | replace(\"'\", \"'\\\\''\") }}" _db_name_sq: "{{ database_name | replace(\"'\", \"'\\\\''\") }}" _db_user_sq: "{{ database_username | replace(\"'\", \"'\\\\''\") }}" _db_pass_sq: "{{ database_password | replace(\"'\", \"'\\\\''\") }}" _db_host_sq: "{{ (database_host ~ ':' ~ database_port) | replace(\"'\", \"'\\\\''\") }}" _lang_sq: "{{ HOST_LL | replace(\"'\", \"'\\\\''\") }}" shell: | docker exec -u {{ MEDIAWIKI_USER }} {{ MEDIAWIKI_CONTAINER }} bash -lc ' set -euo pipefail LSP="{{ _lsp_path }}" [ -f "$LSP" ] || { echo "ERROR: LocalSettings.php not found."; exit 1; } SERVER='\''{{ _server_url_sq }}'\'' DBNAME='\''{{ _db_name_sq }}'\'' DBUSER='\''{{ _db_user_sq }}'\'' DBPASS='\''{{ _db_pass_sq }}'\'' DBHOST='\''{{ _db_host_sq }}'\'' LANG='\''{{ _lang_sq }}'\'' tmp="$(mktemp)"; trap "rm -f \"$tmp\"" EXIT # 1) Copy existing file, but drop ALL prior assignments of our managed keys grep -Ev "^[[:space:]]*\$(wgServer|wgCanonicalServer|wgDBname|wgDBuser|wgDBpassword|wgDBserver|wgLanguageCode)[[:space:]]*=" "$LSP" > "$tmp" || true # 2) Append ONE clean, authoritative block { printf "\n\$wgServer = '\''%s'\'';\n" "$SERVER" printf "\$wgCanonicalServer = '\''%s'\'';\n" "$SERVER" printf "\$wgDBname = '\''%s'\'';\n" "$DBNAME" printf "\$wgDBuser = '\''%s'\'';\n" "$DBUSER" printf "\$wgDBpassword = '\''%s'\'';\n" "$DBPASS" printf "\$wgDBserver = '\''%s'\'';\n" "$DBHOST" printf "\$wgLanguageCode = '\''%s'\'';\n" "$LANG" } >> "$tmp" # 3) Idempotent write: only replace if content actually changed if ! cmp -s "$LSP" "$tmp"; then cat "$tmp" > "$LSP" echo CHANGED fi ' args: executable: /bin/bash register: mw_lsp_update changed_when: "'CHANGED' in (mw_lsp_update.stdout | default(''))" failed_when: mw_lsp_update.rc != 0 no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"