Ansible wait_for模块,从文件末尾开始

use*_*100 2 ansible ansible-playbook

wait_for如果我search_regex='foo'在文件上使用,则使用Ansible中的模块

它似乎从文件的开头开始,这意味着它将匹配旧数据,因此当重新启动附加到文件而不是启动新文件的进程/应用程序(Java)时,wait_for模块将针对旧数据退出true ,但我想从文件的尾部检查.

tec*_*raf 7

默认情况下search_regex,wait_for模块中的正则表达式设置为多行.

您可以注册最后一行的内容,然后搜索该行之后出现的字符串(这假设日志文件中没有重复的行,即每个行包含一个时间戳):

vars:
  log_file_to_check: <path_to_log_file>
  wanted_pattern: <pattern_to_match>

tasks:
  - name: Get the contents of the last line in {{ log_file_to_check }}
    shell: tail -n 1 {{ log_file_to_check }}
    register: tail_output

  - name: Create a variable with a meaningful name, just for clarity
    set_fact:
      last_line_of_the_log_file: "{{ tail_output.stdout }}"

  ### do some other tasks ###

  - name: Match "{{ wanted_pattern }}" appearing after "{{ last_line_of_the_log_file }}" in {{ log_file_to_check }}
    wait_for:
      path: "{{ log_file_to_check }}"
      search_regex: "{{ last_line_of_the_log_file }}\r(.*\r)*.*{{ wanted_pattern }}"
Run Code Online (Sandbox Code Playgroud)


Sam*_*dra 5

如果日志文件中的每一行都带有时间戳,techraf 的答案就会起作用。否则,日志文件可能有多行与最后一行相同。

更健壮/耐用的方法是检查日志文件当前有多少行,然后搜索“第 n”行之后出现的正则表达式/模式。


vars:
  log_file: <path_to_log_file>
  pattern_to_match: <pattern_to_match>

tasks:
  - name: "Get contents of log file: {{ log_file }}"
    command: "cat {{ log_file }}"
    changed_when: false  # Do not show that state was "changed" since we are simply reading the file!
    register: cat_output

  - name: "Create variable to store line count (for clarity)"
    set_fact:
      line_count: "{{ cat_output.stdout_lines | length }}"

##### DO SOME OTHER TASKS (LIKE DEPLOYING APP) #####

  - name: "Wait until '{{ pattern_to_match}}' is found inside log file: {{ log_file }}"
    wait_for:
      path: "{{ log_file }}"
      search_regex: "^{{ pattern_to_skip_preexisting_lines }}{{ pattern_to_match }}$"
      state: present
    vars:
      pattern_to_skip_preexisting_lines : "(.*\\n){% raw %}{{% endraw %}{{ line_count }},{% raw %}}{% endraw %}"  # i.e. if line_count=100, then this would equal "(.*\\n){100,}"
Run Code Online (Sandbox Code Playgroud)