All HowTo's Ansible Ansible & Terraform Automation Cyber-Security Linux Scripting in Bash Ubuntu, Mint & Debian Linux

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


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

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

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


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.


  1. Hello,

    Could you please let me know what is missing in my code?

    Requirement: Need to add multiple users and their associated keys in different files on destination servers.

    – hosts: lb:app2
    – name: Add list of users
    # tags: system-user
    name: “{{ }}”
    uid: “{{ item.uid }}”
    groups: “{{ item.groups }}”
    comment: “{{ item.comment }}”
    password: ” {{ item.password }}”
    createhome: yes
    state: present
    – { name: testuser1, uid: 1002, groups: “wheel, automate”, comment: “{{ ‘Test Admin ID’ }}”, password: “{{ ‘$6$wsix5/A0$Qs46riLAIqJfolLAzqrMc8ZVVN8tBSZWaoDKco9gnqQJJqvf1hA3K9HHM8HtJXzcpA/ZnvagCPmiXsxl4ifzn.’ }}” }
    – { name: testuser2, uid: 1003, groups: “automate”, comment: “{{ ‘Test2 Admin ID’ }}”, password: “{{ ‘$6$gs3s6NUC$EwG7Lys4yxSLW8d1bceC1y4JH/ag0wmJt/AKnMg2DNHTy/HMfMYJV06SUyD89ZNioh2IfVmC14bbqFWWpfC9E/’ }}” }
    – name: Add .ssh directories
    name: “{{ }}”
    path: “/home/{{}}/.ssh”
    state: directory
    mode: 0700
    owner: “{{ }}”
    group: “{{|default( }}”
    – { name: testuser1, path: “{{ }}” }


    It does create a user but doesn’t create .ssh directory & I’m unable to push authorized_keys & authorize_keys2 files to different locations.


  2. hmm
    ERROR! ‘sudo’ is not a valid attribute for a Play

    The offending line appears to be:

    – hosts: all
    ^ here

Leave a Reply

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