title: How to cleanly edit sshd_config for basic security options in an ansible playbook?
body: <p>I'm trying to write a playbook that cleanly edits /etc/ssh/sshd_config so that it has <code>PasswordAuthentication no</code> and <code>PermitRootLogin no</code>.</p>
  
  <p>I can think of a few ways that are all problematic.</p>
  
  <p>Firstly, I could delete all the lines matching <code>PasswordAuthentication|PermitRootLogin</code> using lineinfile, and then append two new lines that I want, but i) this can fail non-atomically AND ii) appending lines at the end can mix them up with 'Match' blocks, which can typically appear at the end.</p>
  
  <p>I could replace every line matching <code>^(# *)?PasswordAuthentication</code> with <code>PasswordAuthentication no</code>, also using lineinfile, but that doesn't work if a matching line doesn't already exist. Also, if there are multiple matching lines, I'll have duplicate <code>PasswordAuthentication no</code> lines.</p>
  
  <p>I could use a template for the entire file, but that means I need to specify everything, including HostKey, but I don't want to specify everything and want to leave the other options the way they were originally setup.</p>
  
  <p>None of the above ways are satisfactory because of the problems listed. Is there a clean way that makes the desired changes reliably, is idempotent, and does not leave the system in a bad state if it fails halfway?</p>