summaryrefslogtreecommitdiffstats
path: root/ansible_collections/purestorage/flashblade/plugins/modules/purefb_ad.py
blob: ccd1f5d9282b129dade6921172f3fbbb39e5ffa9 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2021, Simon Dodsley (simon@purestorage.com)
# 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": ["preview"],
    "supported_by": "community",
}

DOCUMENTATION = r"""
---
module: purefb_ad
version_added: '1.6.0'
short_description: Manage FlashBlade Active Directory Account
description:
- Add or delete FlashBlade Active Directory Account
- FlashBlade allows the creation of one AD computer account, or joining of an
  existing AD computer account.
author:
- Pure Storage Ansible Team (@sdodsley) <pure-ansible-team@purestorage.com>
options:
  name:
    description:
    - Name of the AD account
    type: str
    required: true
  existing:
    description:
    - Does the account I(name) already exist in the AD environment
    type: bool
    default: false
  state:
    description:
    - Define whether the AD sccount is deleted or not
    default: present
    choices: [ absent, present ]
    type: str
  computer:
    description:
    -  The common name of the computer account to be created in the Active Directory domain.
    - If not specified, defaults to the name of the Active Directory configuration.
    type: str
  domain:
    description:
    - The Active Directory domain to join
    type: str
  username:
    description:
    - A user capable of creating a computer account within the domain
    type: str
  password:
    description:
    - Password string for I(username)
    type: str
  encryption:
    description:
    - The encryption types that will be supported for use by clients for Kerberos authentication
    type: list
    elements: str
    choices: [ aes256-sha1, aes128-sha1, arcfour-hmac]
    default: aes256-sha1
  join_ou:
    description:
    - Location where the Computer account will be created. e.g. OU=Arrays,OU=Storage.
    - If left empty, defaults to B(CN=Computers).
    type: str
  directory_servers:
    description:
    - A list of directory servers that will be used for lookups related to user authorization
    - Accepted server formats are IP address and DNS name
    - All specified servers must be registered to the domain appropriately in the array
      configured DNS and will only be communicated with over the secure LDAP (LDAPS) protocol.
      If not specified, servers are resolved for the domain in DNS
    - The specified list can have a maximum length of 5. If more are provided only the first
      5 are used.
    type: list
    elements: str
  kerberos_servers:
    description:
    - A list of key distribution servers to use for Kerberos protocol
    - Accepted server formats are IP address and DNS name
    - All specified servers must be registered to the domain appropriately in the array
      configured DNS. If not specified, servers are resolved for the domain in DNS.
    - The specified list can have a maximum length of 5. If more are provided only the first
      5 are used.
    type: list
    elements: str
  service_principals:
    description:
    - A list of either FQDNs or SPNs for registering services with the domain.
    - If not specified B(Computer Name.Domain) is used
    type: list
    elements: str
  service:
    description:
    - Service protocol for Active Directory principals
    - Refer to FlashBlade User Guide for more details
    type: list
    elements: str
    choices: ['nfs', 'cifs', 'HOST']
    default: nfs
  local_only:
    description:
    - Do a local-only delete of an active directory account
    type: bool
    default: false
extends_documentation_fragment:
- purestorage.flashblade.purestorage.fb
"""

