Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save feythin/f0715d6cebc961181cc139768c25928f to your computer and use it in GitHub Desktop.
Save feythin/f0715d6cebc961181cc139768c25928f to your computer and use it in GitHub Desktop.

Revisions

  1. @muloka muloka created this gist Nov 28, 2013.
    57 changes: 57 additions & 0 deletions ansible-lineinfile-examples.yml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    ## credit: http://fabian-affolter.ch/blog/the-lineinfile-module-of-ansible/
    ---
    - hosts: alpine_install
    user: root

    tasks:
    # - name: create a complete empty file
    # command: /usr/bin/touch /test/test.conf

    - name: create a new file with lineinfile
    lineinfile: dest=/test/test.conf
    regexp='^' line=''
    state=present
    create=True

    - name: add a string to the new file
    lineinfile: dest=/test/test.conf
    regexp='^'
    line='Hello, World!'
    state=present

    - name: add a multiline string to the file and delete the string from before
    # Be aware, with the given regex the string will be added everytime the playbook runs
    lineinfile: dest=/test/test.conf
    regexp='^'
    line='#This is a comment\n#Another comment\n#Another comment, again\n#Again a comment\n#The last comment'
    state=present

    - name: add a single line, in this case the same as the comment but uncommented
    lineinfile: dest=/test/test.conf
    regexp='^Another'
    insertafter='^#Another'
    line='Another comment, no longer a comment'
    state=present

    - name: remove the line '#Again a comment'
    lineinfile: dest=/test/test.conf
    regexp='^#Again'
    state=absent

    - name: add a new string at the beginning of the file
    lineinfile: dest=/test/test.conf
    regexp='^This'
    insertbefore=BOF
    line='This is no longer a comment'

    - name: add a new string before the match
    lineinfile: dest=/test/test.conf
    regexp='^Another'
    insertbefore='^#Another'
    line='Another comment, no longer'

    - name: add a new string at the end of the file
    lineinfile: dest=/test/test.conf
    regexp=''
    insertafter=EOF
    line='The latest entry'