Перейти к содержанию

Ansible Lint

Документация по Ansible Lint

Описание

Утилита командной строки для проверки плейбуков, ролей и коллекций.

Его основная цель - продвигать проверенные практики, шаблоны и модели поведения, избегая при этом распространенных подводных камней, которые могут легко привести к ошибкам или затруднить обслуживание кода.

Как и любой другой линтер, он упрямый. Тем не менее, его правила являются результатом вклада сообщества, и они всегда могут быть отключены на основе индивидуально или по категориям каждого пользователя.


Установка

Виртуальное окружение

Для идентичности всех компонентов ansible рекомендуется использовать единое виртуальное окружение Виртуальное окружение

ansible-lint является python пакетом, поэтому ставиться через менеджер пакетов pip

pip3 install ansible-lint

ansible-lint --version
#пример вывода 
#ansible-lint 26.8.0 using ansible-core:2.21.3 ansible-compat:26.8.0 ruamel-yaml:0.19.1 ruamel-yaml-clib:None

Использование

Внутри вашей роли (в корне проекта) используем простую команду:

ansible-lint

#пример вывода

WARNING  Listing 10 violation(s) that are fatal
schema[meta]: $.galaxy_info.min_ansible_version 2.2 is not of type 'string'. See https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_reuse_roles.html#using-role-dependencies
meta/main.yml:1  Returned errors will not include exact line numbers, but they will mention
the schema name being used as a tag, like ``schema[playbook]``,
``schema[tasks]``.

This rule is not skippable and stops further processing of the file.

If incorrect schema was picked, you might want to either:

* move the file to standard location, so its file is detected correctly.
* use ``kinds:`` option in linter config to help it pick correct file type.
[/]

yaml[trailing-spaces]: Trailing spaces
meta/main.yml:2

name[casing]: All names should start with an uppercase letter.
tasks/main.yml:4:9 Task/Handler: nginx | install nginx package (present)

yaml[truthy]: Truthy value should be one of [false, true]
tasks/main.yml:8

yaml[trailing-spaces]: Trailing spaces
tasks/main.yml:10

name[casing]: All names should start with an uppercase letter.
tasks/main.yml:11:9 Task/Handler: nginx | install nginx package (latest)

package-latest: Package installs should not use latest.
tasks/main.yml:11 Task/Handler: nginx | install nginx package (latest)

yaml[truthy]: Truthy value should be one of [false, true]
tasks/main.yml:15

name[casing]: All names should start with an uppercase letter.
tasks/main.yml:18:9 Task/Handler: nginx | allow nginx ufw

syntax-check[specific]: The role 'ansible-role-nginx' was not found in: /Users/andreyderyugin/ansible-role-nginx/tests/roles:/Users/andreyderyugin/molecule_lab/roles:/Users/andreyderyugin/ansible-role-nginx/tests
tests/test.yml:5:7

Read documentation for instructions on how to ignore specific rule violations.

# Rule Violation Summary

  1 syntax-check profile:min tags:core,unskippable
  1 schema profile:min tags:core
  2 yaml profile:min tags:formatting,yaml
  2 yaml profile:min tags:formatting,yaml
  3 name profile:min tags:idiom
  1 package-latest profile:min tags:idempotency

Failed: 10 failure(s), 0 warning(s) in 6 files processed of 8 encountered.

В результате выполнения мы видим все ошибки которые обнаружил ansible-lint

По мере исправления всех недочетов вы будете получать все меньшее кол-во ошибок пока не дойдете до целевого вывода

Passed: 0 failure(s), 0 warning(s) in 5 files processed of 7 encountered. Last profile that met the validation criteria was 'production'.

Этот вывод означает что наша роль полностью соответствует всем best-practice Ansible.


Автоисправление

ansible-lint позволяет автоматически исправлять найденные ошибки используя ключ --fix.

Предупреждение

Использование этой фичи автоматически внесет изменения в "проблемные" файлы, поэтому заранее сделайте коммит "важных" файлов

ansible-lint --fix

# пример вывода
ERROR    Rule specific fix not applied for: yaml[trailing-spaces]/yaml meta/main.yml:2
ERROR    Rule specific fix not applied for: yaml[trailing-spaces]/yaml tasks/main.yml:8
ERROR    Rule specific fix not applied for: yaml[trailing-spaces]/yaml tasks/main.yml:10
WARNING  Listing 1 violation(s) that are fatal
syntax-check[specific]: The role 'ansible-role-nginx' was not found in: /Users/andreyderyugin/ansible-role-nginx/tests/roles:/Users/andreyderyugin/molecule_lab/roles:/Users/andreyderyugin/ansible-role-nginx/tests
tests/test.yml:5:7


Modified 2 files.
# Rule Violation Summary

  1 syntax-check profile:min tags:core,unskippable

Failed: 1 failure(s), 0 warning(s) in 6 files processed of 8 encountered.

В выводе мы видим что были изменены два файла, но есть ошибки которые ansible-lint не смог исправить и они ложатся на ручное исправление.