0

All-in-one device upgrade

Published 15 days ago

One upgrade step on one switch: activate, reload (once-only guard), commit or rollback. Returns { status: done } or throws ActivateFailed, RollbackFailed, DeviceUnreachable or AuthFailure. For native step retry and sleep in the workflow, use the single-attempt Device actions (Device pre-check, Get Reload Delay, Device post-check, Device activate, Device reload, Device commit, Device rollback) instead.

Script arista_eos Verified

The script

Submitted by hugo989 Python3
Verified 1 day ago
1
# py312
2
# requirements:
3
# pyeapi==1.0.4
4
# wmill==1.851.0
5

6
# Device upgrade: one upgrade step on one switch, picked by action.
7
# - activate: records the image of the running version as the rollback target (once per run, before any change),
8
#   copies the image to flash (skipped when already there), compares verify /sha512 with the expected digest, then
9
#   boot system. No reload. The image is image_url, or image_base_url + EOS-<target_version>.swi; the digest is
10
#   sha512, or the .sha512 file next to the image. A file that doesn't match is copied once more, then deleted.
11
#   An image file name that carries a version must carry target_version.
12
# - reload: reload now, at most once per switch and flow run. Skipped (reloaded false, with the reason) when this run
13
#   already sent it, the switch already runs target_version, or it rebooted less than min_uptime_seconds ago.
14
#   boot-config must be the image activate set in this run, or flash:/EOS-<target_version>.swi. It refuses while
15
#   show running-config diffs changes anything but its ! headers, or there is no startup-config (reload now doesn't
16
#   prompt, so unsaved changes would be lost), unless allow_unsaved. Rollback has no such check: it is the recovery path.
17
# - commit: write memory (refused while a config session's commit timer is pending, so a change about to roll back
18
#   isn't saved); the previous image stays on flash (delete_old_images removes only the others).
19
# - rollback: boot system back to the recorded previous image, then reload now behind the same guard. A boot that
20
#   this run's reload caused doesn't count against min_uptime_seconds.
21
# State (rollback target, activated image, reload markers) is the root flow run's user state under arista_eos-<host>-<port>.
22

23
import logging
24
import os
25
import re
26
import ssl
27
import time
28
import urllib.error
29
import urllib.request
30
from typing import Literal, TypedDict
31
from urllib.parse import urlsplit
32

33
import pyeapi
34
import wmill
35

36

37
class arista_eos(TypedDict):
38
    host: str
39
    username: str
40
    password: str
41
    port: int
42
    verify_tls: bool
43
    allow_http: bool
44

45

46
class ActivateFailed(Exception):
47
    pass
48

49

50
class RollbackFailed(Exception):
51
    pass
52

53

54
def main(
55
    auth: arista_eos,
56
    action: Literal["activate", "reload", "commit", "rollback"],
57
    target_version: str = "",
58
    image_base_url: str = "",
59
    vrf: str = "",
60
    min_uptime_seconds: int = 300,
61
    delete_old_images: bool = False,
62
    image_url: str = "",
63
    sha512: str = "",
64
    allow_unsaved: bool = False,
65
):
66
    """
67
    All-in-one device upgrade
68
    One upgrade step on one switch: activate (copy the image from image_url or EOS-<target>.swi from image_base_url, verify its sha512, boot system it, no reload), reload (exactly once, guarded, refused with unsaved config unless allow_unsaved), commit (write memory, refused while a config-session commit timer is pending; keep the previous image), rollback (boot the previous image and reload, same guard). Returns { status: "done" } or throws ActivateFailed, RollbackFailed, DeviceUnreachable or AuthFailure as the first token of the error. For native step retry and sleep in the workflow, use the single-attempt Device actions (Device pre-check, Get Reload Delay, Device post-check, Device activate, Device reload, Device commit, Device rollback) instead.
69
    """
70
    key = state_keys(auth)
71
    state = load_state(key) or {}
72
    min_uptime = 300 if min_uptime_seconds is None else min_uptime_seconds
73

74
    if action == "activate":
75
        # Set again only once this activate has booted the image: a stale one would let reload through.
76
        forget_activated(key, state)
77
        if not target_version or not (image_base_url or image_url):
