Imagine you’re in a change review for VLAN 310. Someone points at leaf-04 and asks, “The freeze ends tomorrow. Can we add the VLAN then?” The playbook ran successfully and the report says HOLD. Before I say yes, I want to know what else could keep that leaf out of the change.

Picking the leaves out of six Nexus switches takes one when clause. Working out what to do with a frozen leaf whose VLAN data is missing means deciding which rule wins. I wrote the same rules in an Ansible playbook and a Python function to see which version I’d want to hand to the engineer covering the next change window.

Is Ansible a general-purpose programming language? No. Ansible is an automation engine for configuration management and orchestration. Its playbooks use a domain-specific language expressed in YAML. YAML is a data serialisation format. To see what that means in practice, we’ll follow a single VLAN number from Python memory to the bytes you could save in a file, then read it back.

Documentation YAML specification · Ansible playbooks · Ansible conditionals

Start with one condition

For this lab I’m using five Nexus leaves and one spine, represented by six sample records in fabric.yml. Everything runs on the control machine. The playbook prints candidates, so you can follow the example without connecting to a switch.

Visual Studio Code showing simple.yml. The play loads fabric.yml, loops over switches and prints a message when item.role equals leaf.

Figure 1. The complete playbook. Line 14 decides whether the debug task runs for each switch.

Look at when: item.role == ‘leaf’. A YAML parser reads a key and a text value. Ansible recognises when, evaluates the value as a Jinja expression for each item and decides whether to run the task. That’s where the conditional gets its meaning.

What it means to serialise a VLAN number

A Python dictionary is already structured while it’s in memory. The problem serialisation solves is how a second process can reconstruct the same value after the first process has gone away. A pointer into the first program’s memory is useless to the second. They need an agreed way to write the data out and read it back.

From memory to text. The dictionary below is a mapping with one entry. The key is the string target_vlan and the value is the integer 310. YAML calls each of these a scalar. The serialiser visits those nodes in a definite order and produces a stream of events. The emitter writes those events as characters. You can reorder the keys of a mapping and preserve its meaning. In a sequence such as [100, 310], the order is part of the data.

import yaml

original = {“target_vlan”: 310}
yaml_text = yaml.safe_dump(original, sort_keys=False)
file_bytes = yaml_text.encode(“utf-8”)
restored = yaml.safe_load(file_bytes.decode(“utf-8”))
quoted = yaml.safe_load(‘target_vlan: “310”‘)

From characters to bytes. PyYAML writes the text target_vlan: 310 followed by a line feed. Encoding that text as UTF-8 gives one byte for each digit, 33 31 30 in hexadecimal. The final 0a is the line feed. If I wrote 310 as a two-byte, big-endian unsigned integer, the same number would occupy just 01 36.

Blog lab terminal showing yaml_roundtrip.py. The digits 310 produce hex bytes 33 31 30. The integer matches a numeric VLAN list and the quoted string does not.

Figure 2. The same VLAN number as a Python value, YAML text and UTF-8 bytes. Quoting 310 changes the type recovered by the loader.

From bytes back to a decision. The reader decodes UTF-8, parses the YAML and constructs new values using its rules for interpreting scalars. With PyYAML’s safe loader, plain 310 becomes an integer. Quoted “310” becomes a string. Only the integer matches an entry in [100, 310]. I changed just the target to “310” and reran both plans. Both changed leaf-02 from KEEP to ADD, even though its snapshot still contained VLAN 310.

Another process can reconstruct its own mapping from those bytes. That’s the value of agreeing on a serialisation format. In this lab Ansible reads the playbook on the control machine. During a live rollout, the module and connection determine what ultimately goes to the switch.

Documentation YAML processing model · Character encodings · PyYAML loading and dumping

Five candidates and a new requirement

From the lab directory, run the command below. The comma after localhost tells Ansible to treat it as an inline inventory. The six switches are records that the play loops over.

ansible-playbook -i localhost, simple.yml

Terminal output. Leaf-01, leaf-02, leaf-03, leaf-04 and leaf-05 are candidates for VLAN 310. Spine-01 is skipped.

Figure 3. The first run lists five leaves and skips spine-01. The grep expression keeps the messages and the skip line visible.

For the original request, that’s a perfectly good result. The next request sounds almost the same. “Give me a change plan for all six switches, with one reason against each.” A skipped task no longer answers the reviewer’s question. The team agrees to use the following order, stopping at the first matching rule.

OrderConditionResult
1The switch has a role other than leaf.SKIP
2The leaf is under a change freeze.HOLD
3The service VLAN snapshot is missing.REVIEW
4The snapshot contains VLAN 310.KEEP
5A snapshot exists and VLAN 310 is absent.ADD

