MySQL

by linode
24 deployments · 12 still active · last rev. 1 year ago

Install MySQL or MariaDB to a Linode. Can also be used as a library for other StackScripts.

Compatible with: CentOS 7, Debian 7, Debian 8, Ubuntu 14.04 LTS
						#!/usr/bin/env python

"""
MySQL StackScript
	
	Author: Ricardo N Feliciano <rfeliciano@linode.com>
	Version: 1.0.0.0
	Requirements:
		- ss://linode/python-library <ssinclude StackScriptID="3">

This StackScript both deploys and provides a library for MySQL. The functions 
in this StackScript are designed to be run across the Linode Core Distributions:
	- Ubuntu
	- CentOS
	- Debian
	- Fedora

StackScript User Defined Variables:

<UDF name="db_root_password" label="MySQL/MariaDB root password" default="" />
"""

import os
import subprocess
import sys

try: # we'll need to rename included StackScripts before we can import them
	os.rename("/root/ssinclude-3", "/root/pythonlib.py")
except:
	pass

import pythonlib


def mysql_install(root_pw = False, db_name = False):
	"""Install MySQL or MariaDB"""
	# add logging support

	package = {
		'debian': 'mysql',
		'redhat': 'mariadb'
	}

	pythonlib.system_package_install(package[pythonlib.distro['family']] +
	"-server")
	
	mysql_start()

	# if provided with a root password, set it
	if root_pw :
		subprocess.call(['mysqladmin', '-u', 'root', 'password', root_pw])
	
	# if a database name was provided, let's create it
	if db_name :
		subprocess.call('mysql -uroot -p' + root_pw + ' -e "create database ' + db_name + '"', shell=True)


def mysql_start():
	"""Start MariaDB on CentOS and Fedora"""

	if pythonlib.distro['family']  == "redhat":
		subprocess.call(['systemctl', 'start', 'mariadb.service'])


def main():
	"""Install MySQL or MariaDB"""
	# add logging support
	
	pythonlib.init()
	pythonlib.system_update()

	if os.environ['DB_ROOT_PASSWORD'] != "":
		mysql_install(os.environ['DB_ROOT_PASSWORD'])
	else:
		mysql_install()

	pythonlib.end()


if __name__ == "__main__":
	sys.exit(main())