Ansible 最佳实践 - 何时使用“ini_file”模块而不是“copy”

use*_*490 6 ansible

我努力寻找最佳实践或约定,使其更容易维护并让其他人阅读我的 Ansible 剧本/角色。假设我正在创建一个 ini 文件:

[drinks]
fav=lemonade
Run Code Online (Sandbox Code Playgroud)

在 Ansible 中有多种方法可以做到这一点,我将提到两种:

  1. 使用ini_file模块
  2. copy使用模块复制具有相同内容的文件

哪种方法更可取?

谢谢。

Vla*_*tka 4

这取决于数据的来源。数据从哪里来?

  • 如果可以从任何来源获取文件,请使用复制模块。

  • 如果您想将该部分添加到现有文件中,请使用ini_file模块。

  • 如果数据是结构化的,则使用模板模块。例如,

my_ini_data:
  drinks:
    - key: fav
      val: lemonade
Run Code Online (Sandbox Code Playgroud)
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 %}
Run Code Online (Sandbox Code Playgroud)
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 %}
Run Code Online (Sandbox Code Playgroud)

给出

    - template:
        src: conf.ini.j2
        dest: conf.ini
Run Code Online (Sandbox Code Playgroud)

除此之外,最好看看该模块的作者。模板副本由 Ansible 核心团队维护。如果您遇到问题,请先查看未解决的问题