Take leaf-03 and leaf-04. Both have service_vlans: null, which means collection returned no usable snapshot. Only leaf-04 is frozen, so it gets HOLD. Its neighbour gets REVIEW. If I reverse those two checks, I change the report even though the switch data stays exactly the same.

Now compare these two records from the switches list in the input file.

– name: leaf-04
role: leaf
frozen: true
service_vlans: null
– name: leaf-05
role: leaf
frozen: false
service_vlans: []

There’s one more detail in the input. On leaf-05, service_vlans: [] means collection succeeded and found zero service VLANs. The snapshot covers the service VLANs we track and excludes built-in VLANs. An empty list is enough evidence to plan an addition. A missing snapshot is a reason to investigate.

When a playbook becomes a decision tree

If the requirement were just “show me the unfrozen leaves”, I’d keep it in the playbook. Two conditions on the same task read quite naturally. Ansible runs the task when both are true.

when:
– item.role == ‘leaf’
– not item.frozen

For the change plan I want five distinct outcomes and a reason for every switch. I can still do that neatly enough in Ansible. In plan.yml I keep a single reporting task and give it a variable called decision. The task prints the switch name and that variable for every record, including the spine.

Visual Studio Code showing lines 14 to 26 of plan.yml. Jinja checks role, freeze, missing VLAN data and VLAN membership in that order.

Figure 4. The decision variable in plan.yml. The first matching Jinja branch supplies the reason printed for that switch.

Look at line 15. The YAML marker >- introduces a folded text value. Inside that value, Jinja’s if, elif and else choose the message. Line 20 treats an omitted VLAN field and an explicit null alike. Only after that check does the playbook test whether the VLAN is present.

Here’s my gripe. By the time I’m explaining why line 18 must come before line 20, I’m programming a decision tree through a playbook. Moving the Jinja into a separate template would tidy the YAML. I’d still need to prove what happens when two rules match the same switch.

The same decision in one Python function

I keep the same YAML input and move just the decision into vlan_decision(switch, target_vlan). It accepts one switch record and a VLAN number and returns one reason. The small main() function in plan.py reads the file with PyYAML, calls the function for each switch and prints the result.

Visual Studio Code showing vlan_decision in plan.py. Four explicit checks return SKIP, HOLD, REVIEW or KEEP. The final return is ADD.

Figure 5. The entire decision function in plan.py. Each return ends the evaluation for that switch.

Read it from the top. A spine exits on the first return. A frozen leaf exits on the second. The remaining devices reach the snapshot check. I used if vlans is None deliberately. Writing if not vlans would also catch an empty list and incorrectly send leaf-05 for review.

This is the bit that makes Python worth it for me. I can give the function the exact combination that worried the reviewer and check the outcome directly. Here’s that test from test_plan.py.

def test_freeze_wins_over_missing_snapshot(self):
switch = {“role”: “leaf”, “frozen”: True, “service_vlans”: None}
self.assertEqual(vlan_decision(switch, 310), “HOLD – change freeze”)

If someone later moves the missing-data check above the freeze check, this test fails. The next engineer can see which behaviour changed without opening a switch session or running an entire playbook.

I ran all eight unit tests. They cover overlapping rules, missing and empty data, a VLAN already present, and a different target VLAN. Ansible can be tested too. What I gain here is a function I can call directly with any one of those inputs.

The lab terminal running python -m unittest -q in a virtual environment. Eight tests ran and the result was OK.

Figure 6. All eight Python unit tests pass, including the case where a freeze and a missing snapshot overlap.

What both tools actually returned

I ran both implementations against the same fabric.yml. The first command below filters Ansible’s normal console output down to its message lines. The second runs the Python tool directly. The first pass found five candidates. The finished plan proposes two additions, on leaf-01 and leaf-05.

Terminal comparison. Leaf-01 ADD, leaf-02 KEEP, leaf-03 REVIEW, leaf-04 HOLD, leaf-05 ADD and spine-01 SKIP. Both implementations print the same six decisions.

Figure 7. The Ansible messages and the Python report agree on the decision and the reason for all six records.

Where I draw the line

The point I’m making here is that there comes a point when the decision tree becomes so complex that you have to trace several branches just to explain why one switch was skipped. That’s when I’d move the decision into Python. I can give the next engineer one function to read and a test showing which rule wins when a switch meets two conditions.

Back to leaf-04. I lifted the freeze on a copy of its record and ran both versions again. It moved from HOLD to REVIEW because we still had no VLAN snapshot. My answer to the change team would be, “Collect the VLANs first. If 310 is already there, we can leave this switch alone.” Once we’ve agreed which leaves need the change, I’d use Ansible to carry out the rollout.

Documentation Python unittest · Cisco NX-OS VLAN module

Leave a Reply

Trending