**Approach (brief)**- Connect with NAPALM, read existing VLANs, determine which of VLANs 100/apps and 101/db are missing or mismatched, then apply only necessary changes. Support dry-run that prints planned config instead of committing.**Sample NAPALM pseudo-code (Python)**python
from napalm import get_network_driver
def ensure_vlans(host, username, password, dry_run=True):
driver = get_network_driver("ios") # example
device = driver(hostname=host, username=username, password=password)
wanted = {100: "apps", 101: "db"}
try:
device.open() # connect
existing = device.get_vlans() # returns dict {id: { 'name': ... }}
to_create = {}
for vid, name in wanted.items():
if str(vid) not in existing or existing[str(vid)]['name'] != name:
to_create[vid] = name
if not to_create:
print("No changes required.")
return
# build candidate configuration (platform-agnostic pseudo)
for vid, name in to_create.items():
device.load_merge_candidate(config=f"vlan {vid}\n name {name}\n")
diff = device.compare_config()
if not diff:
print("No diff after loading candidate; nothing to commit.")
device.discard_config()
return
if dry_run:
print("DRY-RUN: planned changes:\n", diff)
device.discard_config()
else:
print("Committing changes:\n", diff)
device.commit_config()
except Exception as e:
# granular error handling in production: catch connection/auth/timeouts separately
print(f"Error: {e}")
try:
device.discard_config()
except Exception:
pass
finally:
try:
device.close()
except Exception:
pass
**Key NAPALM calls & control flow**- device.open(), device.get_vlans(), device.load_merge_candidate(), device.compare_config(), device.commit_config(), device.discard_config(), device.close()- Idempotency: check existing state before loading candidate. Dry-run: print diff and discard instead of commit.- Error handling: try/except around connect/apply, ensure discard and close in finally.