简体   繁体   English

如何跟踪通过ansible调用的长时间运行的python脚本的日志

[英]How to tail the logs of long running python script invoked via ansible

We are running a python script via ansible.我们正在通过 ansible 运行一个 python 脚本。 The script takes around 45 mins to complete and the logging is in verbose mode.该脚本大约需要 45 分钟才能完成,并且日志记录处于详细模式。 But the issue is we get to know the result only after 45 minutes or if the script fails.但问题是我们只有在 45 分钟或脚本失败后才能知道结果。

- name: Run a python script
  shell: |
    cd /tmp/
    python {{script_name}} {{branch}} {{ script_action_arg_test }} >>  output.txt

I have tried the above approach, the python process keeps running but does not log anything to output.txt Is there a way to capture the verbose logs of the script in ansible itself?我已经尝试了上述方法,python 进程继续运行但没有将任何内容记录到 output.txt 有没有办法在 ansible 本身中捕获脚本的详细日志?

OK -- it's ugly.好吧 - 这很丑陋。 BUT, Ansible is for automation -- fire and forget, and is not designed for people to see what's going on in real time.但是,Ansible 是用于自动化——即发即忘,而不是为人们实时查看正在发生的事情而设计。

Now, use ansible-galaxy init my-cool-role in your roles directory to create the role.现在,在您的角色目录中使用ansible-galaxy init my-cool-role来创建角色。 Then, these are the files you will put in the role:然后,这些是您将放入角色的文件:

tasks/main.yml : tasks/main.yml

---
- name: Copy script to remote host
  copy:
    src: long_script.sh
    dest: long_script.sh
    mode: 0755

- name: Run script in async
  shell: ./long_script.sh > long_script.out
  async: 1000
  poll: 0
  register: long_task

- name: Include monitoring tasks
  include_tasks: monitor.yml
  loop: "{{ range(0, 100, 1)|list }}"

tasks/monitor.yml

---
- set_fact:
    done: "{{ 'DONE' == tail.stdout_lines[9] | default(false) }}"

- debug:
    var: tail.stdout_lines[9]

- debug:
    var: done

- meta: end_play
  when: done|bool

- name: Get last ten lines
  shell: sleep 5; tail long_script.out
  register: tail

- name: Show lines
  debug:
    var: tail.stdout_lines

files/long_script.sh : files/long_script.sh

#!/bin/bash
for (( ii=0; ii<50; ii++ )); do
  echo -n "$ii: "
  date
  sleep 1
done
echo DONE

   

This assumes that the long task is the last thing you're doing, because it ends the play.这假设长任务是您要做的最后一件事,因为它结束了游戏。 Note that you have to have enough loops to cover the expected time it il take the task to run.请注意,您必须有足够的循环来覆盖任务运行所需的预期时间。 If you need to do something after this, just put another play in the playbook.如果您在此之后需要做某事,只需在剧本中放另一个剧本。 Good luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM