【问题标题】:In Ansible, how to move an existing line to the end of a file?在 Ansible 中,如何将现有行移动到文件末尾?
【发布时间】:2020-09-16 00:11:25
【问题描述】:

我正在寻找一种在 Ansible (2.9) 中将文本文件中的一行移动到文件末尾的方法。

line 1
line 2
line at end of file
line 3
line 4

应该变成

line 1
line 2
line 3
line 4
line at end of file

lineinfile 模块可以在末尾添加新行,但如果该行已经存在,则不会移动它。

# This does not move an existing line
- name: Move line to end of file
  lineinfile:
    path: /etc/myfile
    line: 'line at end of file'
    insertafter: EOF

我目前的解决方案是先去掉行,然后重新添加,但这当然不是幂等的,每次运行都会导致两次变化。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    还有更多选项可以使过程具有幂等性。将任务放入文件中,并仅在需要时包含它们。例如

     - shell: '[ "$(tail -1 myfile)" = "line at end of file" ] && echo OK || echo KO'
       changed_when: false
       register: result
     - include_tasks: move_line.yml
       when: result.stdout == 'KO'
    

    如果最后一行没问题,这个解决方案不关心正文。


    下一个选项是自行编辑文件。例如

     - command: cat myfile
       changed_when: false
       register: result
     - copy:
         dest: myfile
         content: |
           {% for line in lines %}
           {{ line }}
           {% endfor %}
           line at end of file
       vars:
         lines: "{{ result.stdout_lines|
                    difference(['line at end of file']) }}"
    

    【讨论】:

    • 我喜欢这两种解决方案,谢谢!我认为第一个在没有包含的情况下也可以工作,只需将相同的 when 条件放入两个步骤即可。
    • 不客气!正确的。您也可以使用block
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多