gitlab.com/sparetimecoders/build-tools@v0.1.0/scripts/mysql.sh (about)

     1  #!/usr/bin/env bash
     2  
     3  # Creates a user for a service in a mysql database running inside kubernetes
     4  # A secret with the credentials will also be created.
     5  # Intended for local setup.
     6  # Parameters
     7  # 1 - the service name for which to create the database user, username and password will be the same as well
     8  # 2 - the environment to use to access Kubernetes
     9  mysql:create_database_user() {
    10    local SERVICE_NAME="${1}"
    11    local ENVIRONMENT="${2}"
    12    local KUBECTL_CMD=$(kubecmd ${ENVIRONMENT})
    13    db_pod_name=$(${KUBECTL_CMD} get pods --selector 'app=mysql' --output jsonpath={.items..metadata.name})
    14  
    15    ${KUBECTL_CMD} exec -it ${db_pod_name} -- bash -c "echo \"CREATE USER IF NOT EXISTS ${SERVICE_NAME} IDENTIFIED BY '${SERVICE_NAME}';CREATE DATABASE IF NOT EXISTS ${SERVICE_NAME}; GRANT ALL ON ${SERVICE_NAME}.* TO ${SERVICE_NAME};\" | mysql -u root -p\"password\""
    16  
    17    local SECRET_NAME="${SERVICE_NAME}-db"
    18    ${KUBECTL_CMD} delete secret ${SECRET_NAME} &> /dev/null || true
    19    ${KUBECTL_CMD} create secret generic ${SECRET_NAME} \
    20   --from-literal=USERNAME="${SERVICE_NAME}" \
    21   --from-literal=PASSWORD="${SERVICE_NAME}"
    22  }
    23  
    24  # Loads a dump-file into the database for a service
    25  # Intended for local setup.
    26  # Parameters
    27  # 1 - the service name for which to load data
    28  # 2 - the environment to use to access Kubernetes
    29  # 3 - path to the file to load
    30  mysql:load_data() {
    31    local SERVICE_NAME="$1"
    32    local ENVIRONMENT="$2"
    33    local FILE="$3"
    34  
    35    local KUBECTL_CMD=$(kubecmd ${ENVIRONMENT})
    36    db_pod_name=$(${KUBECTL_CMD} get pods --selector 'app=mysql' --output jsonpath={.items..metadata.name})
    37  
    38    cat "$FILE" | ${KUBECTL_CMD} exec -it ${db_pod_name} -- bash -c "mysql -u $SERVICE_NAME -p\"$SERVICE_NAME\" $SERVICE_NAME"
    39    ${KUBECTL_CMD} exec -it ${db_pod_name} -- bash -c "mysqlcheck -u root --password=\"password\" --optimize \"${SERVICE_NAME}\""
    40  }