Preventing User Lockout with Ansible ssh-hardening

1 minute read

I’m continuing to really enjoy working with Ansible. It meets the needs I have for server configuration, and has a lot of great community resources.

One thing that is crucial to any server setup is ensuring that your SSH configuration is sound.

A great role that I’ve used for my Ansible SSH configuration is ssh-hardening.

A pitfall that the author points out in the Readme, is that it is possible that your user account will be locked out after the role is applied. I’ve found this to be particularly true for the ubuntu account on EC2 servers.

In order to make sure I can continue to get in to that user with my AWS key-pair, I’ve started adding this to a role that runs right after the ssh-hardening role in my playbooks.

- name: Check if Ubuntu is locked
  command: grep -q "ubuntu:!:" /etc/shadow
  register: check_ubuntu_lock
  ignore_errors: True
  changed_when: False
  become: true

- name: Unlock Ubuntu
  command: usermod -p "*" ubuntu
  when: check_ubuntu_lock.rc == 0
  become: true

This checks the shadow file for the ! indicator that would lock the account, and sets the password has to * which will unlock the account, but also ensure that the user can only log in via ssh keys.

Tags:

Updated: