Introduction

Ansible is renowned for its flexibility and efficiency in automating various IT tasks. When it comes to managing files and templates in Ansible playbooks, the "copy" and "template" modules are frequently used to handle file transfers and template rendering. However, mismanaging paths in these modules can lead to confusion and unexpected behavior. Ansible Rule 404, known as "no-relative-paths," guides users to maintain best practices for handling paths within these modules.

Demystifying Rule 404 - "no-relative-paths"

Rule 404, "no-relative-paths," is a vital component of Ansible's rule set, aimed at ensuring the proper handling of paths within the "ansible.builtin.copy" and "ansible.builtin.template" modules. These modules are commonly used to interact with local and remote files in Ansible playbooks. While paths are fundamental to these modules, using relative paths can result in errors, disorganized projects, and user confusion.

The core principle emphasized by this rule is that the "src" argument in these modules should refer to local files and directories on the control node, not remote resources. Users are strongly advised to store files and templates in specific locations within the playbook or role directory:

1. Use the "files/" folder in the playbook or role directory for the "copy" module.

2. Use the "templates/" folder in the playbook or role directory for the "template" module.

These dedicated folders provide a clear and organized structure for managing your files and templates, allowing you to omit path information or use subfolders when specifying files with the "src" argument.

Problematic Code

Let's examine a problematic code snippet to understand how Rule 404, "no-relative-paths," can pinpoint issues in your playbooks:

``yaml

---

  • name: Example playbook

hosts: all

tasks:

- name: Template a file to /etc/file.conf

ansible.builtin.template:

src: ../my_templates/foo.j2 # <- Uses a relative path in the src argument.

dest: /etc/file.conf

owner: bin

group: wheel

mode: "0644"

  • name: Example playbook

hosts: all

vars:

source_path: ../../my_templates/foo.j2 # <- Sets a variable to a relative path.

tasks:

- name: Copy a file to /etc/file.conf

ansible.builtin.copy:

src: "{{ source_path }}" # <- Uses the variable in the src argument.

dest: /etc/foo.conf

owner: foo

group: foo

mode: "0644"

`

In this code, both "ansible.builtin.template" and "ansible.builtin.copy" modules use relative paths in the "src" argument. This approach can lead to unexpected behavior and issues, especially when working with remote files.

Correct Code

To align with best practices advocated by Rule 404, the correct code should adhere to the following guidelines:

``yaml

---

  • name: Example playbook

hosts: all

tasks:

- name: Template a file to /etc/file.conf

ansible.builtin.