[dbaas] Fix mysql_static_user heredoc quoting

## Context

The null_resource.mysql_static_user provisioner in commit 2033e767 used
a bash -c wrapper with nested single quotes (`'"$DB"'`-style injection)
to interpolate the app-specific database name and credentials. The outer
bash -c '...' single-quoted string was broken by the inner ' characters
long before reaching the container, so the local (tg) shell saw `$DB`
and `$USER` unset and produced an empty database name:

    ERROR 1102 (42000) at line 1: Incorrect database name ''

Apply failed for both forgejo and roundcubemail.

## This change

Feed the SQL to mysql on the pod via stdin through `kubectl exec -i`:

- Outer command: `kubectl exec -i ... -- sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"'`
- Single-quoted shell heredoc (`<<'SQL'`) carries the SQL statements
- HCL interpolates `${each.key}`, `${each.value.database}`,
  `${each.value.password}` into the heredoc body before the shell runs
- No nested quoting — one single-quote layer, one double-quote layer,
  one heredoc layer

Plan/apply verified on the live stack: 2 added (forgejo + roundcubemail),
7 pre-existing drift items changed, 0 destroyed. Both users now log in
with their app-cached passwords.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Viktor Barzin 2026-04-17 22:34:12 +00:00
parent 9780c04ca0
commit b30bfd4690

View file

@ -611,19 +611,15 @@ resource "null_resource" "mysql_static_user" {
}
provisioner "local-exec" {
command = <<-EOT
kubectl --kubeconfig ${var.kube_config_path} exec -n dbaas mysql-standalone-0 -c mysql -- \
env USER='${each.key}' DB='${each.value.database}' PW='${each.value.password}' \
bash -c '
mysql -uroot -p"$MYSQL_ROOT_PASSWORD" <<SQL
CREATE DATABASE IF NOT EXISTS \`'"$DB"'\`;
CREATE USER IF NOT EXISTS '"'$USER'"'@'"'%'"' IDENTIFIED WITH caching_sha2_password BY '"'$PW'"';
ALTER USER '"'$USER'"'@'"'%'"' IDENTIFIED WITH caching_sha2_password BY '"'$PW'"';
GRANT ALL PRIVILEGES ON \`'"$DB"'\`.* TO '"'$USER'"'@'"'%'"';
FLUSH PRIVILEGES;
SQL
'
EOT
command = <<EOT
kubectl --kubeconfig ${var.kube_config_path} exec -i -n dbaas mysql-standalone-0 -c mysql -- sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' <<'SQL'
CREATE DATABASE IF NOT EXISTS `${each.value.database}`;
CREATE USER IF NOT EXISTS '${each.key}'@'%' IDENTIFIED WITH caching_sha2_password BY '${each.value.password}';
ALTER USER '${each.key}'@'%' IDENTIFIED WITH caching_sha2_password BY '${each.value.password}';
GRANT ALL PRIVILEGES ON `${each.value.database}`.* TO '${each.key}'@'%';
FLUSH PRIVILEGES;
SQL
EOT
}
}