Setup SSH Key and initial user using Ansible Playbook

Check out my YouTube video on this article

Checkout my blog of using automation of setting up an initial user https://devops4solutions.com/automate-ansible-playbook-deployment-on-aws-ec2/

In this blog we will Setup SSH Key and initial user using Ansible Playbook

To create new user on ubuntu system, you need the following things:

  1. Username/Password
  2. Public Key of the user
  3. You will first create a user on one machine. Machine can be your local workstation also
  4. Generate ssh-key for this
  5. Put the public key of that user to the remote hosts.
  6. Add that user to the sudoers.d file

Steps:

sudo -i
useradd -m -s /bin/bash devops
passwd devops
echo -e ‘devops\tALL=(ALL)\tNOPASSWD:\tALL’ > /etc/sudoers.d/devops
Image for post
Image for post

Generate a new SSH-key

  1. Login as a devops user
ssh-keygen -t rsa

It will generate the public and private key file for the devops user.

Image for post
Image for post

Now we have to add this public key to all the remote hosts.

Create Ansible playbook “add-user-ssh.yml”

  • Add a devops user
  • Now we want to disable the Password Authentication on all the remote hosts.This means no user/root user can login to the system by using password. They have to use the SSH keys only.
---
- hosts: all
vars:
- devops_password: 'abcddefsfdfdfdfdfdfdfdfdfdfd'
gather_facts: no
remote_user: ubuntu
become: true

Run the playbook

ansible-playbook add-user-ssh.yml -i hosts

Validate Disable Password Authentication

$ ssh servername -o PubkeyAuthentication=no

You will get the “Permission Denied(public key)

Devops Automation Enginneer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store