lineinfile - use correct index value when inserting at the end (#63696)

This commit is contained in:
Sam Doran 2019-10-22 10:39:58 -04:00 committed by GitHub
parent 05c8e33983
commit 92cd13a2cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 2 deletions

View file

@ -0,0 +1,2 @@
bugfixes:
- lineinfile - use correct index value when inserting a line at the end of a file (https://github.com/ansible/ansible/issues/63684)

View file

@ -409,8 +409,14 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create,
elif insertafter and index[1] != -1:
# Don't insert the line if it already matches at the index
if b_line != b_lines[index[1]].rstrip(b'\n\r'):
# Don't insert the line if it already matches at the index.
# If the line to insert after is at the end of the file use the appropriate index value.
if len(b_lines) == index[1]:
if b_lines[index[1] - 1].rstrip(b'\r\n') != b_line:
b_lines.append(b_line + b_linesep)
msg = 'line added'
changed = True
elif b_line != b_lines[index[1]].rstrip(b'\n\r'):
b_lines.insert(index[1], b_line + b_linesep)
msg = 'line added'
changed = True

View file

@ -1107,3 +1107,33 @@
- insertbefore_test4_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7'
- insertbefore_test5 is not changed
- insertbefore_test5_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7'
# Test inserting a line at the end of the file using regexp with insertafter
# https://github.com/ansible/ansible/issues/63684
- name: Create a file by inserting a line
lineinfile:
path: "{{ output_dir }}/testend.txt"
create: yes
line: testline
register: testend1
- name: Insert a line at the end of the file
lineinfile:
path: "{{ output_dir }}/testend.txt"
insertafter: testline
regexp: line at the end
line: line at the end
register: testend2
- name: Stat the file
stat:
path: "{{ output_dir }}/testend.txt"
register: testend_file
- name: Assert inserting at the end gave the expected results.
assert:
that:
- testend1 is changed
- testend2 is changed
- testend_file.stat.checksum == 'ef36116966836ce04f6b249fd1837706acae4e19'