Ansible lineinfile duplicates line

后端 未结 3 1123
無奈伤痛
無奈伤痛 2021-02-01 02:00

I have a simple file at /etc/foo.txt. The file contains the following:

#bar

I have the following ansible playbook task to uncomment the line ab

相关标签:
3条回答
  • 2021-02-01 02:31

    The problem is the task's regex only matches the commented out line, #bar. To be idempotent, the lineinfile task needs to match both the commented and uncommented state of the line. This way it will uncomment #bar but will pass bar unchanged.

    This task should do what you want:

    - name: test lineinfile
      lineinfile: 
        backup=yes
        state=present
        dest=/etc/foo.txt
        regexp='^#?bar'
        line='bar'
    

    Note the only change was adding a "?" to the regex.

    0 讨论(0)
  • 2021-02-01 02:32

    You need to add backrefs=yes if you don't want to change your regular expression.

    - name: test lineinfile
      lineinfile: backup=yes state=present dest=/etc/foo.txt
                  regexp='^#bar' backrefs=yes
                  line='bar'
    

    This changes the behavior of lineinfile from:

     find
     if found
       replace line found
     else
       add line
    

    to:

     find
     if found
       replace line found
    

    In other words, this makes operation idempotent.

    0 讨论(0)
  • 2021-02-01 02:44

    See https://github.com/ansible/ansible/issues/4531.

    The solution is to not replace the commented out line, but to add an additional line, while keeping the original there.

    0 讨论(0)
提交回复
热议问题