Commenting a line using the Ansible lineinfile module

It’s hard for me to believe that in this case there is nothing to use, but my search turned out to be fruitless.

I have a line in /etc/fstab to install a disk that is no longer available:

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

I want to change it to

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

I used this

 --- - 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 a comment character (#), but instead it replaced the whole line, and I ended up with

 #//archive/Pipeline 

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

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

or

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

I am trying to wrap my head around lineinfile and from what I read, it seems that insertafter is what I am looking for, but "insert after" is not what I want?

+6
source share
3 answers

You can use 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, only works on one line (even if several matches are found in the file). It ensures that a particular line is missing or present with specific content.

+10
source

Use backrefs = yes :

Used with state = present. If set, the string can contain backlinks (both positional and named) that will be populated if the regular expression 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 the (?i) parameter for regexp because your search expression will never match Pipeline with capital P in the fstab example.

+7
source

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

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

But "ah!" you say that you "want to save what the mountain was in fstab at a time." You made one better using mount , you kept it inaccessible .

+1
source

All Articles