Schlagwort-Archive: blockinfile

Quick Ansible: Enforce SSHD configuration options

You need to enforce certain configuration options in sshd_config, while leaving the rest of the config to your colleagues? Your colleagues need to be able to change these parameters too, temporarily, but they should be reset after a certain time? And you wanna do it with Ansible? Read on.

- hosts: all
  - name: sshd configuration file update
      path: /etc/ssh/sshd_config
      insertbefore: BOF # Beginning of the file
      block: |
        PermitRootLogin no
        PubkeyAuthentication yes
        AuthorizedKeysFile .ssh/authorized_keys
        PasswordAuthentication no
      backup: yes
      validate: /usr/sbin/sshd -T -f %s

  - name: Restart SSHD
      name: sshd
      state: restarted

I’ll show you a playbook that sets the options PermitRootLogin, PubkeyAuthentication, AuthorizedKeysFile and PasswordAuthentication using the Ansible module blockinfile.

What happens here is that at the beginning of the file sshd_config a block is getting inserted containing the shown key-argument pairs. Inserting this block at the beginning of the file ensures that these lines are used, because first occurrence wins (see sshd_config(5)).

This playbook ensures the desired configuration that the user root is not permitted to login via ssh, public key authentication is enabled, the .ssh/authorized_keys file from user’s HOME directory should be used, and password authentication is disabled. Before /etc/ssh/sshd_config gets changed a backup is created and the new file is going to be validated prior to saving it.

The second task restarts the sshd service to make sure the desired config is going to be used.

Of course, any user with sudo or root access could edit the sshd_config file and restart the service to change the desired settings; and it might be OK to do so temporarily. To make sure any changes to the file will be reset to the desired config you could just run the playbook every 30 minutes per cron.

This was a really quick example of how to use ansible to set or change configuration settings. I hope you enjoyed it.