Setting up Password-less Authentication for Ansible: A Step-by-Step Guide

When automating tasks with Ansible, setting up password less SSH authentication is crucial for smooth operations. There are two main ways to achieve this: Public Key Authentication and Password Authentication. Below is a step-by-step guide for both methods.


Public Key Authentication

This is the most secure and common method for password-less SSH access. However, I encountered an error while using the ssh-copy-id command, which returned "ERROR: No identities found". Upon investigation, I realized that my .ssh folder didn’t contain the public/private key pair. To resolve this issue, here’s what I did:

  1. Generate SSH Keys: I ran the following command to generate the SSH key pair:

     ssh-keygen
    
  2. Copy the Public Key to the EC2 Instance:
    After generating the keys, I used the following command to copy the public key to the EC2 instance. Replace the path to the private key and the EC2 instance's public IP:

     ssh-copy-id -f "-o IdentityFile <path-to-private-key>" ubuntu@<instance-public-ip>
    

    For example, if your private key is located in ~/.ssh/my-key.pem and your instance’s public IP is 12.34.56.78, the command would look like:

     ssh-copy-id -f "-o IdentityFile ~/.ssh/my-key.pem" ubuntu@12.34.56.78
    

This solved the issue, and I was able to authenticate to the instance without entering a password.


Password Authentication

Alternatively, you can use password authentication. Here's how:

  1. Enable Password Authentication:
    You need to update the SSH configuration to allow password-based logins.

    • Edit the file /etc/ssh/sshd_config on your EC2 instance.

    • Change PasswordAuthentication from no to yes and uncomment the line.

  2. Set the Password:
    Set a password for the ubuntu user with the following command:

     sudo passwd ubuntu
    
  3. Copy the Public Key Using Password Authentication:
    Once the password is set, you can copy the public key using ssh-copy-id from your local machine:

     ssh-copy-id ubuntu@<instance-public-ip>
    

    You’ll be prompted to enter the password you just set.

Test the Connection:
After completing the above steps, you can now log in to your EC2 instance without entering a password using:

ssh ubuntu@<instance-public-ip>

Conclusion

While both methods allow you to set up password less authentication, Public Key Authentication is the more secure and recommended approach, especially when working with automation tools like ansible.