使用Ansible lineinfile模块注释掉一行 [英] Commenting out a line with Ansible lineinfile module

查看:1156
本文介绍了使用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?

推荐答案

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

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模块注释掉一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