【问题标题】:Append single line to existing file using Jinja2 template使用 Jinja2 模板将单行附加到现有文件
【发布时间】:2019-08-19 10:18:51
【问题描述】:

在(相当长的)剧本中,我有一些条目将一行附加到日志文件:

- name: LOG "Task done"
  lineinfile:
    dest: "{{ full_log_name }}"
    line: "{{ tstamp.stdout }}, {{ inventory_hostname }}, Task done"
    insertafter: EOF
  delegate_to: localhost

多亏了这个,我可以跟踪这个剧本已经通过了多少主机。

但是,我想在剧本开始时添加一行。如果我使用模板:

- name: LOG "Start"
  template:
    src: playbook_start.j2
    dest: "{{ full_log_name }}"
  delegate_to: localhost

它用这一行创建一个新的空文件,然后我的“lineinfile”任务附加它自己的日志。我想将旧日志保存在同一个文件中,这样我的 playbook 的两次运行将创建如下日志:

2019-08-19 11:34:56.63446, log.log, *** PLAYBOOK STARTED ***
2019-08-19 11:35:09.12405, Host1, First task done
2019-08-19 11:35:09.12299, Host2, First task done
2019-08-19 11:35:18.94610, Host1, Second task done
2019-08-19 11:35:18.95439, Host2, Second task done
2019-08-19 11:35:19.63446, log.log, *** PLAYBOOK STARTED ***
2019-08-19 11:35:20.33616, Host1, First task done
2019-08-19 11:45:25.84871, Host2, First task done
2019-08-19 11:45:25.83616, Host1, Second task done
2019-08-19 11:45:33.13359, Host2, Second task done

我也尝试使用“lineinfile”,但它会为每个主机创建多个“PLAYBOOK STARTED”行。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    我认为你可以使用 run_once: true。像下面的东西。我没有测试过。

    - name: LOG "PLAYBOOK STARTED"
      lineinfile:
        dest: "{{ full_log_name }}"
        line: "{{ tstamp.stdout }},log.log, *** PLAYBOOK STARTED***"
        insertbefore: BOF
        run_once: true 
      delegate_to: localhost
    

    【讨论】:

      【解决方案2】:

      run_once: true 你的lineinfile 会成功的。

      不过,我觉得你要实现的目标应该是通过回调插件来完成。你应该看看log_plays 插件,看看你可以如何定制它来满足你的需要……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多