78
            raise named(
79
                ActivateFailed,
80
                "target_version and image_base_url (or image_url) are required",
81
            )
82
        try:
83
            image, url = image_source(target_version, image_base_url, image_url)
84
        except ValueError as e:
85
            raise named(ActivateFailed, str(e))
86
        # A file name that carries a version must carry this one; one without (a lab image) is taken as is.
87
        if image_version(image) not in (None, target_version):
88
            raise named(
89
                ActivateFailed,
90
                f"{image} is named for {image_version(image)}, not target_version {target_version}",
91
            )
92
        steps = []
93
        previous = state.get("previous_image") or ""
94
        try:
95
            if sha512:
96
                expected = digest(sha512)
97
                if not expected:
98
                    raise Exception("sha512 must be the 128-hex digest of the image")
99
            else:
100
                try:
101
                    with urllib.request.urlopen(f"{url}.sha512", timeout=60) as r:
102
                        expected = digest(r.read().decode(errors="replace"))
103
                except urllib.error.HTTPError as e:
104
                    raise Exception(f"cannot read {url}.sha512 ({e.code}): pass sha512")
105
                except OSError as e:
106
                    reason = getattr(e, "reason", e)
107
                    # Unlike the switch's copy, this fetch checks the certificate: the digest is what activate trusts.
108
                    trust = (
109
                        ", or trust the image server's CA on the worker (SSL_CERT_FILE)"
110
                        if isinstance(reason, ssl.SSLCertVerificationError)
111
                        else ""
112
                    )
113
                    raise Exception(
114
                        f"cannot read {url}.sha512 ({reason}): pass sha512{trust}"
115
                    )
116
                if not expected:
117
                    raise Exception(f"no sha512 hash in {url}.sha512")
118

119
            d, boot, version = eapi(
120
                auth,
121
                [
122
                    {"cmd": "dir flash:/", "revision": 2},
123
                    "show boot-config",
124
                    "show version",
125
                ],
126
            )
127
            files = list(d["urls"]["flash:/"]["entries"])
128
            running = short_version(version["version"])
129
            booted = boot["softwareImage"].replace("flash:/", "")
130
            # boot-config is the running image (first run) or the target (an earlier run got past boot system).
131
            # Anything else is a stale boot-config this step won't guess around.
132
            if image_version(booted) != running and booted != image:
133
                raise Exception(
134
                    f"boot-config points to {boot['softwareImage']}, neither the running version {running} nor {image}: fix boot-config first"
135
                )
136
            # The rollback target is the image of the running version, recorded once per run before anything changes.
137
            if not previous and running != target_version:
138
                candidates = (
139
                    [booted]
140
                    if booted != image
141
                    else [
142
                        f
143
                        for f in files
144
                        if f.endswith(".swi") and image_version(f) == running
145
                    ]
146
                )
147
                if len(candidates) != 1 or candidates[0] not in files:
148
                    raise Exception(
149
                        f"cannot tell which image on flash runs {running} (candidates: {', '.join(candidates) or 'none'}): no rollback target"
150
                    )
151
                previous = f"flash:/{candidates[0]}"
152
                save_state(key, {**state, "previous_image": previous})
153

154
            def copy():
155
                # The copy runs on the switch and can take minutes for a ~1 GB image.
156
                eapi(
157
                    auth,
158
                    [*([f"cli vrf {vrf}"] if vrf else []), f"copy {url} flash:{image}"],
159
                    "json",
160
                    3600,
161
                )
162
                steps.append(f"copied {url}")
163

164
            def verify():
165
                [v] = eapi(auth, [f"verify /sha512 flash:{image}"])
166
                return digest((v.get("messages") or [""])[0])
167

168
            copied = image not in files
169
            if copied:
170
                copy()
171
            actual = verify()
172
            if actual != expected and not copied:
173
                # Most likely a partial copy left by a killed run: copy it once more.
174
                eapi(auth, [f"delete flash:{image}"])
175
                copy()
176
                actual = verify()
177
            if actual != expected:
178
                # An earlier run may have booted it already: never leave boot-config on a deleted image.
179
                restored = booted == image and previous
180
                if restored:
181
                    boot_system(auth, previous.replace("flash:/", ""))
182
                eapi(auth, [f"delete flash:{image}"])
