From 8ddf8dbb9090f758430b412e3ea7fbf0b29a9906 Mon Sep 17 00:00:00 2001 From: Abdullah Adeel Date: Fri, 28 Jan 2022 14:52:07 +0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7add=20`init`=20script=20for=20mysql?= =?UTF-8?q?=20container=20to=20run=20tests=20without=20db=20permission=20e?= =?UTF-8?q?rrors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../compose/production/mysql/Dockerfile | 4 ++ .../compose/production/mysql/init.sh | 40 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 {{cookiecutter.project_slug}}/compose/production/mysql/init.sh diff --git a/{{cookiecutter.project_slug}}/compose/production/mysql/Dockerfile b/{{cookiecutter.project_slug}}/compose/production/mysql/Dockerfile index 71eabc804..65aa79ab9 100644 --- a/{{cookiecutter.project_slug}}/compose/production/mysql/Dockerfile +++ b/{{cookiecutter.project_slug}}/compose/production/mysql/Dockerfile @@ -4,3 +4,7 @@ COPY ./compose/production/mysql/maintenance /usr/local/bin/maintenance RUN chmod +x /usr/local/bin/maintenance/* RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ && rmdir /usr/local/bin/maintenance + +COPY ./compose/production/mysql/init.sh /docker-entrypoint-initdb.d +RUN sed -i 's/\r$//g' /docker-entrypoint-initdb.d/init.sh +RUN chown -R mysql:mysql /docker-entrypoint-initdb.d/init.sh diff --git a/{{cookiecutter.project_slug}}/compose/production/mysql/init.sh b/{{cookiecutter.project_slug}}/compose/production/mysql/init.sh new file mode 100644 index 000000000..e6802e377 --- /dev/null +++ b/{{cookiecutter.project_slug}}/compose/production/mysql/init.sh @@ -0,0 +1,40 @@ +#!/bin/bash + + +initialize() { + { + mysql_note "Giving user ${MYSQL_USER} access to schema test_${MYSQL_DATABASE}" + docker_process_sql --database=mysql <<<"GRANT ALL ON \`test_${MYSQL_DATABASE//_/\\_}\`.* TO '$MYSQL_USER'@'%' ;" + + # exporting dummy MYSQL_ONETIME_PASSWORD to avoid -> MYSQL_ONETIME_PASSWORD: unbound variable + export DUMMY_ONETIME_PASSWORD="$MYSQL_ROOT_PASSWORD" + } || { + exit 1 + } +} + +docker_process_sql() { + if [ -n "$MYSQL_DATABASE" ]; then + set -- --database="$MYSQL_DATABASE" "$@" + fi + + mysql --protocol=socket -uroot --password="${MYSQL_ROOT_PASSWORD}" -hlocalhost --socket="${SOCKET}" --comments "$@" +} + +# logging functions +mysql_log() { + local type="$1"; shift + # accept argument string or stdin + local text="$*"; if [ "$#" -eq 0 ]; then text="$(cat)"; fi + local dt; dt="$(date --rfc-3339=seconds)" + printf '%s [%s] [Entrypoint]: %s\n' "$dt" "$type" "$text" +} + +mysql_note() { + mysql_log Note "$@" +} + +until (initialize); do + >&2 echo 'Waiting for MYSQL to execute init' + sleep 1 +done