Commenting out a line with Ansible lineinfile module

China☆狼群 提交于 2019-12-04 00:05:14

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

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

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.

Use backrefs=yes:

Used with state=present. If set, line can contain backreferences (both positional and named) that will get populated if the regexp matches.

Like this:

- name: Comment out pipeline archive in fstab
  lineinfile:
    dest: /etc/fstab
    regexp: '(?i)^(//archive/pipeline.*)'
    line: '# \1'
    backrefs: yes
    state: present

Also note that I use (?i) option for regexp, because your search expression will never match Pipeline with capital P in the example fstab.

This is one of the many reasons lineinfile is an antipattern. In many cases, a template is the best solution. In this case, the mount module was designed for this.

- name: Remove the pipeline archive
  mount: name="/archive/pipeline" state=absent

But "ah!" you say, you "want to preserve that the mount was in fstab at one time". You've done one better by using mount, you've preserved it in ansible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!