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

# (c) 2020, 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 = """
---
module: purefa_subnet
version_added: '1.0.0'
short_description:  Manage network subnets in a Pure Storage FlashArray
description:
    - This module manages the network subnets on a Pure Storage FlashArray.
author: Pure Storage Ansible Team (@sdodsley) <pure-ansible-team@purestorage.com>
options:
  name:
    description:
      - Subnet name.
    required: true
    type: str
  state:
    description:
      - Create or delete subnet.
    required: false
    default: present
    choices: [ "present", "absent" ]
    type: str
  enabled:
    description:
      - whether the subnet should be enabled or not
    default: true
    type: bool
  prefix:
    description:
      - Set the IPv4 or IPv6 address to be associated with the subnet.
    required: false
    type: str
  gateway:
    description:
      - IPv4 or IPv6 address of subnet gateway.
    required: false
    type: str
  mtu:
    description:
      - MTU size of the subnet. Range is 568 to 9000.
    required: false
    default: 1500
    type: int
  vlan:
    description:
      - VLAN ID. Range is 0 to 4094.
    required: false
    type: int
extends_documentation_fragment:
    - purestorage.flasharray.purestorage.fa
"""

EXAMPLES = """
- name: Create subnet subnet100
  purestorage.flasharray.purefa_subnet:
    name: subnet100
    vlan: 100
    gateway: 10.21.200.1
    prefix: "10.21.200.0/24"
    mtu: 9000
    state: present
    fa_url: 10.10.10.2
    api_token: c6033033-fe69-2515-a9e8-966bb7fe4b40

- name: Disable subnet subnet100
  purestorage.flasharray.purefa_subnet:
    name: subnet100
    enabled: false
    fa_url: 10.10.10.2
    api_token: c6033033-fe69-2515-a9e8-966bb7fe4b40

