简体   繁体   English

如何使用 ansible 在特定行号插入块

[英]How to insert block at specific line number using ansible

I want to add below docker log rotation specs into daemon.json file using ansible-playbook我想使用 ansible-playbook 将 docker 日志轮换规范添加到 daemon.json 文件中

"log-driver": "json-file",
"log-opts": {
  "max-size": "1m",
  "max-file": "4"
}

What if daemon.json is already present on the node which I am applying the playbook to.如果 daemon.json 已经存在于我正在应用剧本的节点上怎么办。 I dont want to mess up existing configuration.我不想弄乱现有的配置。 How do I add above block at line no.如何在第 1 行添加上面的块。 2 ( that is after '{' or before last line ie '}' )? 2(即在'{'之后或最后一行之前,即'}')?

ansible.builtin.lineinfile ansible.builtin.lineinfile

  • This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression.此模块确保特定行位于文件中,或使用反向引用的正则表达式替换现有行。
  • This is primarily useful when you want to change a single line in a file only.当您只想更改文件中的一行时,这主要有用。

ansible.builtin.blockinfile ansible.builtin.blockinfile

  • This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.此模块将插入/更新/删除由可自定义标记线包围的多行文本块。

As @malpanez explains, I think it would be more accurate to use the ansible.builtin.blockinfile module for this.正如@malpanez 解释的那样,我认为为此使用ansible.builtin.blockinfile模块会更准确。 You can look at the example usage from the link below.您可以从下面的链接中查看示例用法。

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/blockinfile_module.html https://docs.ansible.com/ansible/latest/collections/ansible/builtin/blockinfile_module.html

You can use the lineinfile module您可以使用lineinfile模块

- name: Add logrotate to daemon.json
  lineinfile:
    path: "<location of the docker daemon.json>"
    insertafter: '\"log-opts\": {'         # not sure about the escaping
    line: <your custom line>


I'd use for blocks blockinfile :我会使用块blockinfile

- name: Add config to daemon.json
  ansible.builtin.blockinfile:
    path: "<location of the docker daemon.json>"
    insertafter: '\"log-opts\": {' # not sure about the escaping
    block: |
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "1m",
        "max-file": "4"
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM