Log In Without a Password

Last Updated:

Something that can get annoying is typing your password each time you SSH into remote machines. Depending on your password length and complexity, it's usually far less secure to use a manual password. We'll use a private/public key pair instead of a password to authenticate and login over SSH.

Generating SSH Key Pairs

To begin, we need to generate a SSH key pair. Instructions for checking if you have on already and generating a new one if not is located below. If you're generating a new one, you can just select the defaults by pressing enter.

# Check if you have a public key (identified by ".pub")
$ cat ~/.ssh/id_rsa.pub

# Generate a New Key Pair (Accepting the Defaults is fine)
$ ssh-keygen

Once you have your keypair generated, we're ready to add it to the remote machines using Ansible. It's VERY imporatnt to understand that you should ONLY give out your public “.pub” key and NEVER your private key, which is the same filename without the “.pub” extension.

Uploading the Public Key

The Ansible tasks to put in your playbook are pretty straightforward. The first ensures the local, hidden “.ssh” directory exists in the remote user's home. If a special directory does not exist and you try to upload a file to it, Ansible will not create the needed directories and will instead fail entirely. That's the reason for the first step.

Now, to upload the public key. We specify our local copy of “~/.ssh/id_rsa.pub”, the public key in our SSH directory, and upload it to the remote user's directory under the “authorized_keys” file. Since we're running as root (unless you already created another user), we are sure to mark the file as being owned by our remote user and set the permissions to “0600” so only our user will have access, instead of other users on the system.

# See the previous lesson to create a new User
- name: Allow login with SSH Public Key
  hosts: all
    user_username: ansible

    - name: Ensure the ~/.ssh directory exists
      file: path=/home//.ssh state=directory owner=textile mode=0700

    - name: Upload the local id_rsa.pub key
      remote_user: root
      copy: src=~/.ssh/id_rsa.pub dest=/home//.ssh/authorized_keys owner= group=sudo mode=0600

That's all there is to it. You should now be able to login using the same command as before, but now you wont be prompted for the password and will automatically be connected. Sweet.

$ ssh -p 2200 [user]@localhost