Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stable-2.8] lineinfile - use correct index value when inserting at the end (#63696) #63795

Merged
merged 1 commit into from Nov 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelogs/fragments/lineinfile-use-correct-index-value.yaml
@@ -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)
10 changes: 8 additions & 2 deletions lib/ansible/modules/files/lineinfile.py
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions test/integration/targets/lineinfile/tasks/main.yml
Expand Up @@ -1096,3 +1096,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'