Since Lesson 3.4, Aurora Store has had conventions: FQCN for every module, task names in the imperative and capitalized, true/false, mode in quotes, variables prefixed with their role's name… and in Lesson 9.1 you gathered them in a table. But until now only one thing has been policing them: your attention. In a team, that doesn't scale: everyone reviews differently, oversights slip through pull requests, and style discussions eat up review time. In Lesson 8.3 you added a lint stage with yamllint and ansible-lint to the CI, but as informational only (continue-on-error: true), pending this lesson. Now you're going to configure both tools thoroughly: install them with pinned versions, write a .yamllint compatible with ansible-lint, choose a rule profile in .ansible-lint, learn the most common rules and how to fix them (by hand or with --fix), fix the repository's real warnings, check the code before each commit with pre-commit and, finally, make the CI reject code that doesn't follow the rules.

Contents

  1. Automated review: what it gives you and what it doesn't
  2. yamllint and ansible-lint: two tools, two levels
  3. Installation with pinned versions
  4. Configuring yamllint
  5. Configuring ansible-lint: profiles, rule lists and exclusions
  6. The most common rules and how to fix them
  7. Automatic fixing with ansible-lint --fix
  8. The real warnings in aurora-infra
  9. Checking before each commit: pre-commit
  10. The CI stops being informational

  1. Automated review: what it gives you and what it doesn't

A linter is a program that analyzes code without running it and flags whatever breaks a set of rules. In Ansible, that covers three kinds of problems:

Kind Example Consequence if it goes undetected
Latent errors mode: 644 without quotes (interpreted as decimal), become_user without become Wrong permissions, tasks that don't escalate as you expect
Bad practices command where there's a module, tasks without changed_when, ignore_errors Non-idempotent code, false change reports
Style Uncapitalized names, inconsistent indentation, modules without FQCN Code that's hard to read and review; ambiguity between collections

What a linter doesn't do: check that the code works. A task can be flawless for ansible-lint and still misconfigure a service. For that you need tests that run the code, which you'll see in Lesson 9.5. The linter is the first layer: cheap, fast and with no servers.

  1. yamllint and ansible-lint: two tools, two levels

yamllint ansible-lint
What it understands Generic YAML Ansible: playbooks, roles, tasks, variables, meta/, collections
What it checks Syntax and formatting: indentation, line length, spaces, booleans, duplicate keys, --- Ansible best practices (more than 40 rules) and the YAML formatting too (it uses yamllint internally)
Which files All .yml/.yaml files (including the Gitea workflows, the manifests, ansible-navigator.yml) Ansible content; it detects each file's type by its path
Configuration .yamllint .ansible-lint