183
                raise Exception(
184
                    f"sha512 mismatch for {image} (switch {actual or 'none'}, expected {expected}), deleted it"
185
                    + (f", boot-config back on {previous}" if restored else "")
186
                )
187
            steps.append("sha512 verified")
188
            steps.extend(boot_system(auth, image))
189
            # reload checks boot-config against this, so it needs no image_url of its own.
190
            save_state(
191
                key,
192
                {
193
                    **state,
194
                    "previous_image": previous,
195
                    "activated_image": f"flash:/{image}",
196
                },
197
            )
198
        except (DeviceUnreachable, AuthFailure):
199
            raise
200
        except Exception as e:
201
            raise named(ActivateFailed, str(e))
202
        return {"status": "done", "steps": steps, "previous_image": previous}
203

204
    if action == "commit":
205
        [sessions] = eapi(auth, ["show configuration sessions detail"])
206
        if sessions.get("commitTimerSessionName"):
207
            raise RuntimeError(
208
                f"config session {sessions['commitTimerSessionName']} is pending under a commit timer: confirm or abort it before commit (write memory)"
209
            )
210
        _, boot, d = eapi(
211
            auth,
212
            ["write memory", "show boot-config", {"cmd": "dir flash:/", "revision": 2}],
213
        )
214
        deleted = []
215
        # Rollback needs the previous image: only images that are neither booted nor the recorded previous one go.
216
        if delete_old_images and state.get("previous_image"):
217
            keep = [
218
                i.replace("flash:/", "")
219
                for i in (boot["softwareImage"], state["previous_image"])
220
            ]
221
            for f in list(d["urls"]["flash:/"]["entries"]):
222
                if re.match(r"^EOS.*\.swi$", f) and f not in keep:
223
                    eapi(auth, [f"delete flash:{f}"])
224
                    deleted.append(f)
225
        return {"status": "done", "saved": True, "deleted": deleted}
226

227
    if action == "reload":
228
        if not target_version:
229
            raise Exception("target_version is required for the reload guard")
230
        sw = read_switch(auth, state, min_uptime)
231
        sent = sw["marker"]("reload")
232
        if sw.get("unreachable"):
233
            if sent:
234
                return skip(
235
                    f"reload sent at {sent['sent_at']}; the switch no longer answers: it is reloading"
236
                )
237
            raise named(DeviceUnreachable, sw["unreachable"])
238
        if sent and (sent["confirmed"] or sent["boot_timestamp"] != sw["boot"]):
239
            return skip(guard_reason("reload", sent, sw))
240
        if sw["running"] == target_version:
241
            return skip(f"already running {target_version}")
242
        # The image activate set in this run (state), or exactly EOS-<target_version>.swi.
243
        activated = state.get("activated_image")
244
        if sw["image"] not in (activated, f"flash:/EOS-{target_version}.swi"):
245
            raise Exception(
246
                f"boot-config points to {sw['image']}, neither the image activate set ({activated or 'none in this run'}) nor flash:/EOS-{target_version}.swi: run activate first"
247
            )
248
        if sw["uptime"] < min_uptime:
249
            return skip(f"rebooted {round(sw['uptime'])} s ago")
250
        if not allow_unsaved and unsaved(auth):
251
            raise Exception(
252
                "unsaved config: run Save Config first, or pass allow_unsaved: true"
253
            )
254
        fire_reload(auth, key, "reload", sw["boot"])
255
        return {"status": "done", "reloaded": True}
256

257
    # rollback: boot the previous image (still on flash) and reload, with the same once-only guard.
258
    try:
259
        sw = read_switch(auth, state, min_uptime)
260
        sent = sw["marker"]("rollback")
261
        if sw.get("unreachable"):
262
            if sent:
263
                return skip(
264
                    f"rollback sent at {sent['sent_at']}; the switch no longer answers: it is reloading"
265
                )
266
            raise Exception(sw["unreachable"])
267
        if sent and (sent["confirmed"] or sent["boot_timestamp"] != sw["boot"]):
268
            return skip(guard_reason("rollback", sent, sw))
269
        d, boot = eapi(
270
            auth, [{"cmd": "dir flash:/", "revision": 2}, "show boot-config"]
271
        )
