代码之家  ›  专栏  ›  技术社区  ›  Kevin Keane

在Ansible中,如何将现有行移动到文件末尾?

  •  0
  • Kevin Keane  · 技术社区  · 4 年前

    我正在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
    

    # 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
    

    我目前的解决方案是先删除该行,然后再重新添加它,但这当然不是幂等的,每次运行都会导致两个更改。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Vladimir Botka    4 年前

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

     - 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']) }}"