Ansible Rule "no-free-form": Shifting from Free-Form to Full Syntax
In the world of automation, precision and clarity are paramount. Ansible, the powerful automation tool, brings forth an array of features to make automation tasks simpler and more efficient. However, it also lays down specific rules to ensure the correctness and maintainability of your Ansible playbooks. One such rule is "no-free-form," which enforces the use of full syntax over free-form syntax in module calling.
What Is Free-Form Syntax?
Free-form syntax, also known as inline or shorthand syntax, is a way to specify module parameters by simply listing them. While this might seem convenient, it can lead to subtle bugs and hinder the functionality of code editors and integrated development environments (IDEs) in providing feedback, autocompletion, and validation.
Here's an example of problematic code with free-form syntax:
``yaml
---
- name: Example with discouraged free-form syntax
hosts: all
tasks:
- name: Create a placeholder file
ansible.builtin.command: chdir=/tmp touch foo # <-- Using free-form
- name: Use raw to echo
ansible.builtin.raw: executable=/bin/bash echo foo # <-- Using executable=
changed_when: false
`
In this code, the use of free-form syntax in the ansible.builtin.command and ansible.builtin.raw modules can create issues and hinder the editing experience.
Output
`bash
WARNING Listing 4 violation(s) that are fatal
no-changed-when: Commands should not change things if nothing needs doing.
no-free-form.yml:5 Task/Handler: Create a placeholder file
no-free-form: Avoid using free-form when calling module actions. (ansible.builtin.command)
no-free-form.yml:5 Task/Handler: Create a placeholder file
no-free-form[raw]: Avoid embedding executable= inside raw calls, use explicit args dictionary instead.
no-free-form.yml:7 Task/Handler: Use raw to echo
yaml[new-line-at-end-of-file]: No new line character at the end of file
no-free-form.yml:9
Read documentation for instructions on how to ignore specific rule violations.
Rule Violation Summary
count tag profile rule associated tags
1 no-free-form basic syntax, risk
1 no-free-form[raw] basic syntax, risk
1 yaml[new-line-at-end-of-file] basic formatting, yaml
1 no-changed-when shared command-shell, idempotency
Failed: 4 failure(s), 0 warning(s) on 1 files. Last profile that met the validation criteria was 'min'.
`
Adhering to the Rule "no-free-form"
To adhere to "no-free-form," it's important to switch to the full syntax for module calling. Here's the correct way to write the same code without using free-form syntax:
``yaml
---
- name: Example that avoids free-form syntax
hosts: all
tasks:
- name: Create a placeholder file
ansible.builtin.c