Avoid Non-Builtin Actions in Your Ansible Playbooks
In the realm of Ansible playbooks, maintaining consistency and simplicity is key to a successful automation strategy. One way to achieve this is by adhering to the "only-builtins" rule, which emphasizes the usage of built-in actions from the ansible.builtin collection exclusively.
Keeping It Builtin
The "only-builtins" rule acts as a guardrail to ensure that you don't inadvertently wander into using non-built-in collections, plugins, or modules within your Ansible playbooks. While Ansible's ecosystem is rich with various extensions, sticking to the built-in collection can streamline your playbook's structure and maintainability.
Enable the only-builtins Rule
You can enable this rule in your Ansible-lint configuration. By doing so, you instruct Ansible to validate only builtin modules.
Here's how you can configure this rule:
``yaml
enable_list:
- only-builtins
`
Problematic Code
`yaml
---
- name: Example playbook
hosts: all
tasks:
- name: Deploy a Helm chart for Prometheus
kubernetes.core.helm: # <- Uses a non-builtin collection.
name: test
chart_ref: stable/prometheus
release_namespace: monitoring
create_namespace: true
`
In the problematic code above, we can see a playbook that attempts to deploy a Helm chart for Prometheus but uses the kubernetes.core.helm module, which is not part of the built-in ansible.builtin collection.
Ansible Lint Output
`bash
WARNING Listing 1 violation(s) that are fatal
only-builtins: Use only builtin actions. (warning)
only-bultin.yml:5 Task/Handler: Deploy a Helm chart for Prometheus
Read documentation for instructions on how to ignore specific rule violations.
Rule Violation Summary
count tag profile rule associated tags
1 only-builtins opt-in, experimental (warning)
Passed: 0 failure(s), 1 warning(s) on 1 files. Last profile that met the validation criteria was 'production'. Rating: 5/5 star
`
Correcting the Code
To adhere to the "only-builtins" rule, you should rewrite the playbook as follows:
`yaml
- name: Example playbook
hosts: localhost
tasks:
- name: Run a shell command
ansible.builtin.shell: echo This playbook uses actions from the builtin collection only.
`
In the corrected code, we replaced the non-built-in kubernetes.core.helm module with a simple ansible.builtin.shell module, ensuring that we are using only built-in actions.
The Advantages
1. Consistency: Relying solely on built-in actions maintains a consistent codebase and makes it easier for other team members to understand and work on your playbooks.
2. Reduced Dependencies: You won't have to manage external collections or plugins, simplifying your playbook's requirements and dependencies.
3. Enhanced Maintainability: Playbooks based on the "only-builtins`" rule are less pro