How to log in a separate file per playbook in Ansi

2019-04-12 20:41发布

问题:

Instead of the single log file defined in log_path, I want to have separate log files per playbook run in Ansible.

As far as I know there is no built-in way to do that. So I am looking for clever "hacks".

More specifically, I want after a playbook is ran a log file to be generated in the format [playbook name].[date].log

I found this thread in SO but it doesn't meet my needs. The alias would be a solution if I could pass somehow the playbook name dynamically, not only the date. The lookup solution would be ok if I could copy only the relevant part from the main log file without all the history up until the moment of the copy. Additionally, if you have many playbooks running in parallel I don't know how good this method will work.

Any clues / ideas? What I thought is creating a shell script that would be called inside a playbook to somehow "extract" the relevant entries from the main log and create a separate one. But I believe I am making it too complex.

回答1:

Be sure to comment out the log_path option in ansible.cfg.

create a wrapper shell script: ansible-playbook-wrapper.sh

#!/bin/bash

export ANSIBLE_LOG_PATH=/var/log/ansible/playbook_$(echo $1 | cut -d . -f 1).log
ansible-playbook $@

alias ansible-playbook to run the wrapper script instead:

alias ansible-playbook="/path/to/ansible-playbook-wrapper.sh"

create a log directory and open up permissions so all users (or perhaps all ansible users) can write to it:

sudo mkdir /var/log/ansible
sudo chmod 777 /var/log/ansible

Now when you run ansible-playbook dns_server.yml -u cobra -k you will see the following:

[cobra@ansible ~]$ ls /var/log/ansible
playbook-dns_server.log
playbook-some_other_playbook.log
playbook-even_more_plays.log