Format your code with Ansible-Lint
Use Ansible-Lint to standardize your Playbooks
General
ESLint and Prettier are famous linting tools for web development to fix formatting/styling issues automatically. With Ansible-Lint you can format your playbooks now too.
Be aware that it does not fix your code-syntax. Your ansible file has to be exetucable before we can format it with ansible-lint.
Install
You can install Ansible-Lint with one of the following commands:
pip3 install ansible-lint
sudo apt install ansible-lint
Config
Lets take this helloworld.yml playbook as example.
---
- name: Hello World!
hosts: localhost
connection: local
tasks:
- name: debug
debug:
msg: hello world
The yml itself works fine but there are two style issues. If we issue the command ansible-lint helloworld.yml we get the following output.
WARNING Listing 2 violation(s) that are fatal
fqcn[action-core]: Use FQCN for builtin module actions (debug).
helloworld.yml:6 Use `ansible.builtin.debug` or `ansible.legacy.debug` instead.
name[casing]: All names should start with an uppercase letter.
helloworld.yml:6 Task/Handler: debug
It tells us that we should type the full module name of debug and to begin the taskname with an uppercase letter.
If we only want to fix the fqcn module name we can use the following command.
ansible-lint helloworld.yml --fix fqcn
You have also the option to use the all tag to fix all style issues.
ansible-lint helloworld.yml --fix all
Now our yml file looks like this
---
- name: Hello World!
hosts: localhost
connection: local
tasks:
- name: Debug
ansible.builtin.debug:
msg: hello world
We successfully fixed all style issues.
The default profile is production which has the highest standards but you can use other profiles with the command.
ansible-lint --profile=safety helloworld.yml
Checkout Ansible-Lint Profiles for the documentation of the profiles.
VSCode Extension
The Redhat Ansible extension for VSCode has an integration for the Ansible-Lint module.
You can install the VSCode extension by pressing CTRL + SHIFT + P in VSCode.
Now just copy/paste ext install redhat.ansible and the extension will be installed automatically. If you installed Ansible-Lint then the VSCode extension will display formatting issues in your YMLs directly.
Python Extension
For Python linting I use the VSCode extension pylint by Microsoft which shows me the errors directly in VSCode.
For Python formatting I use truff that can be installed in your python venv.
pip install ruff
ruff check main.py #just lists errors
ruff format main.py
Thanks for reading my article. If you have any questions or recommendations you can message me via arvednetblog@gmail.com.