rabbitmq_user 7.42 KB
Newer Older
Chris Hoffman committed
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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2013, Chatham Financial <oss@chathamfinancial.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/>.

DOCUMENTATION = '''
---
module: rabbitmq_user
short_description: Adds or removes users to RabbitMQ
description:
  - Add or remove users to RabbitMQ and assign permissions
27
version_added: "1.1"
Chris Hoffman committed
28 29 30 31 32 33 34 35 36 37
author: Chris Hoffman
options:
  user:
    description:
      - Name of user to add
    required: true
    default: null
    aliases: [username, name]
  password:
    description:
38 39 40
      - Password of user to add.
      - To change the password of an existing user, you must also specify
        C(force=yes).
Chris Hoffman committed
41 42 43 44 45 46 47 48 49 50 51 52
    required: false
    default: null
  tags:
    description:
      - User tags specified as comma delimited
    required: false
    default: null
  vhost:
    description:
      - vhost to apply access privileges.
    required: false
    default: /
53 54 55 56 57
  node:
    description:
      - erlang node name of the rabbit we wish to configure
    required: false
    default: rabbit
Chris Hoffman committed
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
  configure_priv:
    description:
      - Regular expression to restrict configure actions on a resource
        for the specified vhost.
      - By default all actions are restricted.
    required: false
    default: ^$
  write_priv:
    description:
      - Regular expression to restrict configure actions on a resource
        for the specified vhost.
      - By default all actions are restricted.
    required: false
    default: ^$
  read_priv:
    description:
      - Regular expression to restrict configure actions on a resource
        for the specified vhost.
      - By default all actions are restricted.
    required: false
    default: ^$
  force:
    description:
      - Deletes and recreates the user.
    required: false
83 84
    default: "no"
    choices: [ "yes", "no" ]
Chris Hoffman committed
85 86 87 88 89 90
  state:
    description:
      - Specify if user is to be added or removed
    required: false
    default: present
    choices: [present, absent]
91 92 93 94 95 96 97 98 99 100 101
'''

EXAMPLES = '''
# Add user to server and assign full access control
- rabbitmq_user: user=joe
                 password=changeme
                 vhost=/
                 configure_priv=.*
                 read_priv=.*
                 write_priv=.*
                 state=present
Chris Hoffman committed
102 103 104
'''

class RabbitMqUser(object):
105
    def __init__(self, module, username, password, tags, vhost, configure_priv, write_priv, read_priv, node):
Chris Hoffman committed
106 107 108
        self.module = module
        self.username = username
        self.password = password
109
        self.node = node
Chris Hoffman committed
110
        if tags is None:
111
            self.tags = list()
Chris Hoffman committed
112 113 114 115 116 117 118 119 120 121 122 123 124
        else:
            self.tags = tags.split(',')

        permissions = dict(
            vhost=vhost,
            configure_priv=configure_priv,
            write_priv=write_priv,
            read_priv=read_priv
        )
        self.permissions = permissions

        self._tags = None
        self._permissions = None
Chris Hoffman committed
125
        self._rabbitmqctl = module.get_bin_path('rabbitmqctl', True)
Chris Hoffman committed
126

127 128
    def _exec(self, args, run_in_check_mode=False):
        if not self.module.check_mode or (self.module.check_mode and run_in_check_mode):
129
            cmd = [self._rabbitmqctl, '-q', '-n', self.node]
130 131 132
            rc, out, err = self.module.run_command(cmd + args, check_rc=True)
            return out.splitlines()
        return list()
Chris Hoffman committed
133 134

    def get(self):
135
        users = self._exec(['list_users'], True)
Chris Hoffman committed
136 137 138 139 140 141 142 143 144 145 146

        for user_tag in users:
            user, tags = user_tag.split('\t')

            if user == self.username:
                for c in ['[',']',' ']:
                    tags = tags.replace(c, '')

                if tags != '':
                    self._tags = tags.split(',')
                else:
147
                    self._tags = list()
Chris Hoffman committed
148 149 150 151 152 153

                self._permissions = self._get_permissions()
                return True
        return False

    def _get_permissions(self):
154
        perms_out = self._exec(['list_user_permissions', self.username], True)
Chris Hoffman committed
155 156 157 158 159 160 161 162 163

        for perm in perms_out:
            vhost, configure_priv, write_priv, read_priv = perm.split('\t')
            if vhost == self.permissions['vhost']:
                return dict(vhost=vhost, configure_priv=configure_priv, write_priv=write_priv, read_priv=read_priv)

        return dict()

    def add(self):
164
        self._exec(['add_user', self.username, self.password])
Chris Hoffman committed
165 166

    def delete(self):
167
        self._exec(['delete_user', self.username])
Chris Hoffman committed
168 169

    def set_tags(self):
170
        self._exec(['set_user_tags', self.username] + self.tags)
Chris Hoffman committed
171 172

    def set_permissions(self):
173 174 175 176 177 178 179 180
        cmd = ['set_permissions']
        cmd.append('-p')
        cmd.append(self.permissions['vhost'])
        cmd.append(self.username)
        cmd.append(self.permissions['configure_priv'])
        cmd.append(self.permissions['write_priv'])
        cmd.append(self.permissions['read_priv'])
        self._exec(cmd)
Chris Hoffman committed
181 182

    def has_tags_modifications(self):
183
        return set(self.tags) != set(self._tags)
Chris Hoffman committed
184 185 186 187 188 189 190 191 192 193 194 195 196

    def has_permissions_modifications(self):
        return self._permissions != self.permissions

def main():
    arg_spec = dict(
        user=dict(required=True, aliases=['username', 'name']),
        password=dict(default=None),
        tags=dict(default=None),
        vhost=dict(default='/'),
        configure_priv=dict(default='^$'),
        write_priv=dict(default='^$'),
        read_priv=dict(default='^$'),
197
        force=dict(default='no', type='bool'),
198 199
        state=dict(default='present', choices=['present', 'absent']),
        node=dict(default='rabbit')
Chris Hoffman committed
200 201 202 203 204 205 206 207 208 209 210 211 212
    )
    module = AnsibleModule(
        argument_spec=arg_spec,
        supports_check_mode=True
    )

    username = module.params['user']
    password = module.params['password']
    tags = module.params['tags']
    vhost = module.params['vhost']
    configure_priv = module.params['configure_priv']
    write_priv = module.params['write_priv']
    read_priv = module.params['read_priv']
213
    force = module.params['force']
Chris Hoffman committed
214
    state = module.params['state']
215
    node = module.params['node']
Chris Hoffman committed
216

217
    rabbitmq_user = RabbitMqUser(module, username, password, tags, vhost, configure_priv, write_priv, read_priv, node)
Chris Hoffman committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    changed = False
    if rabbitmq_user.get():
        if state == 'absent':
            rabbitmq_user.delete()
            changed = True
        else:
            if force:
                rabbitmq_user.delete()
                rabbitmq_user.add()
                rabbitmq_user.get()
                changed = True

            if rabbitmq_user.has_tags_modifications():
                rabbitmq_user.set_tags()
                changed = True

            if rabbitmq_user.has_permissions_modifications():
                rabbitmq_user.set_permissions()
                changed = True
    elif state == 'present':
        rabbitmq_user.add()
        rabbitmq_user.set_tags()
        rabbitmq_user.set_permissions()
        changed = True

244
    module.exit_json(changed=changed, user=username, state=state)
Chris Hoffman committed
245

246
# import module snippets
247
from ansible.module_utils.basic import *
Chris Hoffman committed
248
main()