From 6341cc23fb6cdc61715f98e0d6a7a12f3a0de686 Mon Sep 17 00:00:00 2001 From: Ahti Kitsik Date: Mon, 9 Jun 2014 19:58:45 +0300 Subject: [PATCH] Bugfix to lineinfile to properly handle files with no newline at EOF when using insertafter=EOF. Looks like #6881 is also affected by this bug. Currently when using lineinfile insertafter=EOF for a file that has no newline then the added line is not prefixed with a newline. As a concrete example, ubuntu distro default /etc/ssh/sshd_config has no newline so lineinfile module cannot be used to add a new line to the end of the file. --- files/lineinfile | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/files/lineinfile b/files/lineinfile index be6209e2b7b..3f81d048950 100644 --- a/files/lineinfile +++ b/files/lineinfile @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- # (c) 2012, Daniel Hokka Zakrisson +# (c) 2014, Ahti Kitsik # # This file is part of Ansible # @@ -25,7 +26,7 @@ import tempfile DOCUMENTATION = """ --- module: lineinfile -author: Daniel Hokka Zakrisson +author: Daniel Hokka Zakrisson, Ahti Kitsik short_description: Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression. description: @@ -110,7 +111,7 @@ options: validate: required: false description: - - validation to run before copying into place. The command is passed + - validation to run before copying into place. The command is passed securely so shell features like expansion and pipes won't work. required: false default: None @@ -251,6 +252,11 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create, # if insertafter=/insertbefore didn't match anything # (so default behaviour is to add at the end) elif insertafter == 'EOF': + + # If the file is not empty then ensure there's a newline before the added line + if len(lines)>0 and not (lines[-1].endswith('\n') or lines[-1].endswith('\r')): + lines.append(os.linesep) + lines.append(line + os.linesep) msg = 'line added' changed = True