Ansible dynamic log files
Ansible log file path be set through log_path inside ansible.cfg or through environment variable ANSIBLE_LOG_PATH when executing ansible command through shell.
In some cases you may want to seperate log output per playbook run. There are different ways to achieve this, such as executing ansible through a wrapper shell, or using callback plugins.
I am sharing my approach, using pre and post tasks, that copy the original ansible log file (static log file) into run and host specific log files and thereby providing ‘dynamic log files’ for ansible.
This approach assumes that your log_path is at ./logs/ansible.log (within your ansible project directory). If you would like to abstract log_path, you can use the config lookup, as commented out in the example.
playbook.yml
pre_tasks:
- ansible.builtin.import_tasks: specify-dynamic-log-file.yml
tasks:
- name: Do some stuff
...
post_tasks:
- ansible.builtin.import_tasks: restore-static-log-file.yml
specify-dynamic-log-file.yml
---
# author: tertek
# description: specifies dynamic log file; to be run as pre-task
- block:
# - name: Lookup default log_path (as specified in ansible.cfg as log_path)
# ansible.builtin.set_fact:
# default_log_path: ""
- name: Specify dynamic log directory per playbook name
ansible.builtin.set_fact:
dynamic_log_dir: ""
dynamic_log_name: ".ansible..log"
- name: Specify dynamic log path
ansible.builtin.set_fact:
dynamic_log_path: "./logs//"
- debug:
msg="[INFO] Log output moved to dynamic log file "
- name: Backup static log file
ansible.builtin.shell: cp ./logs/ansible.log ./logs/ansible.log.bak
- name: Reset static log file
ansible.builtin.shell: echo "" > ./logs/ansible.log
- name: Ensure dynamic log directory exists
ansible.builtin.shell: "mkdir -p ./logs/"
delegate_to: localhost
restore-static-log-file.yml
---
# author: tertek
# description: restores static log file; to be run as post-task
- block:
- name: Move static log file to dynamic log path
ansible.builtin.shell: "mv ./logs/ansible.log "
- name: Restore static log from backup
ansible.builtin.shell: "mv ./logs/ansible.log.bak ./logs/ansible.log"
delegate_to: localhost
This has first been posted here.