Use Ansible To Create Multiple Users And Authorize SSH Keys

Ansible is a great tool, easy to understand and way more powerful along with its simplicity. If you have ever needed to create multiple ucreate multiple users using ansible and distribute authorized ssh keyssers along with their ssh keys what did you do? Possibly, its an easy task to do using a “bash” script. Of course, it is! What if you had to make sure all users exist on all of your production servers (say 50 Servers and 20 users)? There will be a chaos to maintain the users and specially there ssh keys.  This is exactly, where the Ansible comes in handy. Just setup a playbook with all instructions and you are good to go.

Here we will look into the Ansible to create multiple users and authorize the SSH Keys. Here we assume that the Users do not exist on the remote hosts and SSH Private/Public Key Pair is already generated for required users. Also the management has decided to use single private key per user for all servers.

Open your favorite editor and write the "playbook.yml” file as following:

- hosts: webservers #modify your server list
  remote_user: root

  - include_vars: users.yml
  - name: Creating users to Jump Server
    user: name="{{ item.username}}"
    with_items: "{{ users }}"

  - name: Placing SSH Key to Authorized Key
  #please note that this code assumes as if the public-private key pair is generated, all public users (created above) have public keys copied at one place i.e. keyfiles directory for the ease
    authorized_key: user="{{item.username}}" key="{{ lookup('file', './keyfiles/authorized_keys.{{ item.username}}.pub')}}"
    with_items: "{{ users }}"

if you noticed in the above playbook, it is assumed that the  public keys for all users are residing in keyfiles directory relative to the current path of the playbook. Since, we need a list of users to be created, we can add another playbook called users.yml  as shown below:

  - username: oleg
  - username: ahmed
  - username: ray
  - username: ria
  - username: jack

That’s it! Run your playbook using ansible-playbook command and let it show the magic.

$# ansible-playbook playbook.yml

Example Git Hub Repo Can Be Pulled From here

Share your thoughts