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:
- Installs necessary packages based on the operating system (Debian/Ubuntu or RedHat/CentOS).
- Checks if users already exist.
- Generates passwords for new users.
- Creates new users with these passwords and assigns them to the sudo group.
- Sets passwords to expire upon the user's first login.
- Deploys SSH public keys for users.
- 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 == ""