Skip to content

Linting and testing network automation code

The GitLab pipeline article lists the build stage's job as "lint YAML, lint Ansible, syntax-check playbooks" and leaves it at that. This article opens up that line: what each tool actually catches, why a green --syntax-check is not the same as working code, how to unit-test the pure logic in your automation without a lab, and how to run all of it on every commit so a broken change never reaches the pipeline in the first place.

Two kinds of correctness

There is a distinction worth drawing before any tool. Validating your code and validating the network are different jobs, caught at different stages, by different tools:

  • Does the code hold together? Is the YAML well-formed, the playbook free of deprecated modules and footguns, the rendering function producing the string you expect? This needs no device — it is static analysis and unit tests, and it belongs in the build stage.
  • Did the change do the right thing to the network? This needs a real (or simulated) device, and it is exactly what change validation with pyATS does in the post-validation stage.

Linting and unit tests are fast, cheap, and run anywhere; pyATS is slower and needs a testbed. Front-load the cheap checks. Most mistakes — a typo'd key, a wrong indent, a deprecated module, a template that drops a variable — are code problems a linter or a unit test will catch in milliseconds, long before you spend a lab reservation discovering them.

yamllint: the formatting floor

Almost everything in network automation is YAML — playbooks, inventory, group_vars, CI definitions, Docker Compose files. yamllint checks that it parses and that it is consistently formatted: indentation, trailing spaces, duplicate keys, line length, and the classic "Norway problem" where an unquoted no becomes the boolean false. It knows nothing about Ansible; it only cares that the document is valid, tidy YAML.

Run it across the repo, and keep a config so the rules match your house style instead of the strict defaults:

# .yamllint
extends: default
rules:
  line-length:
    max: 120
  truthy:
    allowed-values: ["true", "false"]   # force quoted booleans, dodge the Norway problem
  comments:
    min-spaces-from-content: 1
yamllint .

A non-zero exit means a problem; in CI that fails the stage and stops the change going further.

ansible-lint: semantics and best practice

yamllint proves the file is valid YAML. ansible-lint proves the playbook is sound: it flags deprecated or removed modules, tasks that use command/shell where a module exists, missing name: keys, and — importantly for this site's recurring theme — patterns that break idempotency. The no-changed-when rule, for instance, catches a command task that will report changed on every run because nothing tells Ansible when it actually changed anything.

ansible-lint groups its rules into profiles that get progressively stricter — min, basic, moderate, safety, shared, and production — so you can adopt it gradually and raise the bar over time. The production profile is the strictest and is the gate Red Hat uses for certified content (profiles reference):

# lint the playbooks directory at the strictest profile
ansible-lint --profile production playbooks/

Note that ansible-lint depends on ansible-core but not on your collections, so in CI (and in the pre-commit hook below) you have to install cisco.ios, ansible.netcommon, and anything else your playbooks import, or the lint run can't resolve the modules it's checking.

--syntax-check is not a test

It is tempting to treat a passing ansible-playbook --syntax-check as proof the playbook works. It isn't.

ansible-playbook playbooks/deploy.yml --syntax-check

What it does: parse every referenced file and resolve roles, includes, and imports, then exit. What it does not do: run anything, or reason about whether your tasks are correct. A playbook that references a variable that is never defined, targets the wrong interface, or sets a VLAN that doesn't exist will pass --syntax-check cleanly — the YAML is well-formed and the modules exist, so there is nothing for a parser to object to. Syntax-check answers "will Ansible load this?"; it says nothing about "will this do the right thing?" (Red Hat on ansible-lint vs. syntax-check). That is why the build stage runs all three — yamllint, ansible-lint, and --syntax-check — and why none of them replaces the dry-run and pyATS checks downstream.

Unit-test the logic that has no device in it

A surprising amount of automation is pure data transformation: rendering a Jinja2 template from source-of-truth data, or parsing CLI output into a dictionary. That code takes an input and returns an output with no network involved — which makes it perfectly suited to a plain pytest unit test. You assert on the output string, no lab required.

Say you have a helper that renders an interface stanza:

# render.py
from jinja2 import Environment, FileSystemLoader, StrictUndefined


def render_interface(data: dict) -> str:
    env = Environment(
        loader=FileSystemLoader("templates"),
        trim_blocks=True,
        lstrip_blocks=True,
        undefined=StrictUndefined,   # fail loudly on a missing variable
    )
    return env.get_template("interface.j2").render(**data)

The test proves both the happy path and that a missing variable is caught, not silently rendered blank:

# test_render.py
import pytest
from jinja2 import UndefinedError

from render import render_interface


def test_vlan_is_rendered():
    config = render_interface({"name": "GigabitEthernet1", "vlan": 10})
    assert "interface GigabitEthernet1" in config
    assert "switchport access vlan 10" in config


def test_missing_vlan_raises():
    # StrictUndefined turns a missing key into an error instead of an empty line
    with pytest.raises(UndefinedError):
        render_interface({"name": "GigabitEthernet1"})
pytest -q

These tests run in milliseconds, in CI or on a laptop, and they lock in the behaviour that matters most: the config text you ship is the config text you meant. The same approach covers a parser — feed it a saved show output fixture and assert on the dictionary it returns, so you catch a broken parse without touching a device.

Run it before CI, not only in CI

The pipeline is a backstop, not the first line of defence. The cheapest place to catch a problem is before the commit exists, with a pre-commit hook that runs the same linters locally. This is the same mechanism the secure coding article uses to block leaked secrets — here it also enforces formatting and lint:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/adrienverge/yamllint
    rev: v1.37.1
    hooks:
      - id: yamllint
  - repo: https://github.com/ansible/ansible-lint
    rev: v25.9.2
    hooks:
      - id: ansible-lint
        additional_dependencies:
          - ansible-core

Install it once with pre-commit install, and every git commit runs the hooks against your staged files; a failure blocks the commit until you fix it. Pin the rev tags and bump them with pre-commit autoupdate rather than copying whatever is newest — an unpinned linter that changes its rules is its own source of surprise pipeline failures. Because someone can always bypass a local hook, run the identical checks in CI as well; the two together mean a lint rule is enforced whether or not the author remembered to install the hook.

Where it fits in the pipeline

Mapped onto the four-stage pipeline, these checks are the front half:

Stage Tool Question answered
Build yamllint, ansible-lint, --syntax-check, pytest Is the code well-formed and sound?
Pre-validation ansible-playbook --check --diff, terraform plan, CML Would this change do what I expect, without touching prod?
Post-validation pyATS / Genie Does the live network now match intent?

One rule survives all of it: when a check goes red, fix the code it flagged — never disable the test or loosen the linter to force the job green. A failing lint rule or assertion is a working test doing its job.

Key takeaways

  • Validating your code and validating the network are different jobs. Linting and unit tests are cheap, device-free, and belong in the build stage; pyATS validates the live network in post-validation. Front-load the cheap checks.
  • yamllint enforces valid, consistent YAML (and quotes your booleans); ansible-lint enforces playbook semantics and best practice, including idempotency rules like no-changed-when, with profiles from min to production.
  • --syntax-check only proves the playbook loads — it runs nothing and catches no logic errors, so it never replaces lint or real tests.
  • Unit-test the pure logic — rendering and parsing take an input and return an output, so a plain pytest can assert on the result with no device in the loop.
  • Shift the checks left with a pre-commit hook so problems are caught before the commit, and run the same checks in CI as a backstop. Pin your tool versions.

Sources: ansible-lint documentation and its profiles reference, Red Hat — Ansible Lint, yamllint, pytest, pre-commit.