我如何使用 Ansible lineinfile 删除除少数特定行以外的所有行?

How can I use Ansible lineinfile to remove all but a few specific lines?

我正在尝试确保从文件中删除除少数特定行之外的所有行。我可以通过以下任务完成一半。

- name: ensure only the correct lines are present
  lineinfile: dest=/path/to/file
    regexp="pattern1|pattern2[0-9]*|pattern3[0-9]*"
    state=present
    backup=yes

最终我想确保 pattern1pattern2[0-9]*pattern3[0-9]* 是此文件中唯一保留的行。我试图想出一个正则表达式来否定这个,然后指定 state=absent 但到目前为止我一直没有成功。

如果您只需要文件中的特定行,为什么不将该文件和您想要的行一起传输到远程服务器?您可以使用 copy module to transfer that file as is or template module to dynamically substitute some variables inside or even assemble 模块从一些片段(例如配置)生成文件。