Ansible Lint

26.4.0 · active · verified Fri Apr 10

Ansible Lint is a command-line tool that checks Ansible playbooks, roles, and collections for practices and behavior that could potentially be improved. It helps maintain code quality, enforce best practices, and identify common pitfalls in Ansible automation. The current version is 26.4.0, and it maintains an active release cadence, often with multiple updates per month to incorporate new rules and keep pace with Ansible Core development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically use `ansible-lint` to check a playbook. It creates a temporary Ansible playbook file with known linting issues, initializes the `App` with specific options, runs the linting process, and prints any identified issues. The example also includes cleanup of the temporary files.

import os
import tempfile
from pathlib import Path
from ansiblelint.app import App
from ansiblelint.config import Options

# Create a temporary playbook file for linting
playbook_content = """
---
- name: Example playbook with common linting issues
  hosts: localhost
  tasks:
    - name: Using command module directly (LINT: no-shell-command)
      ansible.builtin.command: echo "hello world"
    - name: Insecure default permissions for file (LINT: risky-file-permissions)
      ansible.builtin.file:
        path: /tmp/testfile.txt
        state: touch
        mode: "0777" # Risky permissions
"""

temp_dir = Path(tempfile.mkdtemp())
playbook_path = temp_dir / "playbook.yml"
with open(playbook_path, "w") as f:
    f.write(playbook_content)

try:
    # Configure linting options
    options = Options()
    # Prevent App from configuring logging globally, for cleaner output in example
    options.configure_logger = False
    # Specify the file(s) to lint
    options.lintables = [str(playbook_path)]
    # Set up app and run lint
    app = App(options)
    matches = app.run()

    print(f"Linting results for {playbook_path.name}:")
    if matches:
        for match in matches:
            print(f"- [{match.rule_id}] {match.message} (File: {match.filename}, Line: {match.linenumber})")
    else:
        print("No linting issues found.")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up the temporary directory and file
    if temp_dir.exists():
        for item in temp_dir.iterdir():
            item.unlink()
        temp_dir.rmdir()

view raw JSON →