summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/cloudstack/cs_account.py
blob: 3f3c50b8059eeef7d7cb92a011fc0e6d94c9c9b8 (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: cs_account
short_description: Manages accounts on Apache CloudStack based clouds.
description:
    - Create, disable, lock, enable and remove accounts.
version_added: '2.0'
author: René Moser (@resmo)
options:
  name:
    description:
      - Name of account.
    type: str
    required: true
  username:
    description:
      - Username of the user to be created if account did not exist.
      - Required on I(state=present).
    type: str
  password:
    description:
      - Password of the user to be created if account did not exist.
      - Required on I(state=present) if I(ldap_domain) is not set.
    type: str
  first_name:
    description:
      - First name of the user to be created if account did not exist.
      - Required on I(state=present) if I(ldap_domain) is not set.
    type: str
  last_name:
    description:
      - Last name of the user to be created if account did not exist.
      - Required on I(state=present) if I(ldap_domain) is not set.
    type: str
  email:
    description:
      - Email of the user to be created if account did not exist.
      - Required on I(state=present) if I(ldap_domain) is not set.
    type: str
  timezone:
    description:
      - Timezone of the user to be created if account did not exist.
    type: str
  network_domain:
    description:
      - Network domain of the account.
    type: str
  account_type:
    description:
      - Type of the account.
    type: str
    choices: [ user, root_admin, domain_admin ]
    default: user
  domain:
    description:
      - Domain the account is related to.
    type: str
    default: ROOT
  role:
    description:
      - Creates the account under the specified role name or id.
    type: str
    version_added: '2.8'
  ldap_domain:
    description:
      - Name of the LDAP group or OU to bind.
      - If set, account will be linked to LDAP.
    type: str
    version_added: '2.8'
  ldap_type:
    description:
      - Type of the ldap name. GROUP or OU, defaults to GROUP.
    type: str
    choices: [ GROUP, OU ]
    default: GROUP
    version_added: '2.8'
  state:
    description:
      - State of the account.
      - C(unlocked) is an alias for C(enabled).
    type: str
    choices: [ present, absent, enabled, disabled, locked, unlocked ]
    default: present
  poll_async:
    description:
      - Poll async jobs until job has finished.
    type: bool
    default: yes
extends_documentation_fragment: cloudstack
'''

EXAMPLES = '''
- name: create an account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    username: customer_xy
    password: S3Cur3
    last_name: Doe
    first_name: John
    email: john.doe@example.com
    domain: CUSTOMERS
    role: Domain Admin
  delegate_to: localhost

- name: Lock an existing account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    domain: CUSTOMERS
    state: locked
  delegate_to: localhost

- name: Disable an existing account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    domain: CUSTOMERS
    state: disabled
  delegate_to: localhost

- name: Enable an existing account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    domain: CUSTOMERS
    state: enabled
  delegate_to: localhost

- name: Remove an account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    domain: CUSTOMERS
    state: absent
  delegate_to: localhost

- name: Create a single user LDAP account in domain 'CUSTOMERS'
  cs_account:
    name: customer_xy
    username: customer_xy
    domain: CUSTOMERS
    ldap_domain: cn=customer_xy,cn=team_xy,ou=People,dc=domain,dc=local
  delegate_to: localhost

- name: Create a LDAP account in domain 'CUSTOMERS' and bind it to a LDAP group
  cs_account:
    name: team_xy
    username: customer_xy
    domain: CUSTOMERS
    ldap_domain: cn=team_xy,ou=People,dc=domain,dc=local
  delegate_to: localhost
'''

RETURN = '''
---
id:
  description: UUID of the account.
  returned: success
  type: str
  sample: 87b1e0ce-4e01-11e4-bb66-0050569e64b8
name:
  description: Name of the account.
  returned: success
  type: str
  sample: linus@example.com
account_type:
  description: Type of the account.
  returned: success
  type: str
  sample: user
state:
  description: State of the account.
  returned: success
  type: str
  sample: enabled
network_domain:
  description: Network domain of the account.
  returned: success
  type: str
  sample: example.local
domain:
  description: Domain the account is related.
  returned: success
  type: str
  sample: ROOT
role:
  description: The role name of the account
  returned: success
  type: str
  sample: Domain Admin
'''

# import cloudstack common
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (
    AnsibleCloudStack,
    cs_argument_spec,
    cs_required_together
)


class AnsibleCloudStackAccount(AnsibleCloudStack):

    def __init__(self, module):
        super(AnsibleCloudStackAccount, self).__init__(module)
        self.returns = {
            'networkdomain': 'network_domain',
            'rolename': 'role',
        }
        self.account = None
        self.account_types = {
            'user': 0,
            'root_admin': 1,
            'domain_admin': 2,
        }

    def get_role_id(self):
        role_param = self.module.params.get('role')
        role_id = None

        if role_param:
            role_list = self.query_api('listRoles')
            for role in role_list['role']:
                if role_param in [role['name'], role['id']]:
                    role_id = role['id']

            if not role_id:
                self.module.fail_json(msg="Role not found: %s" % role_param)

        return role_id

    def get_account_type(self):
        account_type = self.module.params.get('account_type')
        return self.account_types[account_type]

    def get_account(self):
        if not self.account:
            args = {
                'listall': True,
                'domainid': self.get_domain(key='id'),
                'fetch_list': True,
            }
            accounts = self.query_api('listAccounts', **args)
            if accounts:
                account_name = self.module.params.get('name')
                for a in accounts:
                    if account_name == a['name']:
                        self.account = a
                        break

        return self.account

    def enable_account(self):
        account = self.get_account()
        if not account:
            account = self.present_account()

        if account['state'].lower() != 'enabled':
            self.result['changed'] = True
            args = {
                'id': account['id'],
                'account': self.module.params.get('name'),
                'domainid': self.get_domain(key='id')
            }
            if not self.module.check_mode:
                res = self.query_api('enableAccount', **args)
                account = res['account']
        return account

    def lock_account(self):
        return self.lock_or_disable_account(lock=True)

    def disable_account(self):
        return self.lock_or_disable_account()

    def lock_or_disable_account(self, lock=False):
        account = self.get_account()
        if not account:
            account = self.present_account()

        # we need to enable the account to lock it.
        if lock and account['state'].lower() == 'disabled':
            account = self.enable_account()

        if (lock and account['state'].lower() != 'locked' or
                not lock and account['state'].lower() != 'disabled'):
            self.result['changed'] = True
            args = {
                'id': account['id'],
                'account': self.module.params.get('name'),
                'domainid': self.get_domain(key='id'),
                'lock': lock,
            }
            if not self.module.check_mode:
                account = self.query_api('disableAccount', **args)

                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    account = self.poll_job(account, 'account')
        return account

    def present_account(self):
        account = self.get_account()

        if not account:
            self.result['changed'] = True

            if self.module.params.get('ldap_domain'):
                required_params = [
                    'domain',
                    'username',
                ]
                self.module.fail_on_missing_params(required_params=required_params)

                account = self.create_ldap_account(account)

            else:
                required_params = [
                    'email',
                    'username',
                    'password',
                    'first_name',
                    'last_name',
                ]
                self.module.fail_on_missing_params(required_params=required_params)

                account = self.create_account(account)

        return account

    def create_ldap_account(self, account):
        args = {
            'account': self.module.params.get('name'),
            'domainid': self.get_domain(key='id'),
            'accounttype': self.get_account_type(),
            'networkdomain': self.module.params.get('network_domain'),
            'username': self.module.params.get('username'),
            'timezone': self.module.params.get('timezone'),
            'roleid': self.get_role_id()
        }
        if not self.module.check_mode:
            res = self.query_api('ldapCreateAccount', **args)
            account = res['account']

            args = {
                'account': self.module.params.get('name'),
                'domainid': self.get_domain(key='id'),
                'accounttype': self.get_account_type(),
                'ldapdomain': self.module.params.get('ldap_domain'),
                'type': self.module.params.get('ldap_type')
            }

            self.query_api('linkAccountToLdap', **args)

        return account

    def create_account(self, account):
        args = {
            'account': self.module.params.get('name'),
            'domainid': self.get_domain(key='id'),
            'accounttype': self.get_account_type(),
            'networkdomain': self.module.params.get('network_domain'),
            'username': self.module.params.get('username'),
            'password': self.module.params.get('password'),
            'firstname': self.module.params.get('first_name'),
            'lastname': self.module.params.get('last_name'),
            'email': self.module.params.get('email'),
            'timezone': self.module.params.get('timezone'),
            'roleid': self.get_role_id()
        }
        if not self.module.check_mode:
            res = self.query_api('createAccount', **args)
            account = res['account']

        return account

    def absent_account(self):
        account = self.get_account()
        if account:
            self.result['changed'] = True

            if not self.module.check_mode:
                res = self.query_api('deleteAccount', id=account['id'])

                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    self.poll_job(res, 'account')
        return account

    def get_result(self, account):
        super(AnsibleCloudStackAccount, self).get_result(account)
        if account:
            if 'accounttype' in account:
                for key, value in self.account_types.items():
                    if value == account['accounttype']:
                        self.result['account_type'] = key
                        break
        return self.result


def main():
    argument_spec = cs_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        state=dict(choices=['present', 'absent', 'enabled', 'disabled', 'locked', 'unlocked'], default='present'),
        account_type=dict(choices=['user', 'root_admin', 'domain_admin'], default='user'),
        network_domain=dict(),
        domain=dict(default='ROOT'),
        email=dict(),
        first_name=dict(),
        last_name=dict(),
        username=dict(),
        password=dict(no_log=True),
        timezone=dict(),
        role=dict(),
        ldap_domain=dict(),
        ldap_type=dict(choices=['GROUP', 'OU'], default='GROUP'),
        poll_async=dict(type='bool', default=True),
    ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=cs_required_together(),
        supports_check_mode=True
    )

    acs_acc = AnsibleCloudStackAccount(module)

    state = module.params.get('state')

    if state in ['absent']:
        account = acs_acc.absent_account()

    elif state in ['enabled', 'unlocked']:
        account = acs_acc.enable_account()

    elif state in ['disabled']:
        account = acs_acc.disable_account()

    elif state in ['locked']:
        account = acs_acc.lock_account()

    else:
        account = acs_acc.present_account()

    result = acs_acc.get_result(account)

    module.exit_json(**result)


if __name__ == '__main__':
    main()