繁体   English   中英

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

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

我想使用 ansible-playbook 将 docker 日志轮换规范添加到 daemon.json 文件中

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

如果 daemon.json 已经存在于我正在应用剧本的节点上怎么办。 我不想弄乱现有的配置。 如何在第 1 行添加上面的块。 2(即在'{'之后或最后一行之前,即'}')?

ansible.builtin.lineinfile

  • 此模块确保特定行位于文件中,或使用反向引用的正则表达式替换现有行。
  • 当您只想更改文件中的一行时,这主要有用。

ansible.builtin.blockinfile

  • 此模块将插入/更新/删除由可自定义标记线包围的多行文本块。

正如@malpanez 解释的那样,我认为为此使用ansible.builtin.blockinfile模块会更准确。 您可以从下面的链接中查看示例用法。

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

您可以使用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>


我会使用块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