ansible-lint includes the yamllint checks in its yaml rule and reads the same .yamllint. Even so, Aurora runs both: yamllint checks all the YAML in the repository (including files that aren't Ansible) and ansible-lint checks what's specific to Ansible.

  1. Installation with pinned versions

3.1. The same versions everywhere

A linter without a pinned version is a source of surprises: a new version adds rules or changes criteria, and the CI starts failing on a Monday without anyone having touched the code. That's why the versions are pinned in ci/requirements.txt (the file the CI has used since Lesson 8.3) and you use the same file on your computer.

There's an important detail about versions. ansible-core 2.17, the series Aurora uses, has reached the end of its support cycle, and recent versions of the tools explicitly exclude it in their dependencies: ansible-lint since 26.8.0 and its ansible-compat library since 26.8.0 declare ansible-core!=2.17.*. If you left the versions unpinned, pip would backtrack on its own until it found a compatible combination, or it would fail. The right thing to do is to explicitly pin the latest version compatible with your ansible-core:

# Tools for the aurora-infra continuous integration (Lessons 8.3 and 9.4).
# ansible-core: the same series as the laptop and aurora-ee.
ansible-core>=2.17,<2.18
# Linting. ansible-lint and ansible-compat 26.6.0 are the latest versions
# that support ansible-core 2.17; when ansible-core is upgraded, they're reviewed together.
yamllint==1.38.0
ansible-lint==26.6.0
ansible-compat==26.6.0
# AWX client: the same version as the server (AWX 24.6.1).
awxkit==24.6.1

These are the versions current at the time of writing this lesson; check the latest ones compatible with your ansible-core series (pip index versions ansible-lint and each version's metadata on PyPI). And note an important pending task in the CHANGELOG.md: upgrading ansible-core to a supported series (with the corresponding review of collections, the EE and the tools), which is part of the normal maintenance of a project like this one.

3.2. On your computer: a project virtual environment

Installing ansible-lint with pipx install ansible-lint would bring its own copy of ansible-core (the latest), different from the one in your Ansible pipx: the results might not match the CI's. Use a project virtual environment, like the CI does (.venv/ has been in .gitignore since Lesson 8.3):

cd ~/aurora-infra
python3 -m venv .venv
.venv/bin/pip install -r ci/requirements.txt
.venv/bin/yamllint --version
.venv/bin/ansible-lint --version
yamllint 1.38.0
ansible-lint 26.6.0 using ansible-core:2.17.x ansible-compat:26.6.0 ruamel-yaml:... ruamel-yaml-clib:...

ansible-lint --version tells you which ansible-core it analyzes with: it must be 2.17, as in the rest of the project. To avoid typing the path every time, activate the environment in your session (source .venv/bin/activate) while you're linting.

  1. Configuring yamllint

ansible-lint requires some specific values in the yamllint configuration (otherwise it warns that the configuration is incompatible): comments with at least one space of separation, comments-indentation disabled, at most one space inside braces, and octals forbidden. .yamllint in the root:

---
# yamllint configuration for aurora-infra (Lesson 9.4), compatible with ansible-lint.
extends: default

ignore: |
  .venv/
  galaxy_roles/
  collections/ansible_collections/
  ee/context/
  artifacts/
  lab/awx/
  inventories/staging/hosts-terraform.yml
  playbooks/group_vars/*/vault.yml

rules:
  line-length:
    max: 160
  comments:
    min-spaces-from-content: 1
  comments-indentation: false
  braces:
    max-spaces-inside: 1
  octal-values:
    forbid-implicit-octal: true
    forbid-explicit-octal: true
  truthy:
    allowed-values: ["true", "false"]
    check-keys: false

Piece by piece:

  • extends: default: starts from yamllint's default configuration (indentation consistent with indented lists, --- at the beginning, no trailing spaces, a final blank line, no duplicate keys…), which matches Aurora's conventions.
  • ignore: paths that aren't checked, using .gitignore syntax. Third-party or generated content (galaxy_roles/, installed collections, the EE context, the generated staging inventory), the Kubernetes manifests in lab/awx/ (written in the usual Kubernetes style, without indentation in lists, and maintained separately) and the encrypted files, whose content isn't structured YAML.
  • line-length: max: 160: the default (80) is too strict for Jinja expressions; 160 is the one ansible-lint uses.
  • comments, comments-indentation, braces, octal-values: the values ansible-lint requires. Forbidding octals prevents the classic mode: 0644 without quotes mistake (Lesson 3.2).
  • truthy: only true and false as booleans (no yes, no, True). check-keys: false avoids a false positive: Gitea workflows start with the on: key, which in YAML 1.1 is a boolean, but which Gitea (and GitHub) read as text.

Run it:

.venv/bin/yamllint .

Each warning shows the file, line, column, level and rule:

./playbooks/group_vars/webservers.yml
  9:22      error    too many spaces after colon  (colons)

  1. Configuring ansible-lint: profiles, rule lists and exclusions

5.1. The profiles

Instead of choosing rules one by one, ansible-lint groups its rules into cumulative profiles: each one includes all the rules of the previous one.

Profile What it adds (representative rules) What for
min Parsing and syntax errors (syntax-check, load-failure) The bare minimum: the code can be loaded
basic command-instead-of-module, command-instead-of-shell, deprecated-module, key-order, literal-compare, jinja, no-free-form, partial-become, role-name, schema, name, var-naming, yaml Style and common mistakes
moderate name[template], name[imperative], name[casing], spell-var-name Well-crafted task names
safety avoid-implicit, latest, package-latest, risky-file-permissions, risky-octal, risky-shell-pipe Risks to the systems
shared galaxy, ignore-errors, meta-incorrect, meta-no-tags, no-changed-when, no-handler, no-relative-paths, max-tasks, max-block-depth… Content for sharing (publishable roles and collections)
production fqcn, sanity and some rules still planned "Certifiable" quality content

You can see the exact list for your version with ansible-lint --list-profiles and all the rules with ansible-lint -L. Aurora chooses production: it's the most demanding profile, the one applied to content published on Automation Hub, and Aurora has already followed almost all its rules since the beginning of the course. Starting at the top in a project that's already tidy is easier than moving up a profile later.

In a legacy project, with hundreds of warnings, the sensible approach is to start with basic or moderate, fix things, and move up a profile in stages. Another option is ansible-lint --generate-ignore, which creates a .ansible-lint-ignore file with all the current warnings (file and rule per line): that way the CI only fails on new ones, and the debt is reduced by deleting lines from that file.

5.2. The .ansible-lint file

---
# ansible-lint configuration for aurora-infra (Lesson 9.4).
profile: production

# Dependencies are installed before linting (ansible-galaxy with the requirements).
offline: true

exclude_paths:
  - .venv/
  - .gitea/
  - galaxy_roles/
  - collections/ansible_collections/
  - ee/context/
  - artifacts/
  - lab/
  - terraform/
  - inventories/staging/hosts-terraform.yml
  - playbooks/group_vars/*/vault.yml

# Optional rules that Aurora enables in addition to the profile.
enable_list:
  - no-log-password       # "password" parameters without no_log (Lesson 9.2)
  - role-argument-spec    # every role must have meta/argument_specs.yml (Lesson 4.6)

# Rules that only warn (they don't make the check fail).
warn_list:
  - experimental
  - jinja[spacing]

# Rules disabled entirely: none. An exception is justified on its own line with noqa.
skip_list: []

# File types that ansible-lint doesn't recognize by their path alone.
kinds:
  - inventory: "**/inventories/*/hosts.yml"
Key Meaning
profile Rule profile
offline Don't try to install the requirements.yml dependencies by itself (you already install them, and in the CI they're installed beforehand)
exclude_paths Paths that aren't checked: third-party content, generated content, non-Ansible content (the workflows are checked by yamllint; the lab and Terraform aren't Ansible) and the encrypted files
enable_list Optional (opt-in) rules that are enabled
warn_list Rules shown as warnings that don't cause failures: experimental (new rules being trialed) and jinja[spacing] (which the tool itself still considers prone to false positives)
skip_list Rules disabled entirely. Better left empty: disabling a rule across the whole project also hides the cases where it would be right
kinds Maps paths to file types. ansible-lint recognizes playbooks/*.yml, roles/*/tasks/*.yml, group_vars/ or inventory/ by their path, but not the inventories/ name Aurora adopted in Lesson 9.1

5.3. Justified exceptions: # noqa

When a rule isn't right in a specific case (and only then), it's silenced on that line with a # noqa: <rule> comment and an explanation:

    - name: Re-read the local facts if they have changed
      ansible.builtin.setup:
        filter: ansible_local
      # It must run at this point, not at the end of the play (decision from Lesson 5.1).
      when: common_local_facts is changed  # noqa: no-handler

The comment goes on the line the warning points to (ansible-lint tells you the line). The explanation is mandatory by team convention: whoever reads the code a year from now must know why the exception was made. A pull request review that finds a noqa without a justification should reject it.

  1. The most common rules and how to fix them

This table summarizes the rules that come up most often in real projects, with the typical mistake and the fix. You've already applied almost all of them in Aurora by convention; now they have names.

Rule Wrong Right
fqcn[action-core] apt: ansible.builtin.apt:
fqcn[action] ufw: community.general.ufw:
name[missing] Task without name name: Install nginx
name[casing] name: install nginx name: Install nginx
name[template] name: "{{ item }} installed" name: "Install {{ item }}" (Jinja only at the end)
name[play] Play without name name: Configure the Aurora Store web servers
no-changed-when command: cmd: nginx -t and nothing else Add changed_when: false (if it only queries) or a real condition
risky-file-permissions template: without mode mode: "0644"
yaml[octal-values] mode: 0644 mode: "0644"
yaml[truthy] become: yes become: true
var-naming[no-role-prefix] In the nginx role: register: config_result register: nginx_config_result
var-naming[pattern] myVariable my_variable
jinja[spacing] "{{item.name}}" "{{ item.name }}"
no-free-form command: systemctl is-active nginx command: + cmd: systemctl is-active nginx
command-instead-of-module command: cmd: systemctl restart nginx ansible.builtin.systemd_service
command-instead-of-shell shell: with no pipes or redirections command:
risky-shell-pipe shell: cmd: a | b Add set -o pipefail && at the beginning (with executable: /bin/bash)
literal-compare when: x == true when: x
package-latest state: latest state: present (upgrades handled in a controlled way, as in upgrade.yml)
partial-become become_user: postgres without become in the same task Add become: true next to become_user
no-handler when: result is changed A handler (or a justified # noqa)
key-order[task] block: before name/when name, when, tags… and block at the end (Aurora's convention, Lesson 5.6)
ignore-errors ignore_errors: true failed_when with the specific condition (Lesson 5.5)
no-relative-paths src: ../templates/x.j2 src: x.j2 (standard lookup in templates/)
no-log-password user: with password and no no_log no_log: true
meta-incorrect author: your name (values from role init) Real data
schema[meta] min_ansible_version: 2.17 min_ansible_version: "2.17"

To learn more about a rule, ansible-lint -L lists them, and each warning includes a link to its documentation.

  1. Automatic fixing with ansible-lint --fix

Many rules have an automatic fix: fqcn, yaml (partly), jinja[spacing], key-order, name[casing], no-free-form, partial-become, no-jinja-when, command-instead-of-shell, deprecated-local-action, no-log-password… The --fix option (formerly --write) rewrites the files:

git status                       # the working tree must be clean
.venv/bin/ansible-lint --fix
git diff                         # review ALL the changes before accepting them

Three precautions:

  1. A clean tree before you start: that way git diff shows only what the tool has changed, and git checkout . undoes everything if you're not convinced.
  2. Review the diff: --fix rewrites the YAML files with its own formatter, which may change quotes, line breaks in long strings or the position of comments. It usually gets it right, but it doesn't always respect the team's preferences.
  3. Restrict it if necessary: --fix=fqcn,partial-become fixes only those rules; the write_list key in .ansible-lint sets the default list.

After --fix, run ansible-lint again (without --fix) and, above all, ansible-playbook playbooks/site.yml --check --diff: a style fix must not change anything on the servers.

  1. The real warnings in aurora-infra

8.1. The first run

.venv/bin/yamllint .
.venv/bin/ansible-lint

yamllint shouldn't show anything: Aurora's code has followed its conventions since Lesson 3.2. If something shows up, it's usually a trailing space or a missing final newline in some file edited in a hurry; fix it by hand.

ansible-lint does find things. In the course's reference repository these warnings appear (yours may vary slightly depending on what you wrote in the exercises):

no-handler: Tasks that run when changed should likely be handlers.
roles/common/tasks/main.yml:107 Task/Handler: Re-read the local facts if they have changed

no-handler: Tasks that run when changed should likely be handlers.
roles/docker/tasks/main.yml:24 Task/Handler: Update the package cache if the repository has changed

partial-become[task]: become_user should have a corresponding become at the same level as itself.
roles/postgresql/tasks/users.yml:2 Task/Handler: Create the PostgreSQL users

partial-become[task]: become_user should have a corresponding become at the same level as itself.
roles/postgresql/tasks/users.yml:15 Task/Handler: Create the databases

Failed: 4 failure(s), 0 warning(s) on 147 files. Profile 'production' was required, but 'min' profile passed.

The last line is useful: it tells you which profile the code meets today. The goal is for it to say Passed: 0 failure(s), 0 warning(s) with the production profile. If any of the roles you created with ansible-galaxy role init in Module 8 still has the example values in meta/main.yml (author: your name, company: your company (optional), license: license (GPL-2.0-or-later, MIT, etc)), you'll also see meta-incorrect warnings: replace them with Aurora's details, as in the Module 4 roles.

8.2. partial-become: a real fix

The tasks in roles/postgresql/tasks/users.yml use become_user: postgres and depend on the play having become: true. It works in Aurora, but the role, read on its own, doesn't say so; and if someone used it in a play without become, the task would run as the connection user, with no warning. The fix is explicit and safe (you can leave it to --fix=partial-become):

- name: Create the PostgreSQL users
  community.postgresql.postgresql_user:
    name: "{{ item.name }}"
    password: "{{ item.password | default(omit) }}"
    port: "{{ postgresql_port }}"
    state: present
  become: true
  become_user: postgres
  loop: "{{ postgresql_users }}"
  loop_control:
    label: "{{ item.name }}"
  no_log: true

(And the same in "Create the databases".) Nothing changes on the servers: the play was already escalating.

8.3. no-handler: two justified exceptions

The rule suggests turning tasks conditioned on is changed into handlers. In Aurora's two cases that would not be correct:

  • common, "Re-read the local facts if they have changed": in Lesson 5.1 you decided to keep it as a task because the new facts must be available immediately, not at the end of the play.
  • docker, "Update the package cache if the repository has changed": the cache must be updated before the next task, which installs Docker from that repository. A handler would run too late (or would require a flush_handlers right afterwards, which is more complicated for the same result).

They're silenced with their justification:

    - name: Update the package cache if the repository has changed
      ansible.builtin.apt:
        update_cache: true
      # The cache must be updated before installing Docker from the new repository.
      when: docker_repo is changed  # noqa: no-handler

8.4. Repeat until it passes

.venv/bin/ansible-lint
Passed: 0 failure(s), 0 warning(s) on 147 files. Last profile that met the validation criteria was 'production'.

Check that nothing has changed on the servers (ansible-playbook playbooks/site.yml --check --diff: changed=0) and commit together with the configuration:

git add .yamllint .ansible-lint ci/requirements.txt roles/
git commit -m "Quality: yamllint and ansible-lint configuration (production profile) and warning fixes"

  1. Checking before each commit: pre-commit

9.1. Why before the commit

The CI warns you after you push the change: several minutes of waiting and a fix-up commit in the history. It's better to catch problems on your computer, at the moment you commit. That's what Git hooks are for, and pre-commit is the standard tool for managing them: it reads a list of checks from a versioned file and runs them on the files you're about to commit.

pipx install pre-commit

9.2. A check of our own: the vaults must be encrypted

Before the configuration, a small script that protects against a serious mistake: committing a decrypted vault.yml (for example, after an ansible-vault decrypt to check something). ci/check-vault.sh:

#!/usr/bin/env bash
# Fails if any of the files received is not encrypted with ansible-vault (Lesson 9.4).
status=0
for file in "$@"; do
  if ! head -n 1 "$file" | grep -q '^\$ANSIBLE_VAULT;'; then
    echo "ERROR: $file is not encrypted with ansible-vault"
    status=1
  fi
done
exit "$status"
  • It receives a list of files as arguments ("$@") and checks that the first line is the Vault header.
  • It exits with code 1 if any of them isn't; pre-commit and the CI interpret that code as a failure.

Give it execute permission (Git keeps that permission): chmod +x ci/check-vault.sh.

9.3. .pre-commit-config.yaml

---
# Checks before each commit (Lesson 9.4).
# Installation: pipx install pre-commit && pre-commit install
# Requires the .venv environment with ci/requirements.txt (the same versions as the CI).
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-merge-conflict
      - id: check-added-large-files
      - id: detect-private-key

  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1
    hooks:
      - id: gitleaks

  - repo: local
    hooks:
      - id: vault-encrypted
        name: vault.yml files are encrypted
        entry: ci/check-vault.sh
        language: script
        files: (^|/)vault\.yml$

      - id: yamllint
        name: yamllint
        entry: .venv/bin/yamllint --strict
        language: system
        types: [yaml]

      - id: ansible-lint
        name: ansible-lint
        entry: .venv/bin/ansible-lint
        language: system
        files: \.(ya?ml|j2)$
        pass_filenames: false
  • repo + rev: each hook repository with a fixed version (the example ones were the latest at the time of writing). pre-commit autoupdate updates them, like any other dependency: on a branch, reviewing the changes.
  • pre-commit-hooks: generic checks. trailing-whitespace and end-of-file-fixer fix the files (and the commit stops so that you add the fix); check-merge-conflict detects forgotten <<<<<<< markers; check-added-large-files prevents committing large files by mistake (an image, an EE .tar.gz); detect-private-key looks for private keys.
  • gitleaks: looks for secrets (tokens, API keys, passwords in known formats) in what you're about to commit (Lesson 9.2).
  • repo: local: hooks defined in the repository itself. language: script runs a script from the repository; language: system runs a program that's already installed: here, yamllint and ansible-lint from the .venv, so as to use exactly the same versions as the CI (the versions published as an ansible-lint hook install their own environment with the most recent ansible-core).
  • files/types: which files each hook applies to. pass_filenames: false on ansible-lint: it runs on the whole project (its rules need the full context: roles, inventory…), but only if the commit includes some YAML file or template.

Install the hooks in your copy of the repository and try them on all the code:

pre-commit install
pre-commit run --all-files
trim trailing whitespace.................................................Passed
fix end of files.........................................................Passed
check for merge conflicts................................................Passed
check for added large files..............................................Passed
detect private key.......................................................Passed
Detect hardcoded secrets.................................................Passed
vault.yml files are encrypted............................................Passed
yamllint.................................................................Passed
ansible-lint.............................................................Passed

From now on, every git commit runs the checks on the staged files. Try the Vault hook:

ansible-vault decrypt playbooks/group_vars/lab/vault.yml
git add playbooks/group_vars/lab/vault.yml
git commit -m "test"
vault.yml files are encrypted............................................Failed
- hook id: vault-encrypted
- exit code: 1

ERROR: playbooks/group_vars/lab/vault.yml is not encrypted with ansible-vault

The commit isn't created. Undo it: git restore --staged playbooks/group_vars/lab/vault.yml && git checkout playbooks/group_vars/lab/vault.yml (it restores the encrypted version from the repository).

9.4. What pre-commit doesn't guarantee

pre-commit install is run in each copy of the repository (it doesn't travel with git clone), and anyone can skip it with git commit --no-verify. It's an aid for whoever is working, not a control. The control is the CI, which runs the same checks on everything that's pushed and which, with the main branch protected, prevents merging anything that doesn't pass. Add the pre-commit installation to "Getting started" in the README.md.

  1. The CI stops being informational

10.1. The lint job, final version

In .gitea/workflows/ci.yml, the lint job becomes mandatory: the two continue-on-error: true lines disappear and the Vault and duplicate variable checks are added (the one from Exercise 2 of Lesson 9.1):

  lint:
    name: Lint
    runs-on: aurora-runner
    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Set up the tools and the Ansible dependencies
        run: |
          python3 -m venv .venv
          .venv/bin/pip install --quiet -r ci/requirements.txt
          .venv/bin/ansible-galaxy collection install -r collections/requirements.yml
          .venv/bin/ansible-galaxy role install -r roles/requirements.yml

      - name: Check that the vault.yml files are encrypted
        run: ci/check-vault.sh $(git ls-files '*vault.yml')

      - name: Check that no variable is defined in two places
        shell: bash
        run: |
          status=0
          for env_dir in inventories/*/; do
            repeated=$(comm -12 \
              <(grep -rhoE '^[a-z0-9_]+:' playbooks/group_vars | sort -u) \
              <(grep -rhoE '^[a-z0-9_]+:' "${env_dir}group_vars" | sort -u))
            if [ -n "$repeated" ]; then
              echo "Variables also defined in ${env_dir}: $repeated"
              status=1
            fi
          done
          exit $status

      - name: yamllint
        run: .venv/bin/yamllint --strict .

      - name: ansible-lint
        run: .venv/bin/ansible-lint
  • Dependencies before the linter: with offline: true, ansible-lint doesn't install anything; it needs to find the roles (galaxy_roles/) and collections (collections/) to analyze the playbooks that use them, just like the syntax check.
  • git ls-files '*vault.yml': the list of versioned Vault files; the script receives them as arguments.
  • yamllint --strict: warning-level messages also make the step fail (exit code 2).
  • ansible-lint exits with a non-zero code if there's any failure that isn't in warn_list.
  • Since lab-check has needs: [lint, tests], a lint failure also prevents launching the check in AWX.

10.2. The tools in the other repositories

ansible-role-nginx deserves the same: copy .yamllint, .ansible-lint (with profile: production and without the exclusions specific to aurora-infra) and .pre-commit-config.yaml, and fix its warnings. For the aurora_store.infra collection it's even more important: Galaxy and Automation Hub run ansible-lint when importing a collection, and the production profile includes the sanity rule, which checks the ansible-test sanity ignore file (you'll get to know it in Lesson 9.5).

10.3. Protecting main with the checks

For the CI to be a real control, in Gitea: Settings → Branches → main → Edit, enable Enable Status Check and add the required jobs (Lint, Syntax check and Tests, with the naming pattern Gitea shows for workflows). With that, the merge button of a pull request stays blocked while any check is failing.

Push the changes on a branch, open the pull request and check that lint passes green without ignored warnings. Then trigger a failure to see it (for example, change a task to apt: without FQCN): the CI must fail, the pull request must not be mergeable, and pre-commit on your computer would already have told you beforehand.

git switch -c quality
git add .pre-commit-config.yaml ci/check-vault.sh .gitea/workflows/ci.yml README.md CHANGELOG.md
git commit -m "Quality: pre-commit and mandatory linting in the CI"
git push -u origin quality

Common Mistakes and Tips

  • Different results on your computer and in the CI. Different versions of ansible-lint or ansible-core. Always use the .venv created with ci/requirements.txt and check with ansible-lint --version.
  • "pip can't find a compatible version of ansible-lint". The latest version excludes your ansible-core. Explicitly pin a compatible version (section 3.1) and plan the ansible-core upgrade.
  • ansible-lint complains that it can't find a role or a collection. The dependencies are missing: ansible-galaxy ... install -r ... before linting (with offline: true, the tool doesn't install them).
  • yamllint fails on the workflows with truthy on the on: line. check-keys: false is missing from .yamllint.
  • Disabling a rule in skip_list "because it's annoying". It also hides the cases where it's right. Use # noqa on the specific line, with a justification.
  • --fix with pending changes. You won't be able to separate your changes from the tool's. Clean tree first.
  • Encrypted files in the check. If you don't exclude them, yamllint and ansible-lint will try to analyze them as normal YAML. They're in ignore and exclude_paths.
  • gitleaks false positives (for example, a high-entropy string in an encrypted file or in a manifest). Don't disable the hook: add the finding's fingerprint to .gitleaksignore or an exclusion rule to .gitleaks.toml (check the syntax for your version), and review that file in the pull request like any other exception.
  • Relying on pre-commit as a control. It can be skipped with --no-verify. The control is the CI with the protected branch.
  • Tip: when you upgrade ansible-lint, do it on a branch, read its changelog (new rules, profile changes) and fix the new warnings in the same pull request. That way the upgrade never blocks other people's work.

