Automating (un-)installing MySQL

I am currently trying to automate the purging and reinstallation of MySQL on Ubuntu (for Vagrant). However, I am encountering various problems with that.

Here is what I have:

# Uninstall old MySQL version
sudo systemctl stop mysql
sudo apt-get remove mysql-* -y
sudo apt-get autoremove -y
sudo apt-get autoclean -y
sudo rm -rf /etc/mysql /var/lib/mysql /var/log/mysql

# ...
# Do other stuff.
# ...

# Install MySQL latest, see
# https://gist.github.com/kpietru/a3cb08ee074a4418795a
MYSQL_PASSWORD="root"

export MYSQL_PASSWORD="$MYSQL_PASSWORD"

sudo expect -c '
    spawn apt-get install -y mysql-server

    expect "*password* user:"
    send "$env(MYSQL_PASSWORD)\r"

    expect "*password* user:"
    send "$env(MYSQL_PASSWORD)\r"

    expect "\r"
    send "enter\r"

interact'

sudo systemctl unmask mysql.service
sudo service mysql start

mysql --version

This works and my Vagrant box loads just fine. However, when I try to use MySQL like so:

mysql -uroot -proot

I get a socket related error message (see https://stackoverflow.com/questions/11990708/error-cant-connect-to-local-mysql-server-through-socket-var-run-mysqld-mysq). I do not want to fix an error here. I want the prior scripts to work correctly. Therefore, I will not go down the rabbit hole of fixing the socket error.

My first intuition was to use sudo apt-get purge -y mysql-* instead of remove, but then I have to automate the prompt responses with expect. I tried to do that with autoexpect, but the expect script generated does not seem to work.

Can you guys help me? Is there anything else I can try?

Thanks in advance & cheers


Solution 1:

A colleague of mine managed to find a solution to this problem. I will post it here so that I can spare others some headache :)

# Remove previous MySQL versions
####################################################################

export DEBIAN_FRONTEND=noninteractive

sudo systemctl stop mysql
sudo apt-get remove mysql-* -y

sudo dpkg --configure -a
sudo -E apt-get purge mysql-*
sudo rm -rf /etc/mysql /var/lib/mysql /var/log/mysql

sudo apt-get autoremove
sudo apt-get autoclean

# Install MySQL 8.0
####################################################################

sudo apt-get update
sudo apt install mysql-server-8.0 -o Dpkg::Options::="--force-confnew" -y

# Enable native password authentication
#
# Otherwise you would have to open MySQL as root:
# `sudo mysql -u root`
####################################################################

echo "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'; FLUSH PRIVILEGES;" | sudo mysql -u root