Introduction

Ansible is a powerful automation tool, but its flexibility can sometimes lead to unintended and implicit behaviors in your playbooks. These implicit behaviors are often undocumented, making it challenging to understand what's happening behind the scenes. In this article, we'll explore the "avoid-implicit" rule in Ansible and how you can follow best practices to avoid these implicit behaviors.

What is the "avoid-implicit" Rule?

The "avoid-implicit" rule is a part of Ansible's linting tool that helps identify and flag the use of implicit behaviors within your playbooks. Implicit behaviors are actions that Ansible takes without explicit instructions, and they can lead to unpredictable outcomes or errors.

Common Implicit Behaviors

One common example of implicit behavior in Ansible is when using the ansible.builtin.copy module to write file content. While you might expect to provide content as a simple dictionary, Ansible can interpret this in unexpected ways. To avoid this, it's best to use an explicit Jinja template.

Problematic Code

Here's an example of problematic code and the correct way to address it:

``yaml

  • name: Example playbook

hosts: all

tasks:

- name: Write file content

ansible.builtin.copy:

content: { "foo": "bar" } # Avoid implicit behavior

dest: /tmp/foo.txt

`

Output

`bash

WARNING Listing 2 violation(s) that are fatal

avoid-implicit: Avoid implicit behaviors

avoid-implicit.yml:4 Task/Handler: Write file content

risky-file-permissions: File permissions unset or incorrect.

avoid-implicit.yml:4 Task/Handler: Write file content

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

Rule Violation Summary

count tag profile rule associated tags

1 avoid-implicit safety unpredictability

1 risky-file-permissions safety unpredictability

Failed: 2 failure(s), 0 warning(s) on 1 files. Last profile that met the validation criteria was 'moderate'. Rating: 2/5 star

`

Correct Code

In this code, the content is provided as a dictionary, which Ansible may interpret as file content, leading to unexpected results. It's always best to use an explicit Jinja template, as shown in the corrected code:

`yaml

  • name: Example playbook

hosts: all

tasks:

- name: Write file content

vars:

content: { "foo": "bar" }

ansible.builtin.copy:

content: "{{ content | to_json }}" # Avoid implicit behavior

dest: /tmp/foo.txt

``

By using explicit Jinja templates, you ensure that Ansible understands your intentions, reducing the chances of implicit behaviors causing issues.

Why Avoid Implicit Behaviors

Avoiding implicit behaviors in your Ansible playbooks is essential for several reasons:

1. Predictability: Implicit behaviors can lead to unpredictable outcomes, making it challenging to anticipate the results of your tasks.

2