lineinfile creating line when regexp not found

Consider the following:

`

  • name: Change sshd_config settings
    lineinfile:
    path: /etc/ssh/sshd_config
    regexp: “{{ item.regexp }}”
    line: “{{ item.line }}”
    with_items:
  • {regexp: “^#.ClientAliveInterval.$”, line: “ClientAliveInterval 1800”}
  • {regexp: “^#.ClientAliveCountMax.$”, line: “ClientAliveCountMax 0”}
    notify:
  • restart ssh
    `

If I run this against a server multiple times, it will append the lines to the bottom of the file (even if present). According to the docs the line will only be applied if the regexp is found. I must be missing something. Any ideas? If the regexp isn’t found, I do want them appended to the file, but in this case I am getting duplicate entries.

sshd_config sample:

`

#PermitUserEnvironment no
#Compression delayed
ClientAliveInterval 1800
ClientAliveCountMax 0

X11Forwarding no

AllowTcpForwarding no

PermitTTY no

ForceCommand cvs server

ClientAliveInterval 1800
ClientAliveCountMax 0
ClientAliveInterval 1800
ClientAliveCountMax 0
ClientAliveInterval 1800
ClientAliveCountMax 0

`

Your regexps is checking for a line starting with hash #, but you don't have a line starting with # and contain ClientAliveInterval and ClientAliveCountMax.

And when you add a line that is also without # in the start of the line.

Remove your # in regexp.

But the original did have a #. I am showing you the results after running it a few times.

I removed the hash as you said (leaving in the wild) and it is working now. Thank you.