Definition

There are 5 main modules for managing file contents:

  • ansible.builtin.lineinfile — manages lines in a file
  • ansible.builtin.blockinfile — manages a block of lines in a file (separates them from both sides)
  • ansible.builtin.template — replaces a Jinja2 file with a template
  • ansible.builtin.copy — replaces a file with its contents
  • ansible.builtin.replace — replaces all lines that match a regular expression

Let’s look at the advantages and disadvantages of each of them.

ansible.builtin.lineinfile

Pros: Allows flexibility and precision in creating or removing the lines you want in the right place Cons: If you change line: after adding it, when you run it again, Ansible will not be able to track the previous line and will leave it (ending up with 2 lines)

ansible.builtin.blockinfile

Pros: Allows you to conveniently track the beginning and end of changes that Ansible has made using a marker (the lines for marking can be changed via the marker_begin and marker_end parameters), and you don’t have to worry about previously added lines, since Ansible will work exclusively within the block Cons: Doesn’t allow adding anything separately from the block, when restarting with other data, replaces the existing block with a new one

ansible.builtin.template

Pros: Allows flexible configuration of the configuration file using the entire arsenal of Jinja2 templates, also can create a marker similar to the ansible.builtin.blockinfile module, more details in the post about ansible_managed Cons: By default, completely replaces the file (force: true), not intended to change existing files

ansible.builtin.copy

Pros: Doesn’t require creating a Jinja2 template, intuitive Cons: By default, completely replaces the file (force: true), interpolation can lead to unpredictable results

ansible.builtin.replace

Pros: Allows you to replace several lines in one file at once Cons: You can accidentally change lines that you don’t need to change, and it also can’t add the necessary lines pointwise

Best-practice

When and which to use:

  • If you need to replace a line/lines in an existing file, it is better to use ansible.builtin.lineinfile
  • If you need to add a block with lines to an existing file with the ability to mark changes, it is better to use ansible.builtin.blockinfile
  • If you need to replace a file with some simple content, it is better to use ansible.builtin.copy
  • If you need to dynamically create a file and/or modify it, it is better to use ansible.builtin.template
  • If you need to replace all lines according to some regular expression, it is better to use ansible.builtin.replace