lineinfile task fails on missing file, doesn't add line when it should

I’m pretty sure I’m doing something wrong here and am hoping some of you with more seasoning can help me figure it out.

I have a task:

  • name: Ensure /etc/hosts.deny has default ALL entry
    lineinfile: >
    dest=“/etc/hosts.deny”
    line=“ALL {{‘:’}} ALL”
    insertbefore=EOF
    create=yes
    state=present
    tags:
  • deny

When I run this on a system which doesn’t have an /etc/hosts.deny, I get this:

TASK: [compliance | Ensure /etc/hosts.deny has default ALL entry] **************
failed: [us202] => {“failed”: true, “parsed”: false}
Traceback most recent call last):
File “”, line 2200, in

File “”, line 395, in main

File “”, line 288, in present

File “”, line 178, in check_file_attrs

File “”, line 1199, in set_fs_attributes_if_different

File “”, line 1037, in set_mode_if_different

OSError: [Errorno 2] No such file or directory: ‘/etc/hosts.deny’

I would have expected ansible to create the file instead of erroring out.

If the file does exist but is empty or contains comments (and not the “ALL : ALL” line), ansible just reports an “ok” without adding the line.

What am I doing wrong?

Are you sure that EOF in <insertbefore=EOF> is valid ?

Try this:

(…)

tasks:

  • name: add a line to /etc/hosts.deny
    lineinfile:
    “dest=‘/etc/hosts.deny’
    line=‘ALL : ALL’
    insertafter=EOF
    create=yes
    state=present”
    (…)

I would have expected ansible to create the file instead of erroring out.

Do this first to make sure it exists:

  • name: Create /etc/hosts.deny
    shell: touch /etc/hosts.deny creates=/etc/hosts.deny

If the file already exists, this task also reports “ok”, though it doesn’t add the line, even to an empty file.

That yields a parsing error:

TASK: [compliance | Ensure /etc/hosts.deny has default ALL entry] ************************
failed: [us202] => {“failed”: true}
msg: line= is required with state=present

I switched it back to a single-line version but quoted as you showed, but the result is the same. A nonexistent file isn’t created, and an existing file isn’t modified.

When I do this and the file already exists, then it fails to add the line.

Again:

I strongly believe that EOF is not valid option here: <insertbefore=EOF>

Did you try his :

insertafter=EOF

Ugh. I just re-checked the online docs and you’re absolutely right. And that change fixed the task.

Thank you for pointing this out to me again, after I missed it on my first read. Problem solved!