Skip to content

Instantly share code, notes, and snippets.

@tappoz
Created September 10, 2019 17:00
Show Gist options
  • Save tappoz/7fa01a03f0dc8b96bb897350dbc8763a to your computer and use it in GitHub Desktop.
Save tappoz/7fa01a03f0dc8b96bb897350dbc8763a to your computer and use it in GitHub Desktop.
How to add an SSH user to an existing Linux VM

Setup an SSH user on an existing VM

Create the user and setup the SSH key

$ scp ${PATH_TO_SSH_KEYS}id_rsa.pub existing-user@${MACHINE_IP_ADDRESS}:.
$ ssh existing-user@${MACHINE_IP_ADDRESS}
$ sudo su
# useradd -s /bin/bash -m my-new-username
# mkdir /home/my-new-username/.ssh
# cp id_rsa.pub /home/my-new-username/.ssh/
# touch /home/my-new-username/.ssh/authorized_keys
# cat id_rsa.pub >> /home/my-new-username/.ssh/authorized_keys
# rm id_rsa.pub
# chown -R my-new-username:my-new-username /home/my-new-username/.ssh
# chmod 700 /home/my-new-username/.ssh
# chmod 600 /home/my-new-username/.ssh/authorized_keys

Test the SSH connection: ssh my-new-username@${MACHINE_IP_ADDRESS} -i ${PATH_TO_SSH_KEYS}id_rsa

Make sure the ansible user is in the sudo group

$ groups my-new-username
my-new-username : my-new-username
$ sudo su
# usermod -aG sudo my-new-username

Then use visudo to make the ansible user able to work without password: my-new-username ALL = (ALL) NOPASSWD: ALL

Different approach

The VMs need to be aware of the SSL public key of the ansible user. This means adding it to their ~/.ssh/authorized_keys. This could be done either modifying that file or using a combination of:

  • ssh-keyscan ${REMOTE_VM_IP_ADDR} > ~/.ssh/knwon_hosts to retrieve the SSL public key of the remote VM
  • ssh-copy-id my-user-at-the-vm@${REMOTE_VM_IP_ADDR} to copy our own SSL public key to the remote VM ~/.ssh/authorized_keys file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment