Automating User On-Boarding With Bash Scripting.
Published: 2024-07-02 21:32:29

## Introduction

In Modern day IT administration, automation must become part of your day-to-day activity. This is because automation is crucial in maintaining uniformity, and security policies of the organization as well as avoiding time wastage in doing the same things over again.

One of those repetitive tasks automation takes care of is creating of user or simply a new user on-boarding in an organization.

This blog post briefly examines a simple way that the user onboarding process on Linux Operating Systems can be automated using bash scripting. 

This article references HNG task 1 for the DevOps track.
HNG is a non-profit organization that provides internship and learning programs for individuals seeking to gain real-life experience in IT.
You can find out more about HNG using the links below.
[HNG INTERNSHIP](https://hng.tech/internship)
[HNG LEARN](https://hng.tech/learn)


##Automating User On-Boarding Using Bash

The script we are going to use will enable us to achieve the following:
- Create users
- Generate random passwords for the users
- Store the passwords in a secure file
- Create groups for the users
- Assign the users to their personal and additional groups.
- Log all actions to a log file.

This script can be reused over and over again as it is not limited to just the one-time creation of users and also it can be modified to perform additional tasks or take out what is not needed.

Let's break down the provided script step by step to understand what it does piece by piece.

- First off, we set the interpreter of the script which states what shell we will be using to run the script.
`#!/bin/bash`

- Define log file and password file locations.

```
# Define the log file location for logging
LOG_FILE="/var/log/user_management.log"
# Define the location of the password file where the generated passwords for each user will be stored
PASSWORD_FILE="/var/secure/user_passwords.txt"

```
 
- Define the location of the users_txt file where we have entered the names of the users with their respective groups.

```
# Define the location of the user file for the creation of users and groups
USER_FILE="users.txt"
```

- Ensure the log and password files exist.

```
# Ensure log file and password file exist and set proper permissions
touch "$LOG_FILE" "$PASSWORD_FILE"
chmod 600 "$LOG_FILE" "$PASSWORD_FILE"
```

- Create and Ensure the /var/secure directory exists with appropriate permissions.

```
# Create /var/secure directory if it doesn't exist
if [ ! -d "/var/secure" ]; then
    mkdir -p /var/secure
    chmod 700 /var/secure
    echo "$(date) - Created /var/secure directory." | tee -a "$LOG_FILE"
fi
```

- Generate Password Function for user password generation.

```
# Function to generate a random 12-character alphanumeric password
generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
```
- Confirming that the users_txt file to be used for user creation exist
# Ensure the users.txt file exists

```
if [ ! -f "$USER_FILE" ]; then
    log_message "User file $USER_FILE does not exist. Exiting."
    exit 1
fi
```



###Creation of users, personal groups and password generation
- Read users from the users.txt file.
- Check if the user exists, if not, create the user and their personal group.
- Generate and set a password for the user.
- Save the password securely.

```
# Step 1: Create Users, groups and generate passwords for the users
log_message "Starting user creation process..."
while IFS=';' read -r username groups; do
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    if [ -z "$username" ]; then
        log_message "Empty username found. Skipping."
        continue
    fi

    if id "$username" &>/dev/null; then
        log_message "User $username already exists."
        continue
    fi

    if groupadd "$username"; then
        if useradd -m -g "$username" "$username"; then
            log_message "User $username and group $username created."

            password=$(generate_password)
            if echo "$username:$password" | chpasswd; then
                log_message "Password set for user $username."
                echo "$username:$password" >> "$PASSWORD_FILE"
                log_message "Password for user $username saved to $PASSWORD_FILE."
            else
                log_message "Failed to set password for user $username."
            fi
        else
            log_message "Failed to create user $username."
        fi
    else
        log_message "Failed to create group $username."
    fi
done < "$USER_FILE"

```

###Group Assignment Process

- Read users and their groups from the users.txt file.
- Check if the user exists, if not log a message and skip to the next user.
- Add the user to specified groups, creating groups if they don't exist.

```
# Step 2: Add Users to Groups
log_message "Starting group assignment process..."
while IFS=';' read -r username groups; do
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    if [ -z "$username" ]; then
        log_message "Empty username found. Skipping."
        continue
    fi

    if ! id "$username" &>/dev/null; then
        log_message "User $username does not exist. Skipping group assignment."
        continue
    fi

    IFS=',' read -ra GROUP_ARRAY <<< "$groups"
    for group in "${GROUP_ARRAY[@]}"; do
        group=$(echo "$group" | xargs)
        if [ -z "$group" ]; then
            log_message "Empty group name for user $username. Skipping."
            continue
        fi

        if ! getent group "$group" > /dev/null 2>&1; then
            if groupadd "$group"; then
                log_message "Group $group created."
            else
                log_message "Failed to create group $group."
                continue
            fi
        fi

        if usermod -aG "$group" "$username"; then
            log_message "User $username added to group $group."
        else
            log_message "Failed to add user $username to group $group."
        fi
    done
done < "$USER_FILE"

log_message "User and group creation process completed."

```

###Verify the User accounts that have been created

- You can verify if the account was created successfully by using the id user command to show the user and the groups 

```

id user_name

```

- You can also retrieve the secure passwords by viewing the contents of the password file 

```
sudo cat /var/secure/user_passwords.csv

```

- You can view the logs for the operation by using this command

```
sudo cat /var/log/user_management.log

```


##Conclusion
Creating a bash script to manage user accounts can make adding new employees or users much easier. By following the steps in this guide, you can build a reliable script that:

- Creates user accounts
- Adds users to groups
- Sets secure passwords
- Logs actions for transparency and audits.

 [Link to the script](https://github.com/Eben-DevOps/User-Creation-Script.git)

Thanks to HNG for making this possible. You can also join their premium channel to enjoy more benefits, learn and network in a great environment. by using this link to join [HNG Premium](https://hng.tech/premium)