EXAMPLES = r"""
- name: Create new AD account
  purestorage.flashblade.purefb_ad:
    name: ad_account
    computer: FLASHBLADE
    domain: acme.com
    username: Administrator
    password: Password
    join_ou: "CN=FakeOU"
    encryption:
    - aes128-cts-hmac-sha1-96
    - aes256-cts-hmac-sha1-96
    kerberos_servers:
    - kdc.acme.com
    directory_servers:
    - ldap.acme.com
    service_principals:
    - vip1.flashblade.acme.com
    fb_url: 10.10.10.2
    api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641

- name: Connect to existing AD account
  purestorage.flashblade.purefb_ad:
    name: ad_account
    computer: FLASHBLADE
    domain: acme.com
    username: Administrator
    password: Password
    existing: true
    kerberos_servers:
    - kdc.acme.com
    directory_servers:
    - ldap.acme.com
    fb_url: 10.10.10.2
    api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641

- name: Update existing AD account
  purestorage.flashblade.purefb_ad:
    name: ad_account
    encryption:
    - aes256-cts-hmac-sha1-96
    kerberos_servers:
    - kdc.acme.com
    directory_servers:
    - ldap.acme.com
    service_principals:
    - vip1.flashblade.acme.com
    fb_url: 10.10.10.2
    api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641

- name: Delete local AD account
  purestorage.flashblade.purefb_ad:
    name: ad_account
    local_only: true
    fb_url: 10.10.10.2
    api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641

- name: Fully delete AD account
  purestorage.flashblade.purefb_ad:
    name: ad_account
    fb_url: 10.10.10.2
    api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
"""

RETURN = r"""
"""

HAS_PURESTORAGE = True
try:
    from pypureclient.flashblade import ActiveDirectoryPost, ActiveDirectoryPatch
except ImportError:
    HAS_PURESTORAGE = False

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
    get_system,
    purefb_argument_spec,
)

MIN_REQUIRED_API_VERSION = "2.0"


def delete_account(module, blade):
    """Delete Active directory Account"""
    changed = True
    if not module.check_mode:
        res = blade.delete_active_directory(
            names=[module.params["name"]], local_only=module.params["local_only"]
        )
        if res.status_code != 200:
            module.fail_json(
                msg="Failed to delete AD Account {0}".format(module.params["name"])
            )
    module.exit_json(changed=changed)


def create_account(module, blade):
    """Create Active Directory Account"""
    changed = True
    if not module.params["existing"]:
        ad_config = ActiveDirectoryPost(
            computer_name=module.params["computer"],
            directory_servers=module.params["directory_servers"],
            kerberos_servers=module.params["kerberos_servers"],
            domain=module.params["domain"],
            encryption_types=module.params["encryption"],
            fqdns=module.params["service_principals"],
            join_ou=module.params["join_ou"],
            user=module.params["username"],
            password=module.params["password"],
        )
        if not module.check_mode:
            res = blade.post_active_directory(
                names=[module.params["name"]], active_directory=ad_config
            )
            if res.status_code != 200:
                module.fail_json(
                    msg="Failed to add Active Directory Account {0}. Error: {1}".format(
                        module.params["name"], res.errors[0].message
                    )
                )
    else:
        ad_config = ActiveDirectoryPost(
            computer_name=module.params["computer"],
            directory_servers=module.params["directory_servers"],
            kerberos_servers=module.params["kerberos_servers"],
            domain=module.params["domain"],
            encryption_types=module.params["encryption"],
            user=module.params["username"],
            password=module.params["password"],
        )
        if not module.check_mode:
            res = blade.post_active_directory(
                names=[module.params["name"]],
                active_directory=ad_config,
                join_existing_account=True,
            )
            if res.status_code != 200:
                module.fail_json(
                    msg="Failed to add Active Directory Account {0}. Error: {1}".format(
                        module.params["name"], res.errors[0].message
                    )
                )
    module.exit_json(changed=changed)