- name: Delete subnet subnet100
  purestorage.flasharray.purefa_subnet:
    name: subnet100
    state: absent
    fa_url: 10.10.10.2
    api_token: c6033033-fe69-2515-a9e8-966bb7fe4b40"""

RETURN = """
"""

try:
    from netaddr import IPNetwork, valid_ipv4, valid_ipv6

    HAS_NETADDR = True
except ImportError:
    HAS_NETADDR = False

import re
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
    get_system,
    purefa_argument_spec,
)


def _get_subnet(module, array):
    """Return subnet or None"""
    subnet = {}
    try:
        subnet = array.get_subnet(module.params["name"])
    except Exception:
        return None
    return subnet


def update_subnet(module, array, subnet):
    """Modify subnet settings"""
    changed = False
    current_state = {
        "mtu": subnet["mtu"],
        "vlan": subnet["vlan"],
        "prefix": subnet["prefix"],
        "gateway": subnet["gateway"],
    }
    address = str(subnet["prefix"].split("/", 1)[0])
    if not current_state["vlan"]:
        current_state["vlan"] = 0
    if not current_state["gateway"]:
        if valid_ipv4(address):
            current_state["gateway"] = "0.0.0.0"
        elif valid_ipv6(address):
            current_state["gateway"] = "::"
        else:
            module.fail_json(msg="Prefix address is not valid IPv4 or IPv6")

    if not module.params["prefix"]:
        prefix = subnet["prefix"]
    else:
        if module.params["gateway"] and not (
            module.params["gateway"] in ["0.0.0.0", "::"]
        ):
            if module.params["gateway"] and module.params["gateway"] not in IPNetwork(
                module.params["prefix"]
            ):
                module.fail_json(msg="Gateway and subnet are not compatible.")
            elif (
                not module.params["gateway"]
                and subnet["gateway"]
                and subnet["gateway"] not in IPNetwork(module.params["prefix"])
            ):
                module.fail_json(msg="Gateway and subnet are not compatible.")
        prefix = module.params["prefix"]
    if not module.params["vlan"]:
        vlan = subnet["vlan"]
        if not vlan:
            vlan = 0
    else:
        if not 0 <= module.params["vlan"] <= 4094:
            module.fail_json(
                msg="VLAN {0} is out of range (0 to 4094)".format(module.params["vlan"])
            )
        else:
            vlan = module.params["vlan"]
    if not module.params["mtu"]:
        mtu = subnet["mtu"]
    else:
        if not 568 <= module.params["mtu"] <= 9000:
            module.fail_json(
                msg="MTU {0} is out of range (568 to 9000)".format(module.params["mtu"])
            )
        else:
            mtu = module.params["mtu"]
    if not module.params["gateway"]:
        gateway = subnet["gateway"]
    else:
        if module.params["gateway"] and not (
            module.params["gateway"] in ["0.0.0.0", "::"]
        ):
            if module.params["gateway"] not in IPNetwork(prefix):
                module.fail_json(msg="Gateway and subnet are not compatible.")
        gateway = module.params["gateway"]
    new_state = {"prefix": prefix, "mtu": mtu, "gateway": gateway, "vlan": vlan}
    if new_state != current_state:
        changed = True
        if not module.check_mode:
            try:
                array.set_subnet(
                    subnet["name"],
                    prefix=new_state["prefix"],
                    mtu=new_state["mtu"],
                    vlan=new_state["vlan"],
                    gateway=new_state["gateway"],
                )
            except Exception:
                module.fail_json(
                    msg="Failed to change settings for subnet {0}.".format(
                        subnet["name"]
                    )
                )
    if subnet["enabled"] != module.params["enabled"]:
        if module.params["enabled"]:
            changed = True
            if not module.check_mode:
                try:
                    array.enable_subnet(subnet["name"])
                except Exception:
                    module.fail_json(
                        msg="Failed to enable subnet {0}.".format(subnet["name"])
                    )
        else:
            changed = True
            if not module.check_mode:
                try:
                    array.disable_subnet(subnet["name"])
                except Exception:
                    module.fail_json(
                        msg="Failed to disable subnet {0}.".format(subnet["name"])
                    )
    module.exit_json(changed=changed)


def create_subnet(module, array):
    """Create subnet"""
    changed = True
    if not module.params["prefix"]:
        module.fail_json(msg="Prefix required when creating subnet.")
    else:
        if module.params["gateway"] and not (
            module.params["gateway"] in ["0.0.0.0", "::"]
        ):
            if module.params["gateway"] and module.params["gateway"] not in IPNetwork(
                module.params["prefix"]
            ):
                module.fail_json(msg="Gateway and subnet are not compatible.")
        prefix = module.params["prefix"]
    if module.params["vlan"]:
        if not 0 <= module.params["vlan"] <= 4094:
            module.fail_json(
                msg="VLAN {0} is out of range (0 to 4094)".format(module.params["vlan"])
            )
        else:
            vlan = module.params["vlan"]
    else:
        vlan = 0
    if module.params["mtu"]:
        if not 568 <= module.params["mtu"] <= 9000:
            module.fail_json(
                msg="MTU {0} is out of range (568 to 9000)".format(module.params["mtu"])
            )
        else:
            mtu = module.params["mtu"]
    if module.params["gateway"] and not (module.params["gateway"] in ["0.0.0.0", "::"]):
        if module.params["gateway"] not in IPNetwork(prefix):
            module.fail_json(msg="Gateway and subnet are not compatible.")
        gateway = module.params["gateway"]
    else:
        gateway = ""
    if not module.check_mode:
        try:
            array.create_subnet(
                module.params["name"],
                prefix=prefix,
                mtu=mtu,
                vlan=vlan,
                gateway=gateway,
            )
        except Exception:
            module.fail_json(
                msg="Failed to create subnet {0}.".format(module.params["name"])
            )
    if module.params["enabled"]:
        if not module.check_mode:
            try:
                array.enable_subnet(module.params["name"])
            except Exception:
                module.fail_json(
                    msg="Failed to enable subnet {0}.".format(module.params["name"])
                )
    else:
        if not module.check_mode:
            try:
                array.disable_subnet(module.params["name"])
            except Exception:
                module.fail_json(
                    msg="Failed to disable subnet {0}.".format(module.params["name"])
                )
    module.exit_json(changed=changed)


def delete_subnet(module, array):
    """Delete subnet"""
    changed = True
    if not module.check_mode:
        try:
            array.delete_subnet(module.params["name"])
        except Exception:
            module.fail_json(
                msg="Failed to delete subnet {0}".format(module.params["name"])
            )
    module.exit_json(changed=changed)


def main():
    argument_spec = purefa_argument_spec()
    argument_spec.update(
        dict(
            name=dict(type="str", required=True),
            prefix=dict(type="str"),
            state=dict(type="str", default="present", choices=["present", "absent"]),
            gateway=dict(type="str"),
            enabled=dict(type="bool", default=True),
            mtu=dict(type="int", default=1500),
            vlan=dict(type="int"),
        )
    )

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    if not HAS_NETADDR:
        module.fail_json(msg="netaddr module is required")
    pattern = re.compile(r"[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$")
    if not pattern.match(module.params["name"]):
        module.fail_json(
            msg="name must be between 1 and 63 characters in length and begin and end "
            "with a letter or number. The name must include at least one letter or '-'."
        )
    state = module.params["state"]
    array = get_system(module)
    subnet = _get_subnet(module, array)
    if module.params["prefix"]:
        module.params["prefix"] = module.params["prefix"].strip("[]")
    if module.params["gateway"]:
        module.params["gateway"] = module.params["gateway"].strip("[]")
    if state == "present" and not subnet:
        create_subnet(module, array)
    if state == "present" and subnet:
        update_subnet(module, array, subnet)
    elif state == "absent" and subnet:
        delete_subnet(module, array)

    module.exit_json(changed=False)


if __name__ == "__main__":
    main()