272
        files = list(d["urls"]["flash:/"]["entries"])
273
        current = boot["softwareImage"].replace("flash:/", "")
274
        # Without a recorded previous image (new run), the only other EOS image on flash is unambiguous.
275
        others = [f for f in files if re.match(r"^EOS.*\.swi$", f) and f != current]
276
        previous = (state.get("previous_image") or "").replace("flash:/", "") or (
277
            others[0] if len(others) == 1 else ""
278
        )
279
        if not previous:
280
            raise Exception(
281
                f"previous image unknown (EOS images on flash: {', '.join(others) or 'none'})"
282
            )
283
        if previous not in files:
284
            raise Exception(f"previous image {previous} is no longer on flash")
285
        reload = sw["marker"]("reload")
286
        if reload and reload["confirmed"] and reload["boot_timestamp"] == sw["boot"]:
287
            raise Exception(
288
                f"the reload sent at {reload['sent_at']} has not happened yet (same boot as when it was sent): rolling back now would race it, check the switch"
289
            )
290
        steps = boot_system(auth, previous)
291
        forget_activated(key, state)
292
        if sw["running"] == image_version(previous):
293
            return skip(
294
                f"already running the previous image {previous}; boot-config set back to it"
295
            )
296
        # A recent boot that this run's reload caused doesn't block the rollback: the post-check that ran after it
297
        # can end well inside min_uptime_seconds.
298
        ours = reload and reload["boot_timestamp"] != sw["boot"]
299
        if not ours and sw["uptime"] < min_uptime:
300
            return skip(f"rebooted {round(sw['uptime'])} s ago, not by this run")
301
        fire_reload(auth, key, "rollback", sw["boot"])
302
        return {
303
            "status": "done",
304
            "reloaded": True,
305
            "boot_image": f"flash:/{previous}",
306
            "steps": steps,
307
        }
308
    except AuthFailure:
309
        raise
310
    except Exception as e:
311
        raise named(
312
            RollbackFailed, f"{auth['host']}: {re.sub(r'^[A-Za-z]+: ', '', str(e))}"
313
        )
314

315

316
# Same function in Device check and Device upgrade.
317
# image_url wins; else image_base_url + EOS-<target>.swi. Returns (file name on flash, URL or ""). The URL goes into
318
# the switch's copy command, so it is an allowlist: http(s), then only A-Z a-z 0-9 . _ ~ : / % + - (no query, no
319
# user:password@, nothing the CLI reads as a separator), ending in a plain .swi file name. Raises ValueError otherwise.
320
def image_source(target, base, image_url):
321
    if image_url:
322
        image, url = urlsplit(image_url).path.rsplit("/", 1)[-1], image_url
323
    else:
324
        image = f"EOS-{target}.swi" if target else ""
325
        url = f"{base.rstrip('/')}/{image}" if image and base else ""
326
    if not url:
327
        return image, url
328
    # Not echoed: it would put the password in the steps and errors.
329
    if "@" in url:
330
        raise ValueError("the image URL must not contain @ (no user:password@ in it)")
331
    if not re.match(r"https?://", url):
332
        raise ValueError(
333
            f"the image URL must start with http:// or https://: got {url!r}"
334
        )
335
    if not urlsplit(url).hostname:
336
        raise ValueError(f"the image URL has no host: got {url!r}")
337
    bad = sorted(set(re.sub(r"[A-Za-z0-9._~:/%+-]", "", url.split("://", 1)[1])))
338
    if bad:
339
        raise ValueError(
340
            f"the image URL may only contain A-Z a-z 0-9 . _ ~ : / % + -, not {' '.join(map(repr, bad))}: got {url!r}"
341
        )
342
    if not re.fullmatch(r"[\w.+-]+\.swi", image):
343
        raise ValueError(f"the image URL must end in a .swi file name: got {url!r}")
344
    return image, url
345

346

347
def boot_system(auth, image):
348
    _, set_, _, after = eapi(
349
        auth, ["configure", f"boot system flash:{image}", "end", "show boot-config"]
350
    )
351
    if after["softwareImage"] != f"flash:/{image}":
352
        raise Exception(f"boot-config still points to {after['softwareImage']}")
353
    return [f"boot system flash:{image}", *(set_.get("warnings") or [])]
