Ansible best practice - When to use "ini_file" module instead of "copy"

Viewed 1155

I struggle to find best practices or conventions making it easier to maintain and for others to read my Ansible playbooks/roles. Let's say I'm creating an ini-file:

[drinks]
fav=lemonade

There are multiple ways to do this in Ansible, I'll mention two:

  1. Use ini_file module
  2. Copy a file with the same content using the copy module

Which method is preferable?

Thanks.

1 Answers

It depends on the source of the data. Where does the data come from?

  • If a file is available from whatever source use the copy module.

  • If you want to add the section to an existing file use the ini_file module.

  • If data is structured use the template module. For example

my_ini_data:
  drinks:
    - key: fav
      val: lemonade
shell> cat conf.ini.j2
{% for section in my_ini_data.items() %}
[{{ section.0 }}]
{% for item in section.1 %}
{{ item.key }}={{ item.val }}
{% endfor %}
{% endfor %}
    - template:
        src: conf.ini.j2
        dest: conf.ini

gives

shell> cat conf.ini
[drinks]
fav=lemonade

In addition to this, it's a good idea to take a look at the authors of the module. template and copy are maintained by Ansible Core Team. If you have problems take a look at the open issues first.

Related