summaryrefslogtreecommitdiff
path: root/plugins/modules/vyos_l3_interfaces.py.preview
blob: f6d4e6c92f8778818f9163b327bfcd04da9d602f (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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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

DOCUMENTATION = r"""
---
module: vyos_l3_interfaces
short_description: Manage L3 interface attributes on VyOS via the REST API.
description:
  - Manages IPv4 and IPv6 addresses on VyOS interfaces via the HTTPS REST API.
  - Mirrors C(vyos.vyos.vyos_l3_interfaces) but uses the HTTP API.
version_added: "1.0.0"
author:
  - VyOS Community (@vyos)
options:
  config:
    description: List of L3 interface configurations.
    type: list
    elements: dict
    suboptions:
      name:
        description: Full interface name (e.g. C(eth0), C(eth1)).
        type: str
        required: true
      ipv4:
        description: List of IPv4 address assignments.
        type: list
        elements: dict
        suboptions:
          address:
            description: IPv4 address in CIDR notation or C(dhcp).
            type: str
            required: true
      ipv6:
        description: List of IPv6 address assignments.
        type: list
        elements: dict
        suboptions:
          address:
            description: IPv6 address in CIDR notation or C(dhcpv6) or C(autoconf).
            type: str
            required: true
      vifs:
        description: VLAN sub-interface L3 settings.
        type: list
        elements: dict
        suboptions:
          vlan_id:
            description: 802.1Q VLAN ID.
            type: int
            required: true
          ipv4:
            description: IPv4 addresses for this VIF.
            type: list
            elements: dict
            suboptions:
              address:
                type: str
                required: true
          ipv6:
            description: IPv6 addresses for this VIF.
            type: list
            elements: dict
            suboptions:
              address:
                type: str
                required: true
  state:
    description:
      - C(merged): Add addresses to the interface (preserve existing).
      - C(replaced): Replace all addresses on each listed interface.
      - C(overridden): Replace all addresses on all interfaces.
      - C(deleted): Remove all addresses from listed (or all) interfaces.
      - C(gathered): Read L3 config from device without changes.
    type: str
    choices: [merged, replaced, overridden, deleted, gathered]
    default: merged
  hostname:
    description: IP address or FQDN of the VyOS device.
    type: str
    required: true
  port:
    description: HTTPS port for the REST API.
    type: int
    default: 443
  api_key:
    description: API key configured on the device.
    type: str
    required: true
    no_log: true
  timeout:
    description: Request timeout in seconds.
    type: int
    default: 30
  verify_ssl:
    description: Validate the device's TLS certificate.
    type: bool
    default: false
requirements:
  - VyOS 1.3+
seealso:
  - module: vyos.vyos.vyos_l3_interfaces
  - module: vyos.rest.vyos_interfaces
examples: |
  - name: Assign addresses to eth1 and eth2
    vyos.rest.vyos_l3_interfaces:
      hostname: 192.168.1.1
      api_key: MY-KEY
      config:
        - name: eth1
          ipv4:
            - address: 10.0.1.1/24
          ipv6:
            - address: "2001:db8::1/64"
        - name: eth2
          ipv4:
            - address: dhcp
      state: merged

  - name: Remove all addresses from eth1
    vyos.rest.vyos_l3_interfaces:
      hostname: 192.168.1.1
      api_key: MY-KEY
      config:
        - name: eth1
      state: deleted
"""

RETURN = r"""
before:
  description: L3 interface config before the module ran.
  returned: always
  type: list
after:
  description: L3 interface config after the module ran.
  returned: when changed
  type: list
gathered:
  description: L3 config read from device (state=gathered).
  returned: when state is gathered
  type: list
commands:
  description: set/delete commands issued.
  returned: always
  type: list
"""

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vyos.rest.plugins.module_utils.vyos_rest import (
    VYOS_REST_CONNECTION_ARGSPEC,
    VyOSRestClient,
    VyOSRestError,
)


_IFACE_TYPES = {
    "eth": "ethernet",
    "bond": "bonding",
    "vti": "vti",
    "vxlan": "vxlan",
    "lo": "loopback",
    "dummy": "dummy",
    "br": "bridge",
    "wg": "wireguard",
    "tun": "tunnel",
}


def _iface_type(name):
    for prefix, t in _IFACE_TYPES.items():
        if name.startswith(prefix):
            return t
    return "ethernet"


def _base(name):
    return ["interfaces", _iface_type(name), name]


def _get_l3_interfaces(client):
    try:
        result = client.retrieve_show_config(["interfaces"])
        raw = result.get("data") or {}
        out = []
        for itype, itype_data in raw.items():
            if not isinstance(itype_data, dict):
                continue
            for iname, idata in itype_data.items():
                if not isinstance(idata, dict):
                    continue
                entry = {"name": iname, "ipv4": [], "ipv6": []}
                for addr in _listify(idata.get("address")):
                    if ":" in addr:
                        entry["ipv6"].append({"address": addr})
                    elif addr == "dhcp":
                        entry["ipv4"].append({"address": addr})
                    else:
                        entry["ipv4"].append({"address": addr})
                # VIFs
                if "vif" in idata:
                    vifs = []
                    for vid, vdata in idata["vif"].items():
                        vif_e = {"vlan_id": int(vid), "ipv4": [], "ipv6": []}
                        if isinstance(vdata, dict):
                            for addr in _listify(vdata.get("address")):
                                if ":" in addr:
                                    vif_e["ipv6"].append({"address": addr})
                                else:
                                    vif_e["ipv4"].append({"address": addr})
                        vifs.append(vif_e)
                    entry["vifs"] = vifs
                if entry["ipv4"] or entry["ipv6"] or entry.get("vifs"):
                    out.append(entry)
        return out
    except VyOSRestError:
        return []


def _listify(val):
    """Return val as a list regardless of whether it's a str or list."""
    if val is None:
        return []
    if isinstance(val, list):
        return val
    return [val]


def _set_addresses(client, name, ipv4, ipv6, commands):
    base = _base(name)
    itype = _iface_type(name)
    for a in ipv4 or []:
        client.configure_set(base + ["address"], a["address"])
        commands.append(
            "set interfaces {t} {n} address '{a}'".format(
                t=itype,
                n=name,
                a=a["address"],
            ),
        )
    for a in ipv6 or []:
        client.configure_set(base + ["address"], a["address"])
        commands.append(
            "set interfaces {t} {n} address '{a}'".format(
                t=itype,
                n=name,
                a=a["address"],
            ),
        )


def _delete_addresses(client, name, commands):
    base = _base(name)
    itype = _iface_type(name)
    try:
        client.configure_delete(base + ["address"])
        commands.append(
            "delete interfaces {t} {n} address".format(t=itype, n=name),
        )
    except VyOSRestError:
        pass


def main():
    argument_spec = dict(
        config=dict(
            type="list",
            elements="dict",
            options=dict(
                name=dict(type="str", required=True),
                ipv4=dict(
                    type="list",
                    elements="dict",
                    options=dict(address=dict(type="str", required=True)),
                ),
                ipv6=dict(
                    type="list",
                    elements="dict",
                    options=dict(address=dict(type="str", required=True)),
                ),
                vifs=dict(
                    type="list",
                    elements="dict",
                    options=dict(
                        vlan_id=dict(type="int", required=True),
                        ipv4=dict(
                            type="list",
                            elements="dict",
                            options=dict(address=dict(type="str", required=True)),
                        ),
                        ipv6=dict(
                            type="list",
                            elements="dict",
                            options=dict(address=dict(type="str", required=True)),
                        ),
                    ),
                ),
            ),
        ),
        state=dict(
            type="str",
            default="merged",
            choices=["merged", "replaced", "overridden", "deleted", "gathered"],
        ),
    )
    argument_spec.update(VYOS_REST_CONNECTION_ARGSPEC)

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

    client = VyOSRestClient(module)
    state = module.params["state"]
    config = module.params.get("config") or []
    commands = []
    changed = False

    before = _get_l3_interfaces(client)

    if state == "gathered":
        module.exit_json(changed=False, gathered=before, before=before, commands=[])

    if module.check_mode:
        module.exit_json(changed=True, before=before, commands=["(check mode)"])

    try:
        if state == "deleted":
            targets = {i["name"] for i in config} if config else {i["name"] for i in before}
            for iface in before:
                if iface["name"] in targets:
                    _delete_addresses(client, iface["name"], commands)
                    changed = True

        elif state in ("merged", "replaced", "overridden"):
            if state in ("replaced", "overridden"):
                # First remove existing addresses on targeted interfaces
                targets = {i["name"] for i in config}
                if state == "overridden":
                    targets = {i["name"] for i in before}
                for iface in before:
                    if iface["name"] in targets:
                        _delete_addresses(client, iface["name"], commands)

            for iface_cfg in config:
                name = iface_cfg["name"]
                _set_addresses(
                    client,
                    name,
                    iface_cfg.get("ipv4"),
                    iface_cfg.get("ipv6"),
                    commands,
                )
                for vif in iface_cfg.get("vifs") or []:
                    vid = str(vif["vlan_id"])
                    base = _base(name) + ["vif", vid]
                    itype = _iface_type(name)
                    for a in (vif.get("ipv4") or []) + (vif.get("ipv6") or []):
                        client.configure_set(base + ["address"], a["address"])
                        commands.append(
                            "set interfaces {t} {n} vif {v} address '{a}'".format(
                                t=itype,
                                n=name,
                                v=vid,
                                a=a["address"],
                            ),
                        )
                changed = True
    except VyOSRestError as exc:
        module.fail_json(msg=str(exc))

    after = _get_l3_interfaces(client) if changed else before
    module.exit_json(changed=changed, before=before, after=after, commands=commands)


if __name__ == "__main__":
    main()