All Linux HowTo's Scripting HowTo's Security HowTo's

Use Ansible to Add Users and their SSH public Keys on Multiple Linux Servers

This article demonstrates how to create an Ansible PlayBook that will add users to multiple Linux systems and add their public SSH key allowing them to login securely.

Install Ansible on the host that you’ll use to target each of the Linux host you want the new users on.

sudo yum install ansible

Generate or obtain the public SSH key(s) that you’ll be deploying to the remote Linux host. In my case i will generate the keys myself but you may obtain them (ideally you would) from the users themselves.

mkdir -p ~/ansible/files
ssh-keygen -t rsa -f ~/ansible/files/authorized_keys.myuser

Use the following PlayBook file as an example (the user i’m creating on the remote Linux host is “myuser”). The file for the below should be “~/ansible/playbook.yml”.

---
- hosts: all

  sudo: yes

  tasks:

  - user: name=myuser comment="My User" group=wheel

  - name: Placing key
    authorized_key: user=myuser key="{{ lookup('file', './files/authorized_keys.myuser.pub') }}"

Specify which hosts this user will be created on by creating the “~/ansible/hosts” file with the list of hosts:

host1.example.local
host2.example.local
host3.example.local
host4.example.local

Now you can run the Playbook as follows:

cd ~ansible
ansible-playbook playbook.yml -i ./hosts

If you’re key isn’t working or you don’t have on the remote server, try adding the “–ask-pass” to the end of the above command.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.