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

Use proper index value with insertbefore on a one line file #46071

Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bugfixes:
- lineinfile - fix index out of range error when using insertbefore on a file with only one line (https://github.com/ansible/ansible/issues/46043)
2 changes: 1 addition & 1 deletion lib/ansible/modules/files/lineinfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create,
elif insertbefore and insertbefore != 'BOF':
# If the line to insert before is at the beginning of the file
# use the appropriate index value.
if index[1] == 0:
if index[1] <= 0:
if b_lines[index[1]].rstrip(b('\r\n')) != b_line:
b_lines.insert(index[1], b_line + b_linesep)
msg = 'line replaced'
Expand Down
31 changes: 31 additions & 0 deletions test/integration/targets/lineinfile/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,37 @@
that:
- result.stat.checksum == 'eca8d8ea089d4ea57a3b87d4091599ca8b60dfd2'

- name: Copy empty file to test with insertbefore
copy:
src: testempty.txt
dest: "{{ output_dir }}/testempty.txt"

- name: Add a line to empty file with insertbefore
lineinfile:
path: "{{ output_dir }}/testempty.txt"
line: top
insertbefore: '^not in the file$'
register: oneline_insbefore_test1

- name: Add a line to file with only one line using insertbefore
lineinfile:
path: "{{ output_dir }}/testempty.txt"
line: top
insertbefore: '^not in the file$'
register: oneline_insbefore_test2

- name: Stat the file
stat:
path: "{{ output_dir }}/testempty.txt"
register: oneline_insbefore_file

- name: Assert that insertebefore worked properly with a one line file
assert:
that:
- oneline_insbefore_test1 is changed
- oneline_insbefore_test2 is not changed
- oneline_insbefore_file.stat.checksum == '4dca56d05a21f0d018cd311f43e134e4501cf6d9'

###################################################################
# Issue 29443
# When using an empty regexp, replace the last line (since it matches every line)
Expand Down