354

355

356
# reload now doesn't prompt to save. show running-config diffs is a unified diff of startup-config against
357
# running-config, empty when they match. Its two file-header lines come before the first @@. Changed lines that
358
# start with a single "!" are headers EOS writes itself (boot system shows there, so every activate changes one);
359
# "!!" comments are config. With no startup-config every line shows as added: unsaved, it would boot into ZTP.
360
# A refused command (AAA authorization, an older EOS) is not unsaved config: saving wouldn't clear it.
361
def unsaved(auth):
362
    try:
363
        [d] = eapi(auth, ["show running-config diffs"], "text")
364
    except pyeapi.eapilib.CommandError as e:
365
        raise Exception(f"cannot compare running and startup config: {e}")
366
    hunks, changed = False, []
367
    for l in d["output"].splitlines():
368
        hunks = hunks or l.startswith("@@")
369
        if hunks and l[:1] in ("+", "-") and l[1:].strip():
370
            changed.append(l[1:].strip())
371
    return any(not re.match(r"!(?!!)", l) for l in changed)
372

373

374
def forget_activated(key, state):
375
    if state.pop("activated_image", None):
376
        save_state(key, state)
377

378

379
def skip(reason):
380
    return {"status": "done", "reloaded": False, "reason": reason}
381

382

383
def guard_reason(kind, m, sw):
384
    if m["boot_timestamp"] == sw["boot"]:
385
        return f"{kind} sent at {m['sent_at']}; the switch is going down"
386
    return f"{kind} sent at {m['sent_at']} already rebooted the switch"
387

388

389
# A reload is sent at most once per switch and flow run. Each one leaves a marker { sent_at, boot_timestamp,
390
# confirmed }: boot_timestamp is the boot it was sent on, so a later boot means it happened, and confirmed means
391
# the command reached the switch. An unconfirmed marker on the same boot (the worker died first) is sent again.
392
# Outside a flow, a marker is dropped once the reboot it caused is min_uptime_seconds old.
393
def read_switch(auth, state, min_uptime):
394
    try:
395
        version, boot = eapi(auth, ["show version", "show boot-config"])
396
    except DeviceUnreachable as e:
397
        return {"unreachable": str(e), "marker": lambda k: state.get(k)}
398
    sw = {
399
        "running": short_version(version["version"]),
400
        "image": boot["softwareImage"],
401
        "boot": version["bootupTimestamp"],
402
        "uptime": version["uptime"],
403
    }
404
    in_flow = bool(os.environ.get("WM_FLOW_JOB_ID"))
405

406
    def marker(k):
407
        m = state.get(k)
408
        return (
409
            m
410
            if m
411
            and (
412
                in_flow
413
                or m["boot_timestamp"] == sw["boot"]
414
                or sw["uptime"] < min_uptime
415
            )
416
            else None
417
        )
418

419
    return {**sw, "marker": marker}
420

421

422
# Fire and forget: the switch drops the connection while going down, which is not an error. A connection that
423
# never opened, or a refusal from the switch, means it did not reload: the marker goes and the error is raised.
424
def fire_reload(auth, key, kind, boot_ts):
425
    def mark(m):
426
        rest = {k: v for k, v in (load_state(key) or {}).items() if k != kind}
427
        save_state(key, {**rest, kind: m} if m else rest)
428

429
    m = {
430
        "sent_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
431
        "boot_timestamp": boot_ts,
432
        "confirmed": False,
433
    }
434
    mark(m)
435
    eos = node(auth, 15)
436
    try:
437
        # Opened before sending, so a failure here means the command never left.
438
        eos.connection.transport.connect()
439
    except OSError as e:
440
        mark(None)
441
        raise named(DeviceUnreachable, f"{auth['host']}: {e}")
442
    try:
443
        eos.run_commands(["reload now"])
444
    except pyeapi.eapilib.ConnectionError as e:
445
        # Sent, then the connection dropped or timed out as the switch went down. A 401 is a refusal.
446
        err = connection_error(auth, eos, e)
447
        if isinstance(err, AuthFailure):
448
            mark(None)
449
            raise err
450
    except Exception:
451
        mark(None)
452
        raise
453
    mark({**m, "confirmed": True})
454

455

