mysql_db 7.02 KB
Newer Older
Mark Theunissen committed
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
Mark Theunissen committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

# (c) 2012, Mark Theunissen <mark.theunissen@gmail.com>
# Sponsored by Four Kitchens http://fourkitchens.com.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
DOCUMENTATION = '''
---
module: mysql_db
short_description: Add or remove MySQL databases from a remote host.
description:
   - Add or remove MySQL databases from a remote host.
version_added: "0.6"
options:
  name:
    description:
      - name of the database to add or remove
    required: true
    default: null
  login_user:
    description:
      - The username used to authenticate with
    required: false
    default: null
  login_password:
    description:
42
      - The password used to authenticate with
43 44 45 46 47 48 49 50 51 52 53 54
    required: false
    default: null
  login_host:
    description:
      - Host running the database
    required: false
    default: localhost
  state:
    description:
      - The database state
    required: false
    default: present
55
    choices: [ "present", "absent", "dump", "import" ]
56 57 58 59 60 61 62 63 64 65
  collation:
    description:
      - Collation mode
    required: false
    default: null
  encoding:
    description:
      - Encoding mode
    required: false
    default: null
66 67
  target:
    description:
Jan-Piet Mens committed
68
      - Where to dump/get the C(.sql) file
69
    required: true
70
examples:
71
   - code: "mysql_db: db=bobdata state=present"
72
     description: Create a new database with name 'bobdata'
73
notes:
74
   - Requires the MySQLdb Python package on the remote host. For Ubuntu, this
Jan-Piet Mens committed
75
     is as easy as apt-get install python-mysqldb. (See M(apt).)
76
   - Both I(login_password) and I(login_user) are required when you are
77 78
     passing credentials. If none are present, the module will attempt to read
     the credentials from C(~/.my.cnf), and finally fall back to using the MySQL
Jan-Piet Mens committed
79
     default login of C(root) with no password.
80 81 82 83
requirements: [ ConfigParser ]
author: Mark Theunissen
'''

84
import ConfigParser
85
import os
Mark Theunissen committed
86
try:
87
    import MySQLdb
Mark Theunissen committed
88
except ImportError:
89 90 91
    mysqldb_found = False
else:
    mysqldb_found = True
Mark Theunissen committed
92 93 94 95 96

# ===========================================
# MySQL module specific support methods.
#

97
def db_exists(cursor, db):
Mark Theunissen committed
98 99 100
    res = cursor.execute("SHOW DATABASES LIKE %s", (db,))
    return bool(res)

101
def db_delete(cursor, db):
Mark Theunissen committed
102 103 104 105
    query = "DROP DATABASE %s" % db
    cursor.execute(query)
    return True

106 107 108 109 110 111 112 113 114 115 116 117
def db_dump(user, password, db_name, target):
    res = os.system("/usr/bin/mysqldump -q -u "+user+ " -p"+password+" "
            +db_name+" > "
            +target)
    return (res == 0)

def db_import(user, password, db_name, target):
    res = os.system("/usr/bin/mysql -u "+user+ " -p"+password+" "
            +db_name+" < "
            +target)
    return (res == 0)

118 119 120 121 122 123
def db_create(cursor, db, encoding, collation):
    if encoding:
        encoding = " CHARACTER SET %s" % encoding
    if collation:
        collation = " COLLATE %s" % collation
    query = "CREATE DATABASE %s%s%s" % (db, encoding, collation)
Mark Theunissen committed
124 125 126
    res = cursor.execute(query)
    return True

127 128 129
def load_mycnf():
    config = ConfigParser.RawConfigParser()
    mycnf = os.path.expanduser('~/.my.cnf')
130 131
    if not os.path.exists(mycnf):
        return False
132
    try:
133
        config.readfp(open(mycnf))
134
        creds = dict(user=config.get('client', 'user'),passwd=config.get('client', 'pass'))
135
    except (ConfigParser.NoOptionError, IOError):
136 137 138
        return False
    return creds

Mark Theunissen committed
139 140 141 142
# ===========================================
# Module execution.
#

143 144 145
def main():
    module = AnsibleModule(
        argument_spec = dict(
146 147 148
            login_user=dict(default=None),
            login_password=dict(default=None),
            login_host=dict(default="localhost"),
149
            login_unix_socket=dict(default=None),
150
            db=dict(required=True, aliases=['name']),
151 152
            encoding=dict(default=""),
            collation=dict(default=""),
153 154
            target=dict(default=None),
            state=dict(default="present", choices=["absent", "present","dump", "import"]),
155 156 157 158 159 160 161
        )
    )

    if not mysqldb_found:
        module.fail_json(msg="the python mysqldb module is required")

    db = module.params["db"]
162 163
    encoding = module.params["encoding"]
    collation = module.params["collation"]
164
    state = module.params["state"]
165
    target = module.params["target"]
166 167 168 169

    # Either the caller passes both a username and password with which to connect to
    # mysql, or they pass neither and allow this module to read the credentials from
    # ~/.my.cnf.
170 171 172
    login_password = module.params["login_password"]
    login_user = module.params["login_user"]
    if login_user is None and login_password is None:
173 174
        mycnf_creds = load_mycnf()
        if mycnf_creds is False:
175 176
            login_user = "root"
            login_password = ""
177
        else:
178 179 180 181
            login_user = mycnf_creds["user"]
            login_password = mycnf_creds["passwd"]
    elif login_password is None or login_user is None:
        module.fail_json(msg="when supplying login arguments, both login_user and login_password must be provided")
182

183 184
    if state in ['dump','import']:
        if target is None:
185
            module.fail_json(msg="with state=%s target is required" % (state))
186 187 188
        connect_to_db = db
    else:
        connect_to_db = 'mysql'
Mark Theunissen committed
189
    try:
190
        if module.params["login_unix_socket"]:
191
            db_connection = MySQLdb.connect(host=module.params["login_host"], unix_socket=module.params["login_unix_socket"], user=login_user, passwd=login_password, db=connect_to_db)
192
        else:
193
            db_connection = MySQLdb.connect(host=module.params["login_host"], user=login_user, passwd=login_password, db=connect_to_db)
Mark Theunissen committed
194
        cursor = db_connection.cursor()
195
    except Exception, e:
196
        module.fail_json(msg="unable to connect, check login_user and login_password are correct, or alternatively check ~/.my.cnf contains credentials")
Mark Theunissen committed
197

198
    changed = False
199
    if db_exists(cursor, db):
Mark Theunissen committed
200
        if state == "absent":
201
            changed = db_delete(cursor, db)
202 203 204 205 206 207 208 209
        elif state == "dump":
            changed = db_dump(login_user, login_password, db, target)
            if not changed:
                module.fail_json(msg="dump failed!")
        elif state == "import":
            changed = db_import(login_user, login_password, db, target)
            if not changed:
                module.fail_json(msg="import failed!")
Mark Theunissen committed
210 211
    else:
        if state == "present":
212
            changed = db_create(cursor, db, encoding, collation)
213 214

    module.exit_json(changed=changed, db=db)
Mark Theunissen committed
215

216 217 218
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()