Automating User Management with Bash on Google Cloud Platform
In the fast-paced world of DevOps, automation is key. Managing user accounts efficiently is crucial, especially when onboarding new developers. This article details a Bash script designed to automate user and group creation on an Ubuntu system within Google Cloud Platform (GCP).
Prerequisites
Before diving into the script, ensure you have the following:
Access to Google Cloud Platform
An Ubuntu VM instance
Basic knowledge of Bash scripting
Script Overview
The script, create_users.sh
, reads a text file containing usernames and groups, formatted as user;groups
. It then creates users, assigns them to specified groups, sets up home directories with proper permissions, generates random passwords, and logs all actions.
Breakdown of the Script
Shebang and Variables
The script begins with #!/bin/bash
, which specifies the shell interpreter. Key variables include:
LOG_FILE
: Location for logging actions.PASSWORD_FILE
: Secure file for storing user passwords.USER_FILE
: Input file containing usernames and groups.
Input Validation
The script checks if an input file is provided:
bashCopy codeif [ -z "$USER_FILE" ]; then
echo "Usage: $0 <name-of-text-file>"
exit 1
fi
This ensures the script has the necessary data to proceed.
User and Group Creation
For each line in the input file, the script extracts the username and groups, creates a user with a personal group, and adds them to additional groups:
bashCopy codeuseradd -m -s /bin/bash -G "$groups" "$username"
It also handles errors if a user already exists, logging these occurrences.
Password Generation
Random passwords are generated using openssl
:
bashCopy codepassword=$(openssl rand -base64 12)
These passwords are securely stored in /var/secure/user_passwords.csv
, accessible only by the owner.
Logging
Actions are logged to /var/log/user_management.log
, providing a record of user creation and any issues encountered.
Permissions
Home directories are set with proper ownership and permissions:
bashCopy codechown "$username:$username" "/home/$username"
chmod 700 "/home/$username"
This ensures privacy and security for each user's data.
Conclusion
This Bash script simplifies user management, making onboarding faster and more secure. By automating routine tasks, SysOps engineers can focus on more critical issues, enhancing overall productivity.
For more insights into DevOps and automation, explore the HNG Internship and consider hiring skilled developers through HNG Hire.
Subscribe to my newsletter
Read articles from Henry Davies directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by