本文介绍了用 Ansible lineinfile 模块注释掉一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难相信没有任何内容可以涵盖此用例,但事实证明我的搜索毫无结果.

I find it hard to believe there isn't anything that covers this use case but my search has proved fruitless.

我在 /etc/fstab 中有一行用于安装不再可用的驱动器:

I have a line in /etc/fstab to mount a drive that's no longer available:

//archive/Pipeline /pipeline/Archives cifs ro,credentials=/home/username/.config/cifs 0   0

我想要的是把它改成

#//archive/Pipeline /pipeline/Archives cifs ro,credentials=/home/username/.config/cifs 0   0

我正在使用这个

---
- hosts: slurm
  remote_user: root

  tasks:
    - name: Comment out pipeline archive in fstab
      lineinfile:
        dest: /etc/fstab
        regexp: '^//archive/pipeline'
        line: '#//archive/pipeline'
        state: present
      tags: update-fstab

期望它只是插入注释符号(#),但它替换了整行,我最终得到了

expecting it to just insert the comment symbol (#), but instead it replaced the whole line and I ended up with

#//archive/Pipeline

有没有办法全局捕获该行的其余部分或只插入单个注释字符?

is there a way to glob-capture the rest of the line or just insert the single comment char?

 regexp: '^//archive/pipeline *'
 line: '#//archive/pipeline *'

 regexp: '^//archive/pipeline *'
 line: '#//archive/pipeline $1'

我想把头放在 lineinfile 上,从我读过的内容来看,我正在寻找 insertafter ,但insert after"不是我想要的?

I am trying to wrap my head around lineinfile and from what I"ve read it looks like insertafter is what I'm looking for, but "insert after" isn't what I want?

推荐答案

您可以使用替换 模块适用于您的案例:

You can use the replace module for your case:

---
- hosts: slurm
  remote_user: root

  tasks:
    - name: Comment out pipeline archive in fstab
      replace:
        dest: /etc/fstab
        regexp: '^//archive/pipeline'
        replace: '#//archive/pipeline'
      tags: update-fstab

它将替换所有匹配regexp的字符串.

It will replace all occurrences of the string that matches regexp.

lineinfile 另一方面,仅适用于一行(即使在文件中找到多个匹配项).它确保特定行不存在或存在已定义的内容.

lineinfile on the other hand, works only on one line (even if multiple matching are find in a file). It ensures a particular line is absent or present with a defined content.

这篇关于用 Ansible lineinfile 模块注释掉一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 20:05