Skip to main content

sdnog users creation using Ansible

Ansible Playbook: Sudo Users creation with SSH Keys

This Ansible playbook configures users with sudo privileges, sets up SSH keys, and requires users to change their password upon first login.

Overview

The playbook performs the following tasks:

  1. Installs necessary packages based on the operating system (Debian/Ubuntu or RedHat/CentOS).
  2. Checks if users already exist.
  3. Generates passwords for new users.
  4. Creates new users with these passwords and assigns them to the sudo group.
  5. Sets passwords to expire upon the user's first login.
  6. Deploys SSH public keys for users.
  7. Sends the password to users via email.

Variables

  • users: A list of users to be created, each with the following attributes:
    • username: The username for the new account.
    • ssh_key: The SSH public key to be deployed for the user.
    • email: The email address where the password will be sent.

Tasks

Task 1. Install Required Packages

For Debian/Ubuntu

  - name: needed packages are installed (Debian/Ubuntu)
    apt:
      name: "{{ item }}"
      state: latest
    loop: ["sudo", "openssh-server", "mailutils"]
    when: ansible_facts['os_family'] == "Debian"
  

For RedHat/CentOS

  - name: needed packages are installed (RedHat/CentOS)
    yum:
      name: "{{ item }}"
      state: latest
    loop: ["sudo", "openssh-server", "mailx"]
    when: ansible_facts['os_family'] == "RedHat"
  
Task 2. Check if Users Exist and Set Facts for New Users
  - name: Check if users exist and set fact for new users
    command: "getent passwd {{ item.username }}"
    register: user_check
    loop: "{{ users }}"
    changed_when: false
    failed_when: false
Task 3. Generate Passwords for New Users
  - name: Generate passwords for new users
    set_fact:
      user_passwords: "{{ user_passwords | default({}) | combine({item.item.username: lookup('password', '/dev/null length=15 chars=ascii_letters+digits')}) }}"
    loop: "{{ user_check.results }}"
    when: item.stdout == ""