Ansible Pygments
Ansible Pygments provides a Pygments lexer specifically designed to highlight Ansible output. It can be integrated into any application that uses Pygments for syntax highlighting, such as Sphinx documentation. The lexer is globally registered under the name `ansible-output` and also offers a Pygments style. The project is actively maintained with regular, typically minor, releases.
Common errors
-
Pygments lexer 'ansible-output' not found
cause The `ansible-pygments` package is not installed in the Python environment where Pygments is attempting to load the lexer, or the installation is corrupted.fixEnsure `ansible-pygments` is correctly installed: `pip install ansible-pygments`. If using a virtual environment, activate it before installing. -
Exception: no lexer for alias 'ansible' found
cause The user attempted to reference the Ansible output lexer using the incorrect alias, `ansible`, instead of the globally registered name `ansible-output`.fixAlways use the full registered name `ansible-output` when referencing the lexer, e.g., `get_lexer_by_name('ansible-output')` or `.. code-block:: ansible-output` in Sphinx.
Warnings
- gotcha Pygments, and by extension `ansible-pygments`, can be susceptible to Denial-of-Service (DoS) attacks if processing arbitrary, untrusted user inputs. Crafted inputs might lead to long processing times or excessive memory usage.
- gotcha As a 0.x.x version library, while actively maintained, `ansible-pygments` may introduce minor API changes or breaking modifications between patch or minor versions without adhering to strict semantic versioning (e.g., a 0.1.x to 0.2.x bump might include breaking changes).
Install
-
pip install ansible-pygments
Imports
- AnsibleOutputLexer
from ansible_pygments.lexer import AnsibleOutputLexer
- get_lexer_by_name
from pygments.lexers import get_lexer_by_name lexer = get_lexer_by_name('ansible-output')
Quickstart
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
ansible_output = """
[WARNING]: Unable to find '/nosuchfile' in expected paths (use -vvvvv to see paths)
ok: [localhost] => {
"msg": "Hello from Ansible!"
}
"""
try:
lexer = get_lexer_by_name('ansible-output')
formatter = HtmlFormatter()
highlighted_html = highlight(ansible_output, lexer, formatter)
print(highlighted_html)
except Exception as e:
print(f"Error highlighting: {e}")
print("Make sure 'ansible-pygments' and 'Pygments' are installed.")