気まぐれ備忘録

Amazon Linux2にitamaeでMySQL5.7を入れる

下記のレシピで良い感じに出来る。


execute("install mysql") do
  user("root")
  not_if("rpm -qa | grep mysql57-community-release-el7-8.noarch")
  command(
    <<-EOL
      sudo yum remove mysql-community-server mariadb-libs -y &&
      sudo rm -rf /var/lib/mysql &&
      sudo rpm -ivh http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm &&
      sudo yum install mysql-community-server -y &&
      sudo chown mysql:mysql /var/run/mysqld
    EOL
  )
end

service("mysqld") do
  user("root")
  action(%i(start enable))
end

execute("mysql_secure_installation") do
  user("root")
  only_if("mysql -u root -e 'show databases' | grep information_schema")
  command(
    <<-EOL
      array=( $(sudo cat "/var/log/mysqld.log" | grep -oP "A temporary password is generated for root@localhost: \K.+")) && sql_pw=${array[-1]}
      mysql -u root -p$sql_pw --connect-expired-password -e "set password for root@localhost=password('passwordPASSWORD@123'); FLUSH PRIVILEGES;"
      mysql -u root -ppasswordPASSWORD@123 -e "DELETE FROM mysql.user WHERE User='';"
      mysql -u root -ppasswordPASSWORD@123 -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');"
      mysql -u root -ppasswordPASSWORD@123 -e "DROP DATABASE test;"
      mysql -u root -ppasswordPASSWORD@123 -e "CREATE DATABASE IF NOT EXISTS dbname DEFAULT CHARACTER SET utf8;"
      mysql -u root -ppasswordPASSWORD@123 -e "CREATE USER IF NOT EXISTS 'hoge-user'@'localhost' IDENTIFIED BY 'hogePASS@000';"
      mysql -u root -ppasswordPASSWORD@123 -e "GRANT ALL ON dbname.* TO 'hoge-user'@'localhost';"
      mysql -u root -ppasswordPASSWORD@123 -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';"
      mysql -u root -ppasswordPASSWORD@123 -e "FLUSH PRIVILEGES;"
    EOL
  )
end

キモは

  • rpmでリポジトリ登録してmysql5.7インスコする
  • 5.7系はrootに初期passwordが設定されているので、以下のshellでlogから取ってきてる

array=(sudo cat /var/log/mysqld.log | grep -oP "A temporary password is generated for root@localhost: \K.+") && echo ${array[-1]}