Exercises

Exercise 1: fixing a task

This task has arrived in a pull request. List all the ansible-lint rules (production profile) it breaks and write the corrected version:

- name: check the nginx status
  shell: systemctl status nginx | grep running
  become: yes
  register: status
  ignore_errors: yes

(It's in roles/nginx/tasks/service.yml of a role called nginx.)

Exercise 2: an exception, justified or not?

A colleague adds skip_list: [no-changed-when] to .ansible-lint because "there are lots of query tasks and it's a pain to put changed_when: false on all of them". What would you reply in the review? Propose the alternative.

Exercise 3: one more hook of our own

Write a local pre-commit hook (and the equivalent CI step) that prevents committing .retry files or the generated inventory inventories/staging/hosts-terraform.yml, even if someone adds them with git add -f.

Solutions

Exercise 1. It breaks: name[casing] (lowercase initial), fqcn[action-core] (shell without FQCN), risky-shell-pipe (pipe without pipefail), command-instead-of-module (there's a module for querying services), yaml[truthy] (yes twice), ignore-errors, no-changed-when (a query that would report changes) and var-naming[no-role-prefix] (status inside the nginx role). The fix uses a module, without shell:

- name: Get the status of the services
  ansible.builtin.service_facts:

- name: Check that nginx is running
  ansible.builtin.assert:
    that: ansible_facts['services']['nginx.service']['state'] == 'running'
    fail_msg: nginx is not running on {{ inventory_hostname }}

service_facts doesn't change anything (it doesn't need changed_when), doesn't need become to read the status, and the assert fails with a clear message instead of ignoring errors. If you had to keep the command, it would be ansible.builtin.command with cmd: systemctl is-active nginx, register: nginx_status, changed_when: false, failed_when: nginx_status.rc not in [0, 3] and a justified # noqa: command-instead-of-module (the rule knows systemctl and suggests the systemd module, which has no "query only" option).

Exercise 2. That the rule protects something important: a command or shell task without changed_when always reports a change, which breaks the idempotency check (a repeated run would never report changed=0, and Molecule would fail in Lesson 9.5), and it also runs whatever handlers it notifies. Disabling it globally would also hide the tasks that do change something and should have a real condition. Alternatives: (1) put changed_when: false on the queries (it's one line, and it documents that the task is read-only); (2) even better, replace many of those queries with information modules that already report correctly (service_facts, package_facts, stat, getent, uri…), as in Lesson 5.8.

Exercise 3. In .pre-commit-config.yaml, inside repo: local:

      - id: forbidden-files
        name: Generated files that must not be committed
        entry: This file is generated and must not be in the repository
        language: fail
        files: (\.retry$|^inventories/staging/hosts-terraform\.yml$)

The fail language makes the hook fail for any file that matches files, showing the entry text. In the CI, a step in lint:

      - name: Check that there are no generated files in the repository
        run: |
          if git ls-files | grep -E '(\.retry$|^inventories/staging/hosts-terraform\.yml$)'; then
            echo "There are generated files under version control"; exit 1
          fi

git ls-files lists what's versioned; if grep finds anything, it shows it and the step fails.

Conclusion

aurora-infra no longer depends on anyone's attention to follow its conventions. You've installed yamllint and ansible-lint with versions pinned in ci/requirements.txt (the latest compatible with ansible-core 2.17, with the series upgrade noted as a pending task), you use them from a project .venv with the same versions as the CI, and you've configured them: a .yamllint compatible with ansible-lint that excludes third-party, generated and encrypted content, and an .ansible-lint with the production profile, optional security rules (no-log-password, role-argument-spec) and no disabled rules. You know the most common rules and their fixes, automatic fixing with --fix and its precautions, and you've left the repository without warnings: partial-become fixed and two no-handler cases justified with # noqa. pre-commit checks each commit on your computer (formatting, secrets, unencrypted Vault files, yamllint and ansible-lint), and the CI applies the same checks as mandatory, with main protected. But well-written code doesn't prove that it works: a role that's flawless for ansible-lint may not install what it promises or may not be idempotent. The CI's tests stage, which you prepared in Lesson 8.3, is still empty. In the next lesson, Testing Ansible Code with Molecule, you'll write tests that run the roles in throwaway containers, check their idempotency and verify the result, and you'll fill that stage.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved