Configuring Linux users and SSH keys with Ansible


This is my third post about doing things with Ansible. For more info about Ansible take a look at my other posts about Updating your Homelab with Ansible and Installing Hyper-V Linux Integration Services (LIS) with Ansible. For now lets continu with configuring Linux users and deploying SSH keys with Ansible.


Lets first start with showing my Ansible Playbook.

 - hosts: ubuntu
   gather_facts: yes
   become: true
   become_method: su
   become_user: root
   - name: Create users and groups
       - name: Create tizu group
              name: tizu
              state: present
       - name: Create ansible group
              name: ansible
              state: present
       - name: Create tizu user
              name: tizu
              shell: /bin/bash
              groups: tizu,adm,cdrom,sudo,dip,plugdev,lxd
       - name: Add tizu user to the sudoers
              dest: "/etc/sudoers.d/tizu"
              content: "tizu  ALL=(ALL)  NOPASSWD: ALL"
       - name: Deploy SSH Key to tizu user
         authorized_key: user=tizu
                         key="{{ lookup('file', '/home/tizu/.ssh/') }}"
       - name: Create ansible user
              name: ansible
              shell: /bin/bash
              groups: ansible,adm,cdrom,sudo,dip,plugdev,lxd
       - name: Add ansible user to the sudoers
              dest: "/etc/sudoers.d/ansible"
              content: "ansible  ALL=(ALL)  NOPASSWD: ALL"
       - name: Deploy SSH Key to ansible user
         authorized_key: user=ansible
                         key="{{ lookup('file', '/home/tizu/.ssh/') }}"

This playbook users a couple of buildin Ansible modules. First it starts creating the groups with the group module. Then it creates the users with the user module and adds the users to the specified groups. After the users are created and the groups are assigned the playbook creates a file for passwordless sudo with the copy module. After all that we deploy the SSH public key with the authorized_key module.

Creating your ed25519 SSH key

In the playbook example above we copy over the public key. We can create a ed25519 public key with the following command.

ssh-keygen -t ed25519 -C ""

Using ed25519 SSH keys has a couple of advantages:

  • It’s faster to generate and verify.
  • It’s more secure.
  • Keys are smaller.


As stated in my other blog posts Ansible is a very powerful tool for doing repeatable tasks and bootstrapping servers. Using the buildin Ansible modules for user,group and authorized_keys can make it very easy to deploy your users across all your servers.

Leave a Reply

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