def update_account(module, blade):
    """Update Active Directory Account"""
    changed = False
    mod_ad = False
    current_ad = list(blade.get_active_directory(names=[module.params["name"]]).items)[
        0
    ]
    attr = {}
    if (
        module.params["join_ou"] != current_ad.join_ou
        and module.params["encryption"].sort() != current_ad.encryption_types.sort()
    ):
        module.fail_json(msg="Cannot make changes to OU when changing encryption types")
    if module.params["directory_servers"]:
        if current_ad.directory_servers:
            if set(module.params["directory_servers"]) != set(
                current_ad.directory_servers
            ):
                attr["directory_servers"] = module.params["directory_servers"]
                mod_ad = True
    if module.params["kerberos_servers"]:
        if current_ad.kerberos_servers:
            if set(module.params["kerberos_servers"]) != set(
                current_ad.kerberos_servers
            ):
                attr["kerberos_servers"] = module.params["kerberos_servers"]
                mod_ad = True
    if module.params["join_ou"] != current_ad.join_ou:
        attr["join_ou"] = module.params["join_ou"]
        mod_ad = True
    if set(module.params["encryption"]) != set(current_ad.encryption_types):
        attr["encryption_types"] = module.params["encryption"]
        mod_ad = True
    if module.params["service_principals"]:
        if current_ad.service_principal_names:
            full_spns = []
            for spn in range(0, len(module.params["service_principals"])):
                for service in range(0, len(module.params["service"])):
                    full_spns.append(
                        module.params["service"][service]
                        + "/"
                        + module.params["service_principals"][spn]
                    )
            if set(current_ad.service_principal_names) != set(full_spns):
                attr["service_principal_names"] = full_spns
                mod_ad = True
    if mod_ad:
        changed = True
        if not module.check_mode:
            ad_attr = ActiveDirectoryPatch(**attr)
            res = blade.patch_active_directory(
                names=[module.params["name"]], active_directory=ad_attr
            )
            if res.status_code != 200:
                module.fail_json(
                    msg="Failed to update Active Directory Account {0}. Error: {1}".format(
                        module.params["name"], res.errors[0].message
                    )
                )
    module.exit_json(changed=changed)


def main():
    argument_spec = purefb_argument_spec()
    argument_spec.update(
        dict(
            state=dict(type="str", default="present", choices=["absent", "present"]),
            username=dict(type="str"),
            password=dict(type="str", no_log=True),
            name=dict(type="str", required=True),
            service=dict(
                type="list",
                elements="str",
                default="nfs",
                choices=["nfs", "cifs", "HOST"],
            ),
            computer=dict(type="str"),
            existing=dict(type="bool", default=False),
            local_only=dict(type="bool", default=False),
            domain=dict(type="str"),
            join_ou=dict(type="str"),
            directory_servers=dict(type="list", elements="str"),
            kerberos_servers=dict(type="list", elements="str"),
            service_principals=dict(type="list", elements="str"),
            encryption=dict(
                type="list",
                elements="str",
                choices=["aes256-sha1", "aes128-sha1", "arcfour-hmac"],
                default=["aes256-sha1"],
            ),
        )
    )

    required_if = [["state", "present", ["username", "password", "domain"]]]

    module = AnsibleModule(
        argument_spec, required_if=required_if, supports_check_mode=True
    )

    if not HAS_PURESTORAGE:
        module.fail_json(msg="py-pure-client sdk is required for this module")

    blade = get_system(module)
    api_version = list(blade.get_versions().items)
    module.params["encryption"] = [
        crypt.replace("aes256-sha1", "aes256-cts-hmac-sha1-96").replace(
            "aes128-sha1", "aes128-cts-hmac-sha1-96"
        )
        for crypt in module.params["encryption"]
    ]
    if MIN_REQUIRED_API_VERSION not in api_version:
        module.fail_json(
            msg="FlashBlade REST version not supported. "
            "Minimum version required: {0}".format(MIN_REQUIRED_API_VERSION)
        )
    state = module.params["state"]
    exists = bool(blade.get_active_directory().total_item_count == 1)

    # TODO: Check SMB mode.
    # If mode is SMB adapter only allow nfs
    # Only allow cifs or HOST is SMB mode is native

    if not module.params["computer"]:
        module.params["computer"] = module.params["name"].replace("_", "-")
    if module.params["kerberos_servers"]:
        module.params["kerberos_servers"] = module.params["kerberos_servers"][0:5]
    if module.params["directory_servers"]:
        module.params["directory_servers"] = module.params["directory_servers"][0:5]

    if not exists and state == "present":
        create_account(module, blade)
    elif exists and state == "present":
        update_account(module, blade)
    elif exists and state == "absent":
        delete_account(module, blade)

    module.exit_json(changed=False)


if __name__ == "__main__":
    main()