0

I want to add below docker log rotation specs into daemon.json file using ansible-playbook

"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. I dont want to mess up existing configuration. How do I add above block at line no. 2 ( that is after '{' or before last line i.e. '}' ) ?

Ganesh Shinde
  • 65
  • 2
  • 7

3 Answers3

1

I'd use for blocks 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"
      }
malpanez
  • 225
  • 1
  • 4
1

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

  • 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. You can look at the example usage from the link below.

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

Baris Sonmez
  • 477
  • 2
  • 8
0

You can use the lineinfile module

- 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>


Pavol Krajkovič
  • 505
  • 1
  • 12