[ Ansible ] - How to comment (add #) all lines in file

Hey Ansible gurus, need your help here…

Just googled around and was not able to find a satisfactory answer to the following:

  • I have a file and want to insert in the beginning of each line the # character
  • No matter if it has 10 lines or 1000 lines
  • The final goal would be to no matter which file I said so, will add # to the beginning of line
    Maybe Ansible is not the proper tool to do it… I searched throughout Ansible docs and community webpages and was not able to find an example…

Am I doing something wrong? Again, is not the tool to it?
What would be your experience with such situation? Did you managed to simple use shell module and do it?

Please share your findings with me

Hey Ansible gurus, need your help here...

Just googled around and was not able to find a satisfactory answer to the following:

I have a file and want to insert in the beginning of each line the # character
No matter if it has 10 lines or 1000 lines
The final goal would be to no matter which file I said so, will add # to the beginning of line

Maybe Ansible is not the proper tool to do it... I searched throughout Ansible docs and community webpages and was not able to find an example...

Am I doing something wrong? Again, is not the tool to it?
What would be your experience with such situation? Did you managed to simple use shell module and do it?

      Stupid question: every single line in the file or a specific set
of lines in the file identified in some way or fashion?

To be clear, add # to the beginning of every single line in the file… 10, 1000, 100000 lines… doesnt matter.

Use "replace" module. For example
https://docs.ansible.com/ansible/latest/modules/replace_module.html#replace-replace-all-instances-of-a-particular-string-in-a-file-using-a-back-referenced-regular-expression

    - replace:
        path: "{{ item }}"
        regexp: '^(.*)$'
        replace: '# \1'
      loop: "{{ list_of_files }}"

HTH,

  -vlado

Hi, thanks for the reply.

Indeed that suggestion worked out in replacement of using shell module (or similar).

Thanks for sharing.

You're welcome. Be careful. It's not idempotent. Each run of the task will
prepend '# '.

HTH,
  -vlado

Vlado you are the champ :person_fencing: