yamllint
yamllint is a linter for YAML files written in Python, version 1.38.0. It checks not only for syntax validity but also for common weirdnesses like key repetition and cosmetic issues such as line length, trailing spaces, and indentation. The project is actively maintained with regular releases.
Warnings
- breaking yamllint has progressively dropped support for older Python versions. As of 1.38.0, Python 3.9 is no longer supported, and Python 3.8 was dropped in 1.36.0. Users on older Python environments will need to upgrade their Python version or use an older yamllint version.
- gotcha By default, the `yamllint` CLI exits with code 1 only if errors are found, not warnings. This can lead to CI/CD pipelines passing silently even with warnings. To make warnings also cause a non-zero exit code, use the strict mode.
- gotcha yamllint automatically discovers and loads configuration files named `.yamllint`, `.yamllint.yaml`, or `.yamllint.yml` in the current working directory or any parent directory. This implicit loading can lead to unexpected linting rules being applied if a configuration file exists upstream that you are unaware of or did not intend to use.
- breaking The API for `linter.run` experienced a change in version 1.35.0 regarding how file ignoration was handled, which was then reverted in 1.35.1. If you programmatically interact with `linter.run` and rely on specific file path handling or ignoration behavior, this version range could introduce unexpected results.
Install
-
pip install yamllint
Imports
- YamlLintConfig
from yamllint.config import YamlLintConfig
- linter
from yamllint import linter
- LintProblem
from yamllint.linter import LintProblem
Quickstart
import io
from yamllint.config import YamlLintConfig
from yamllint import linter
yaml_content = """
key: value
another_key: with_trailing_spaces
nested: item
"""
# Use a default configuration or load a custom one
config_string = "extends: default\nrules:\n trailing-spaces: enable\n indentation: enable"
conf = YamlLintConfig(content=config_string)
# Lint the YAML content from a string buffer
problems = linter.run(io.StringIO(yaml_content), conf)
found_issues = []
for p in problems:
found_issues.append(f"Line {p.line}, Column {p.column}: {p.desc} (Rule: {p.rule})")
if found_issues:
print("YAML linting issues found:")
for issue in found_issues:
print(issue)
else:
print("No YAML linting issues found.")