456
# Shared with Device check: the flow run's user state, keyed by switch, holds the pre-check snapshot, the image
457
# activate replaced (rollback target) and the reload markers. Outside a flow, it falls back to this script's own state.
458
# The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
459
# ponytail: the fallback is one map per script, so concurrent standalone runs can race; flows don't.
460
# The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
461
# always in (443 or 80 when unset), so host 10.0.0.11 with port 8443 and host https://10.0.0.11:8443 share one key,
462
# while two switches behind one address on different ports (or http and https) don't. State written before the port
463
# was part of the key is read from arista_eos_<host> as a fallback (all word characters, so never a new key); writes
464
# go to the new key only.
465
def state_keys(auth: arista_eos):
466
    url = switch_url(auth)
467
    port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
468
    return [
469
        f"arista_eos-{word(url.hostname)}-{port}",
470
        f"arista_eos_{word(auth['host'])}",
471
    ]
472

473

474
def word(s):
475
    return re.sub(r"\W", "_", s)
476

477

478
def load_state(keys):
479
    for key in keys:
480
        if os.environ.get("WM_FLOW_JOB_ID"):
481
            c = wmill.Windmill()
482
            value = c.get(
483
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
484
            ).json()
485
        else:
486
            value = (wmill.get_state() or {}).get(key)
487
        if value is not None:
488
            return value
489

490

491
def save_state(keys, value):
492
    if os.environ.get("WM_FLOW_JOB_ID"):
493
        c = wmill.Windmill()
494
        c.post(
495
            f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
496
            json=value,
497
        )
498
    else:
499
        wmill.set_state({**(wmill.get_state() or {}), keys[0]: value})
500

501

502
# "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
503
def short_version(v):
504
    m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
505
    return m.group(0) if m else v
506

507

508
# "EOS64-4.34.9M.swi" -> "4.34.9M"
509
def image_version(file):
510
    m = re.search(r"-(\d+\.\d+\.\d+(\.\d+)?[A-Z]*)\.swi$", file)
511
    return m.group(1) if m else None
512

513

514
# The 128-hex digest in a sha512sum line, a BSD "SHA512 (f) = <hash>" line or verify /sha512 output.
515
def digest(text):
516
    m = re.search(r"\b[0-9a-fA-F]{128}\b", text)
517
    return m.group(0).lower() if m else ""
518

519

520
class DeviceUnreachable(Exception):
521
    pass
522

523

524
class AuthFailure(Exception):
525
    pass
526

527

528
def named(cls, message: str):
529
    return cls(f"{cls.__name__}: {message}")
530

531

532
# pyeapi logs a traceback for every socket error, and the post-check polls a switch that is rebooting.
533
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
534

535

536
def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
537
    eos = node(auth, timeout)
538
    try:
539
        return eos.run_commands(cmds, fmt)
540
    except pyeapi.eapilib.ConnectionError as e:
541
        raise connection_error(auth, eos, e)
542

543

544
# pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
545
# still starting, 5xx) and a 401, the only one with neither.
546
def connection_error(auth, eos, e):
547
    if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
548
        return named(
549
            AuthFailure, f"{auth['host']}: eAPI refused the credential ({e.message})"
550
        )
551
    return named(DeviceUnreachable, f"{auth['host']}: {e.message}")
552

553

554
# host is an address or a URL (https://10.0.0.11:8443); a bare IPv6 address is bracketed. Only https, or http when the
555
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
556
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
557
# self-signed cert).
558
def switch_url(auth: arista_eos):
559
    host = auth["host"]
560
    if "://" not in host:
561
        host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
562
    url = urlsplit(host)
563
    if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
564
        raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
565
    return url
566

567

568
def node(auth: arista_eos, timeout: float = 60):
569
    url = switch_url(auth)
570
    context = ssl.create_default_context()
571
    if auth.get("verify_tls") is False:
572
        context.check_hostname = False
573
        context.verify_mode = ssl.CERT_NONE
574
    return pyeapi.connect(
575
        transport=url.scheme,
576
        host=url.hostname,
577
        port=url.port or auth.get("port") or None,
578
        username=auth["username"],
579
        password=auth["password"],
580
        context=context,
581
        timeout=timeout,
582
        return_node=True,
583
    )
584