diff --git a/library/files/lineinfile b/library/files/lineinfile
index ba842e15e2a..12f8dc89a7d 100644
--- a/library/files/lineinfile
+++ b/library/files/lineinfile
@@ -369,14 +369,19 @@ def main():
         # so we need to know if we should specifically unquote it.
         should_unquote = not is_quoted(line)
 
+        # always add one layer of quotes
+        line = "'%s'" % line
+
         # Replace escape sequences like '\n' while being sure 
         # not to replace octal escape sequences (\ooo) since they
         # match the backref syntax.
         if backrefs:
             line = re.sub(r'(\\[0-9]{1,3})', r'\\\1', line)
-        line = module.safe_eval(pipes.quote(line))
+        line = module.safe_eval(line)
 
-        # Now remove quotes around the string, if needed
+        # Now remove quotes around the string, if needed after
+        # removing the layer we added above
+        line = unquote(line)
         if should_unquote:
             line = unquote(line)
 
diff --git a/test/integration/roles/test_lineinfile/tasks/main.yml b/test/integration/roles/test_lineinfile/tasks/main.yml
index 34c9db6f4f5..8d58cbba6f2 100644
--- a/test/integration/roles/test_lineinfile/tasks/main.yml
+++ b/test/integration/roles/test_lineinfile/tasks/main.yml
@@ -337,4 +337,22 @@
     that:
     - "result.stat.md5 == '29f349baf1b9c6703beeb346fe8dc669'"
 
+- name: insert a line into the quoted file with a single quote
+  lineinfile: dest={{output_dir}}/test_quoting.txt line="import g'"
+  register: result
+
+- name: assert that the quoted file was changed
+  assert:
+    that:
+    - result.changed
+
+- name: stat the quote test file
+  stat: path={{output_dir}}/test_quoting.txt
+  register: result
+
+- name: assert test md5 matches after backref line was replaced
+  assert:
+    that:
+    - "result.stat.md5 == 'fbe9c4ba2490f70eb1974ce31ec4a39f'"
+
 ###################################################################