From b3a42e41cd183f1228bd4c535b183a5b0d87a212 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sun, 23 Nov 2025 21:49:27 +0100 Subject: plugins: add parse_json_file --- plugins/action/parse_json_file.py | 27 +++++++++++++++++++++++++++ roles/docker/tasks/logging.yml | 23 +++++++---------------- 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100755 plugins/action/parse_json_file.py diff --git a/plugins/action/parse_json_file.py b/plugins/action/parse_json_file.py new file mode 100755 index 0000000..d9c864a --- /dev/null +++ b/plugins/action/parse_json_file.py @@ -0,0 +1,27 @@ +#!/usr/bin/python + +import json + +from ansible.errors import AnsibleActionFail +from ansible.plugins.action import ActionBase +from ansible_collections.tensin.infra.plugins.module_utils import file + + +class ActionModule(ActionBase): + def run(self, tmp=None, task_vars=None): + result = super().run(tmp, task_vars) + + path = self._task.args['path'] + default = self._task.args.get('default') + if default is not None: + default = json.dumps(default) + + content = file.read_file(self, path, task_vars, default=default) + + try: + content = json.loads(content) + except json.JSONDecodeError as e: + raise AnsibleActionFail(f'Failed to parse JSON at {path}') from e + + result['content'] = content + return result diff --git a/roles/docker/tasks/logging.yml b/roles/docker/tasks/logging.yml index 8f861a3..2de7a64 100644 --- a/roles/docker/tasks/logging.yml +++ b/roles/docker/tasks/logging.yml @@ -1,18 +1,9 @@ -- name: Read Docker config - block: - - name: Read daemon.json - become: true - ansible.builtin.slurp: - src: /etc/docker/daemon.json - register: docker_current_config - - - name: Parse daemon.json - ansible.builtin.set_fact: - docker_current_config: '{{ docker_current_config.content | b64decode | from_json }}' - rescue: - - name: daemon.json is missing - ansible.builtin.set_fact: - docker_current_config: {} +- name: Read daemon.json + become: true + tensin.infra.parse_json_file: + path: /etc/docker/daemon.json + default: {} + register: daemon_json - name: Modify Docker config become: true @@ -28,7 +19,7 @@ - name: Write daemon.json ansible.builtin.copy: dest: /etc/docker/daemon.json - content: '{{ docker_current_config | combine({"log-driver": docker_logging_driver}) | to_nice_json }}' + content: '{{ daemon_json.content | combine({"log-driver": docker_logging_driver}) | to_nice_json }}' owner: root group: root mode: '644' -- cgit v1.3