lineinfile creating line when regexp not found

47 views
Skip to first unread message

John Harmon

unread,
Feb 26, 2019, 4:57:10 PM2/26/19
to Ansible Project
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




Kai Stian Olstad

unread,
Feb 27, 2019, 10:22:43 AM2/27/19
to ansible...@googlegroups.com
On 26.02.2019 22:57, John Harmon wrote:
> 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

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.


--
Kai Stian Olstad

John Harmon

unread,
Feb 27, 2019, 11:09:08 AM2/27/19
to Ansible Project
But the original did have a #.  I am showing you the results after running it a few times.

John Harmon

unread,
Feb 27, 2019, 11:11:06 AM2/27/19
to Ansible Project


On Wednesday, February 27, 2019 at 8:22:43 AM UTC-7, Kai Stian Olstad wrote:
I removed the hash as you said (leaving in the wild) and it is working now.  Thank you.
Reply all
Reply to author
Forward
0 new messages