This is an Ansible role to create a local Linux user

Manual Process

Create an ansible user on the host and make it a member of the adm and sudo groups. Edit the sudoers file (or add an config file to the sudoers.d directory) so it can execute sudo without a password. Give the user a complex password and once you have SSH authentication working lock the users so the only way to log in is using an SSH key.

Ansible role: host-adduser

This is called with a when clause so that domain-joined systems don't run it since I have an ansible use in the domain too.

File structure

host-adduser

   defaults

      main.yaml

   files

      sudo-30-ansible

   meta

      main.yaml

   tasks

      main.yaml

defaults/main.yaml

--- # Ansible Role Defaults
# Default for Ansible role add-user

local_ansible_user: "ansible"
local_ansible_shell: "/bin/bash"
local_ansible_group: "adm"
local_ansible_grouplist: "sudo"

...

files/sudo-30-ansible

# Allow ansible user to get root privs without password

ansible     ALL=(ALL) NOPASSWD: ALL

meta/main.yaml

--- # Meta for role host-adduser
galaxy_info:
  #role_name: host-adduser
  author: Richard Neighbour
  description: Configure a local user for hosts not in a domain
  license: GPLv3
  min_ansible_version: "2.9"

  platforms:
  - name: Ubuntu
    versions:
    - all

  galaxy_tags: []

dependencies: []

...

tasks/main.yaml

--- # Ansible Role Tasks
# Ansible role: Add user

# Runs after host-ssh
# Still needs to use password login as initial user until this role succeeds.

- name: Set UMASK in login.defs
  become: true
  ansible.builtin.lineinfile:
    path: /etc/login.defs
    regex: '^UMASK'
    line: 'UMASK   027'

- name: Add Ansible admin user
  become: true
  ansible.builtin.user:
    name: "{{ local_ansible_user }}"
    state: present
    password_lock: yes
    update_password: on_create
    shell: "{{ local_ansible_shell }}"
    group: "{{ local_ansible_group }}"
    groups: "{{ local_ansible_grouplist }}"
#    append: yes
    create_home: yes
    home: "/home/{{ local_ansible_user }}"
    comment: "Ansible admin user"


- name: Drop sudoers config file
  become: true
  ansible.builtin.copy:
    src: sudo-30-ansible
    dest: /etc/sudoers.d/30-ansible
    owner: root
    group: root
    mode: '0440'

...