Вы хотите узнать, как использовать Ansible Lint?
Ansible – это инструмент автоматизации ИТ.
Ansible Lint – это инструмент командной строки, который анализирует код плейбука на предмет потенциальных ошибок.
Сегодня мы расскажем о том, как помогает процесс линтинга.
Содержание
- Что такое ansible-lint?
- Установка инструмента линтинга Ansible
- Как использовать ansible-lint?
- Как его настроить?
- Заключение
Что такое ansible-lint?
Прежде чем перейти к ansible-lint, давайте посмотрим на Ansible.
Ansible – это инструмент автоматизации ИТ с открытым исходным кодом.
Цель этого инструмента – конфигурирование систем, развертывание программного обеспечения и многое другое.
Обычно Ansible подключается к другим узлам через SSH и проталкивает в них модули Ansible. Ansible хранит свои конфигурации в файлах .yml.
Важным файлом YAML является плейбук Ansible.
Он определяет, как Ansible должен работать на узлах. Поэтому ошибки в YAML-файлах могут повлиять на работу Ansible.
Именно здесь мы используем инструмент командной строки, ansible-lint. Мы используем эту команду для линтинга плейбуков или файлов .yml в Ansible.
Процесс линтинга запускает программу, которая анализирует код и находит потенциальные ошибки в коде Ansible.
То есть она обнаруживает поведение и методы, которые нуждаются в улучшении.
Он может обнаружить синтаксические ошибки, неопределенные переменные и т.д.
Установка инструмента линтинга Ansible
Ansible-lint – это инструмент командной строки.
Он не входит в пакет Ansible, поэтому нам необходимо установить его. Мы можем установить его различными способами.
Чтобы установить его с помощью встроенного менеджера пакетов в Ubuntu, выполните команду,
apt install ansible-lint
Поскольку ansible-lint – это пакет Python, мы можем установить его с помощью команды,
pip install ansible-lint
Теперь давайте посмотрим, как его использовать!
Как использовать ansible-lint?
Чтобы получить полную информацию об использовании команды linting, мы используем,
ansible-lint --help
И вывод выглядит следующим образом:
Существует множество правил по умолчанию, используемых при линте плейбука.
Чтобы перечислить их, мы используем команду:
ansible-lint -L
Всего существует 18 правил по умолчанию.
Некоторые из них:
ANSIBLE0002: Trailing whitespace
There should not be any trailing whitespace
ANSIBLE0004: Git checkouts must contain explicit version
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0005: Mercurial checkouts must contain explicit revision
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0006: Using command rather than module
Executing a command when there is an Ansible module is generally a bad idea
ANSIBLE0007: Using command rather than an argument to e.g. file
Executing a command when there is are arguments to modules is generally a bad idea
ANSIBLE0008: Deprecated sudo
Instead of sudo/sudo_user, use become/become_user.
. . .
Например, если в плейбуке есть пробелы в конце, вывод линта будет выглядеть так:
ANSIBLE0002: Trailing whitespace
Выводится список нарушенных правил вместе с точным номером строки, где это произошло.
Аналогично, синтаксические ошибки в playbook выглядят следующим образом,
Syntax Error while loading YAML.
did not find expected '-' indicator
The error appears to be in '/etc/ansible/playbook.yml': line 14, column 6, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
name: Disable SELinux
^ here
Здесь отображается ошибочная строка вместе с точной ошибкой.
Самое главное, пользователь должен запустить команду linting в том же месте, где находится файл .yml.
Для сканирования всех файлов .yml в данном месте мы можем использовать команду,
ansible-lint *.yml
Как его настроить?
Далее рассмотрим возможность пользовательской настройки инструмента линтинга.
Мы можем настроить ansible-lint в соответствии с нашими требованиями.
Помимо правил по умолчанию, мы можем указать дополнительные правила в файле.
А флаг командной строки -c <путь к файлу> приведет к линтингу плейбука на основе пользовательской конфигурации.
Заключение
Итак, мы рассмотрели, как использовать инструмент командной строки ansible-lint
см. также:
- 🔐 Создание самоподписанных сертификатов OpenSSL с помощью Ansible
- 📜 Управление пользователями и группами в Linux с помощью Ansible
- 🐧 Как временно остановить демон Auditd с Ansible
- 🐧 Настройка кластера Elasticsearch на CentOS 8/7 | Ubuntu 20.04 / 18.04 с Ansible
- 📜 Как создать зашифрованный пароль пользователя Linux для Ansible
- 🔐 Как использовать Ansible Vault в плейбуках для защиты конфиденциальных данных
- 💽 Шпаргалка Ansible Vault / Справочное руководство
- Определите ключ ssh для каждого хоста, используя ansible_ssh_private_key_file
- 🦊 Безопасность CI/CD – Как защитить свой пайплайн CI/CD
Are you looking at how to use Ansible Lint?
Ansible is an IT automation tool.
Ansible Lint is a command-line tool that analyzes playbook code for potential errors.
At Bobcares, we get many queries regarding Ansible, as a part of our Server Management Services.
Today, our Support Engineers will give an idea of how the linting process helps.
What is ansible-lint?
Before getting to ansible-lint, let’s have a look at Ansible.
Ansible is an open-source IT automation tool. The purpose of this tool is to configure systems, deploy software and many more.
Usually, Ansible connects to other nodes via SSH and pushes Ansible modules into them. Ansible holds its configurations in .yml files.
An important YAML file is Ansible playbook. It defines how the Ansible should work in the hosts. So errors in the YAML files can affect the working of Ansible.
This is where we make use of a command-line tool, ansible-lint. We use this command for linting playbooks or .yml files in Ansible.
A linting process runs a program that analyses code and finds potential errors in Ansible code. That is it detects the behaviors and practices that need improvement. It can detect syntax errors, undefined variables, etc.
Installing the linting tool in Ansible
Ansible-lint is a command-line tool. It does not come with the Ansible package, rather we need to install it. We can install it in various ways.
To install it using the built-in package manager in Ubuntu we use the command,
apt install ansible-lint
Since ansible-lint is a Python package we can install it using the command,
pip install ansible-lint
Now let’s see how our Support Engineers use the linting command in Ansible.
How to use ansible-lint?
To obtain complete information on using the linting command, we use,
ansible-lint --help
And the output appears as,
There many default rules used while linting a playbook. To list them, we use the command,
ansible-lint -L
There are a total of 18 default rules. A few rules are,
ANSIBLE0002: Trailing whitespace
There should not be any trailing whitespace
ANSIBLE0004: Git checkouts must contain explicit version
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0005: Mercurial checkouts must contain explicit revision
All version control checkouts must point to an explicit commit or tag, not just "latest"
ANSIBLE0006: Using command rather than module
Executing a command when there is an Ansible module is generally a bad idea
ANSIBLE0007: Using command rather than an argument to e.g. file
Executing a command when there is are arguments to modules is generally a bad idea
ANSIBLE0008: Deprecated sudo
Instead of sudo/sudo_user, use become/become_user.
. . .
For instance, if a playbook has trailing whitespace, the linting output shows up as,
Here the output lists the violated rule along with the exact line number where it occurred.
Likewise, the syntax errors in playbook appear as,
Syntax Error while loading YAML.
did not find expected '-' indicator
The error appears to be in '/etc/ansible/playbook.yml': line 14, column 6, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
name: Disable SELinux
^ here
Here it displays the offending line along with exact error.
Most importantly, a user should run the linting command in the same location as that of the .yml file.
To scan all the .yml file in the location we can use the command,
ansible-lint *.yml
How to custom configure it?
Next, let’s see the possibility of custom configuring the linting tool.
We can custom configure ansible-lint for our requirement. Apart from the default rules, we can specify additional rules in a file.
And the command-line flag -c <file path> will lint the playbook based on the custom configuration.
[Need assistance in using Ansible lint? – We can help you.]
Conclusion
So far, we saw how to use the ansible-lint command-line tool. Today, our Support Engineers gave a complete guide on its installation, usage, and configuration.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Ansible – это инструмент автоматизации ИТ.
Ansible Lint – это инструмент командной строки, который анализирует код плейбука на предмет потенциальных ошибок.
Ansible – это инструмент автоматизации ИТ с открытым исходным кодом.
Цель этого инструмента – конфигурирование систем, развертывание программного обеспечения и многое другое.
Обычно Ansible подключается к другим узлам через SSH и проталкивает в них модули Ansible. Ansible хранит свои конфигурации в файлах .yml.
Он определяет, как Ansible должен работать на узлах. Поэтому ошибки в YAML-файлах могут повлиять на работу Ansible.
Именно здесь мы используем инструмент командной строки, ansible-lint. Мы используем эту команду для линтинга плейбуков или файлов .yml в Ansible.
Процесс линтинга запускает программу, которая анализирует код и находит потенциальные ошибки в коде Ansible.
То есть она обнаруживает поведение и методы, которые нуждаются в улучшении.
Он может обнаружить синтаксические ошибки, неопределенные переменные и т.д.
Установка инструмента линтинга Ansible
Ansible-lint – это инструмент командной строки.
Он не входит в пакет Ansible, поэтому нам необходимо установить его. Мы можем установить его различными способами.
Чтобы установить его с помощью встроенного менеджера пакетов в Ubuntu, выполните команду,
apt install ansible-lint
Поскольку ansible-lint – это пакет Python, мы можем установить его с помощью команды,
pip install ansible-lint
Теперь давайте посмотрим, как его использовать!
Как использовать ansible-lint?
Чтобы получить полную информацию об использовании команды linting, мы используем,
ansible-lint --help
И вывод выглядит следующим образом:
Существует множество правил по умолчанию, используемых при линте плейбука.
Чтобы перечислить их, мы используем команду:
ansible-lint -L
Всего существует 18 правил по умолчанию.
Некоторые из них:
ANSIBLE0002: Trailing whitespace There should not be any trailing whitespace ANSIBLE0004: Git checkouts must contain explicit version All version control checkouts must point to an explicit commit or tag, not just «latest» ANSIBLE0005: Mercurial checkouts must contain explicit revision All version control checkouts must point to an explicit commit or tag, not just «latest» ANSIBLE0006: Using command rather than module Executing a command when there is an Ansible module is generally a bad idea ANSIBLE0007: Using command rather than an argument to e.g. file Executing a command when there is are arguments to modules is generally a bad idea ANSIBLE0008: Deprecated sudo Instead of sudo/sudo_user, use become/become_user. |
Например, если в плейбуке есть пробелы в конце, вывод линта будет выглядеть так:
ANSIBLE0002: Trailing whitespace
Выводится список нарушенных правил вместе с точным номером строки, где это произошло.
Аналогично, синтаксические ошибки в playbook выглядят следующим образом,
Syntax Error while loading YAML. did not find expected ‘-‘ indicator The error appears to be in ‘/etc/ansible/playbook.yml’: line 14, column 6, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: name: Disable SELinux ^ here |
Здесь отображается ошибочная строка вместе с точной ошибкой.
Самое главное, пользователь должен запустить команду linting в том же месте, где находится файл .yml.
Для сканирования всех файлов .yml в данном месте мы можем использовать команду,
ansible-lint *.yml
Как его настроить?
Далее рассмотрим возможность пользовательской настройки инструмента линтинга.
Мы можем настроить ansible-lint в соответствии с нашими требованиями.
Помимо правил по умолчанию, мы можем указать дополнительные правила в файле.
А флаг командной строки -c <путь к файлу> приведет к линтингу плейбука на основе пользовательской конфигурации.