summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/webfaction/webfaction_db.py
blob: cf0a64a590eba0a75692ba5ca67241c6d63e87c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/python
#
# Create a webfaction database using Ansible and the Webfaction API
#
# ------------------------------------------
#
# (c) Quentin Stafford-Fraser 2015, with contributions gratefully acknowledged from:
#     * Andy Baker
#     * Federico Tarantini
#
# 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/>.
#

ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: webfaction_db
short_description: Add or remove a database on Webfaction
description:
    - Add or remove a database on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction.
author: Quentin Stafford-Fraser (@quentinsf)
version_added: "2.0"
notes:
    - >
      You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since the scripts use the remote webfaction API.
      The location is not important. However, running them on multiple hosts I(simultaneously) is best avoided. If you don't specify I(localhost) as
      your host, you may want to add C(serial: 1) to the plays.
    - See `the webfaction API <http://docs.webfaction.com/xmlrpc-api/>`_ for more info.
options:

    name:
        description:
            - The name of the database
        required: true

    state:
        description:
            - Whether the database should exist
        required: false
        choices: ['present', 'absent']
        default: "present"

    type:
        description:
            - The type of database to create.
        required: true
        choices: ['mysql', 'postgresql']

    password:
        description:
            - The password for the new database user.
        required: false
        default: None

    login_name:
        description:
            - The webfaction account to use
        required: true

    login_password:
        description:
            - The webfaction password to use
        required: true

    machine:
        description:
            - The machine name to use (optional for accounts with only one machine)
        required: false
'''

EXAMPLES = '''
  # This will also create a default DB user with the same
  # name as the database, and the specified password.

  - name: Create a database
    webfaction_db:
      name: "{{webfaction_user}}_db1"
      password: mytestsql
      type: mysql
      login_name: "{{webfaction_user}}"
      login_password: "{{webfaction_passwd}}"
      machine: "{{webfaction_machine}}"

  # Note that, for symmetry's sake, deleting a database using
  # 'state: absent' will also delete the matching user.

'''

import socket
import xmlrpclib

webfaction = xmlrpclib.ServerProxy('https://api.webfaction.com/')

def main():

    module = AnsibleModule(
        argument_spec = dict(
            name = dict(required=True),
            state = dict(required=False, choices=['present', 'absent'], default='present'),
            # You can specify an IP address or hostname.
            type = dict(required=True),
            password = dict(required=False, default=None, no_log=True),
            login_name = dict(required=True),
            login_password = dict(required=True, no_log=True),
            machine = dict(required=False, default=False),
        ),
        supports_check_mode=True
    )
    db_name  = module.params['name']
    db_state = module.params['state']
    db_type  = module.params['type']
    db_passwd = module.params['password']

    if module.params['machine']:
        session_id, account = webfaction.login(
            module.params['login_name'],
            module.params['login_password'],
            module.params['machine']
        )
    else:
        session_id, account = webfaction.login(
            module.params['login_name'],
            module.params['login_password']
        )

    db_list = webfaction.list_dbs(session_id)
    db_map = dict([(i['name'], i) for i in db_list])
    existing_db = db_map.get(db_name)

    user_list = webfaction.list_db_users(session_id)
    user_map = dict([(i['username'], i) for i in user_list])
    existing_user = user_map.get(db_name)

    result = {}

    # Here's where the real stuff happens

    if db_state == 'present':

        # Does a database with this name already exist?
        if existing_db:
            # Yes, but of a different type - fail
            if existing_db['db_type'] != db_type:
                module.fail_json(msg="Database already exists but is a different type. Please fix by hand.")

            # If it exists with the right type, we don't change anything.
            module.exit_json(
                changed = False,
            )


        if not module.check_mode:
            # If this isn't a dry run, create the db
            # and default user.
            result.update(
                webfaction.create_db(
                    session_id, db_name, db_type, db_passwd
                )
            )

    elif db_state == 'absent':

        # If this isn't a dry run...
        if not module.check_mode:

            if not (existing_db or existing_user):
                module.exit_json(changed = False,)

            if existing_db:
                # Delete the db if it exists
                result.update(
                    webfaction.delete_db(session_id, db_name, db_type)
                )

            if existing_user:
                # Delete the default db user if it exists
                result.update(
                    webfaction.delete_db_user(session_id, db_name, db_type)
                )

    else:
        module.fail_json(msg="Unknown state specified: {}".format(db_state))

    module.exit_json(
        changed = True,
        result = result
    )

from ansible.module_utils.basic import *

if __name__ == '__main__':
    main()