【问题标题】:How to tail the logs of long running python script invoked via ansible如何跟踪通过 ansible 调用的长时间运行的 python 脚本的日志
【发布时间】:2020-11-12 09:06:20
【问题描述】:

我们正在通过 ansible 运行一个 python 脚本。该脚本大约需要 45 分钟才能完成,并且日志记录处于详细模式。但问题是我们只有在 45 分钟后或脚本失败时才能知道结果。

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

我已经尝试了上述方法,python 进程继续运行但没有记录任何内容到 output.txt 有没有办法在 ansible 本身中捕获脚本的详细日志?

【问题讨论】:

  • 您可以使用cd /tmp/ python {{script_name}} {{branch}} {{ script_action_arg_test }} > some_file.log 运行它,它会将输出捕获到文件中
  • @Tamir,我只是尝试了这种方法,但即使进程正在运行,它似乎也没有将任何内容记录到文件 output.txt 中
  • 1.不要使用cd /tmp,而是在你的任务中使用chdir: /tmp。 2. 对于手头的问题,这不是 Ansible 的工作方式,您不应该期望从任务中得到“生动的反馈”。这个问题有点接近你在这里问的问题:serverfault.com/questions/958952/…
  • 您需要使用async 运行该任务,然后循环遍历一个include 文件,该文件有一个任务获取文件的尾部(大约十行)和另一个转储它debug.
  • 是的,但不是现在。我有一些工作要为教会的食物银行做。我会在几个小时后回来。

标签: python python-3.x ansible


【解决方案1】:

好吧——太丑了。但是,Ansible 用于自动化——即开即弃,并不是为人们实时查看正在发生的事情而设计的。

现在,在您的角色目录中使用ansible-galaxy init my-cool-role 来创建角色。然后,这些是您将放入角色的文件:

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:

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

   

这假定长任务是您正在做的最后一件事,因为它结束了游戏。请注意,您必须有足够的循环来覆盖任务运行所需的预期时间。如果您需要在此之后做某事,只需在剧本中添加另一个剧本。祝你好运。

【讨论】:

  • 非常感谢 Jack 的精彩解释。我一定会试试这个。你真棒:) ? ?
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 2018-07-02
  • 2019-12-23
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多