summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/general/plugins/modules/influxdb_user.py
blob: ca4201db1b030dda58ce5aa2f2fd967a549d79cc (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
210
211
212
213
214
215
216
217
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2017, Vitaliy Zhhuta <zhhuta () gmail.com>
# insipred by Kamil Szczygiel <kamil.szczygiel () intel.com> influxdb_database module
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import absolute_import, division, print_function

__metaclass__ = type

DOCUMENTATION = r'''
---
module: influxdb_user
short_description: Manage InfluxDB users
description:
  - Manage InfluxDB users.
author: "Vitaliy Zhhuta (@zhhuta)"
requirements:
  - "influxdb >= 0.9"
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  user_name:
    description:
      - Name of the user.
    required: true
    type: str
  user_password:
    description:
      - Password to be set for the user.
    required: false
    type: str
  admin:
    description:
      - Whether the user should be in the admin role or not.
      - Since version 2.8, the role will also be updated.
    default: false
    type: bool
  state:
    description:
      - State of the user.
    choices: [ absent, present ]
    default: present
    type: str
  grants:
    description:
      - Privileges to grant to this user.
      - Takes a list of dicts containing the "database" and "privilege" keys.
      - If this argument is not provided, the current grants will be left alone.
      - If an empty list is provided, all grants for the user will be removed.
    type: list
    elements: dict
extends_documentation_fragment:
  - community.general.influxdb
  - community.general.attributes

'''

EXAMPLES = r'''
- name: Create a user on localhost using default login credentials
  community.general.influxdb_user:
    user_name: john
    user_password: s3cr3t

- name: Create a user on localhost using custom login credentials
  community.general.influxdb_user:
    user_name: john
    user_password: s3cr3t
    login_username: "{{ influxdb_username }}"
    login_password: "{{ influxdb_password }}"

- name: Create an admin user on a remote host using custom login credentials
  community.general.influxdb_user:
    user_name: john
    user_password: s3cr3t
    admin: true
    hostname: "{{ influxdb_hostname }}"
    login_username: "{{ influxdb_username }}"
    login_password: "{{ influxdb_password }}"

- name: Create a user on localhost with privileges
  community.general.influxdb_user:
    user_name: john
    user_password: s3cr3t
    login_username: "{{ influxdb_username }}"
    login_password: "{{ influxdb_password }}"
    grants:
      - database: 'collectd'
        privilege: 'WRITE'
      - database: 'graphite'
        privilege: 'READ'

- name: Destroy a user using custom login credentials
  community.general.influxdb_user:
    user_name: john
    login_username: "{{ influxdb_username }}"
    login_password: "{{ influxdb_password }}"
    state: absent
'''

RETURN = r'''
#only defaults
'''

import json

from ansible.module_utils.urls import ConnectionError
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
import ansible_collections.community.general.plugins.module_utils.influxdb as influx


def find_user(module, client, user_name):
    user_result = None

    try:
        users = client.get_list_users()
        for user in users:
            if user['user'] == user_name:
                user_result = user
                break
    except ConnectionError as e:
        module.fail_json(msg=to_native(e))
    return user_result


def check_user_password(module, client, user_name, user_password):
    try:
        client.switch_user(user_name, user_password)
        client.get_list_users()
    except influx.exceptions.InfluxDBClientError as e:
        if e.code == 401:
            return False
    except ConnectionError as e:
        module.fail_json(msg=to_native(e))
    finally:
        # restore previous user
        client.switch_user(module.params['username'], module.params['password'])
    return True


def set_user_password(module, client, user_name, user_password):
    if not module.check_mode:
        try:
            client.set_user_password(user_name, user_password)
        except ConnectionError as e:
            module.fail_json(msg=to_native(e))


def create_user(module, client, user_name, user_password, admin):
    if not module.check_mode:
        try:
            client.create_user(user_name, user_password, admin)
        except ConnectionError as e:
            module.fail_json(msg=to_native(e))


def drop_user(module, client, user_name):
    if not module.check_mode:
        try:
            client.drop_user(user_name)
        except influx.exceptions.InfluxDBClientError as e:
            module.fail_json(msg=e.content)

    module.exit_json(changed=True)


def set_user_grants(module, client, user_name, grants):
    changed = False

    current_grants = []
    try:
        current_grants = client.get_list_privileges(user_name)
    except influx.exceptions.InfluxDBClientError as e:
        if not module.check_mode or 'user not found' not in e.content:
            module.fail_json(msg=e.content)

    try:
        parsed_grants = []
        # Fix privileges wording
        for i, v in enumerate(current_grants):
            if v['privilege'] != 'NO PRIVILEGES':
                if v['privilege'] == 'ALL PRIVILEGES':
                    v['privilege'] = 'ALL'
                parsed_grants.append(v)

        # check if the current grants are included in the desired ones
        for current_grant in parsed_grants:
            if current_grant not in grants:
                if not module.check_mode:
                    client.revoke_privilege(current_grant['privilege'],
                                            current_grant['database'],
                                            user_name)
                changed = True

        # check if the desired grants are included in the current ones
        for grant in grants:
            if grant not in parsed_grants:
                if not module.check_mode:
                    client.grant_privilege(grant['privilege'],
                                           grant['database'],
                                           user_name)
                changed = True

    except influx.exceptions.InfluxDBClientError as e:
        module.fail_json(msg=e.content)

    return changed


INFLUX_AUTH_FIRST_USER_REQUIRED = "error authorizing query: create admin user first or disable authentication"


def main():
    argument_spec = influx.InfluxDb.influxdb_argument_spec()
    argument_spec.update(
        state=dict(default='present', type='str', choices=['present', 'absent']),
        user_name=dict(required=True, type='str'),
        user_password=dict(required=False, type='str', no_log=True),
        admin=dict(default='False', type='bool'),
        grants=dict(type='list', elements='dict'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    state = module.params['state']
    user_name = module.params['user_name']
    user_password = module.params['user_password']
    admin = module.params['admin']
    grants = module.params['grants']
    influxdb = influx.InfluxDb(module)
    client = influxdb.connect_to_influxdb()

    user = None
    try:
        user = find_user(module, client, user_name)
    except influx.exceptions.InfluxDBClientError as e:
        if e.code == 403:
            reason = None
            try:
                msg = json.loads(e.content)
                reason = msg["error"]
            except (KeyError, ValueError):
                module.fail_json(msg=to_native(e))

            if reason != INFLUX_AUTH_FIRST_USER_REQUIRED:
                module.fail_json(msg=to_native(e))
        else:
            module.fail_json(msg=to_native(e))

    changed = False

    if state == 'present':
        if user:
            if not check_user_password(module, client, user_name, user_password) and user_password is not None:
                set_user_password(module, client, user_name, user_password)
                changed = True

            try:
                if admin and not user['admin']:
                    if not module.check_mode:
                        client.grant_admin_privileges(user_name)
                    changed = True
                elif not admin and user['admin']:
                    if not module.check_mode:
                        client.revoke_admin_privileges(user_name)
                    changed = True
            except influx.exceptions.InfluxDBClientError as e:
                module.fail_json(msg=to_native(e))

        else:
            user_password = user_password or ''
            create_user(module, client, user_name, user_password, admin)
            changed = True

        if grants is not None:
            if set_user_grants(module, client, user_name, grants):
                changed = True

        module.exit_json(changed=changed)

    if state == 'absent':
        if user:
            drop_user(module, client, user_name)
        else:
            module.exit_json(changed=False)


if __name__ == '__main__':
    main()