【问题标题】:Ansible Jinja2 template to replace only a few lines for a configuration file? (Jinja2 template doesn't cover the whole content of the target file)Ansible Jinja2 模板仅替换配置文件的几行? (Jinja2 模板没有覆盖目标文件的全部内容)
【发布时间】:2020-09-02 21:25:00
【问题描述】:

例如配置文件如下:

    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
    # OOM score = 1000

我知道我可以制作一个如下的 Jinja 文件来轻松实现将某些参数定义为变量的任务:

    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
     OOM score = {{ variable }}

但是如果基本文件本身不是完全确定的,文本的其他部分可能会随着时间而改变(我们不希望由于 Ansible/Jinja2 冻结更改以使其成为静态),所以可以我只是用我关心的行定义了一个Jinja2模板文件,逻辑可能是这样的:

  1. 忽略与OOM score =不匹配的行
  2. 如果该行匹配OOM score =,则将该行更改为OOM score = {{ variable }},当然要替换为变量。
#jinja template
#ignore lines if it's not matched
     OOM score = {{ variable }}

我知道上面的情况可以通过lineinfile轻松实现,但是假设很多行都需要这样做(不是块,分散在文本文件中) ,有没有办法通过template/Jinja2 而不是lineinfile with loops来实现?

【问题讨论】:

  • lineinfile 的“many lines”有什么问题?慢吗?它应该更有效吗?目标是什么?

标签: ansible jinja2


【解决方案1】:

问:“有没有办法通过 template/Jinja2 实现只替换几行配置文件,而不是用循环替换 lineinfile?”

A:没有。Modul template 首先从模板创建一个临时文件。然后将此临时文件与当前文件(如果有)进行比较,如果文件不同,则写入该文件。

您正在寻找的是获取当前文件并通过添加行来创建模板,这实际上是lineinfile 模块的功能。

【讨论】:

  • 谢谢,Vladimir,这也是我的理解,只是为了与社区核实以了解更好的方法。
  • 不客气,Bright。那是 all 关于文件的可用信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多