Create users from a CSV with a script kept in Git

applied · 60 min · Objective 2.6

Task

Automate account creation: read a CSV of new starters, create each account with the right groups and home folder, skip anyone who already exists, and log what was done. Keep the script in a Git repository, change it once through a commit, and roll the change back -- scripts are code and get code's discipline.

Steps

  1. Write lab/users/starters.csv with header username,fullname,group and eight made-up users across two groups. Create both groups.
  2. Write lab/users/create-users.sh that reads the CSV, skips the header, checks with id whether each user exists, and otherwise runs useradd -m -c <fullname> -G <group> <username>, logging created or skipped with a timestamp to lab/users/run.log. It exits non-zero if the CSV is missing.
  3. Initialise a Git repository in lab/users, commit the script and CSV, and run the script twice. Save the second run's log lines to lab/users/second-run.log.
  4. Change the script to also set an expiry date on each new account, commit it, then revert that commit with git revert. Save git log --oneline to lab/users/history.txt.
  5. Delete the test accounts and their home folders.

Verify

These checks run in a POSIX shell: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. A stock Windows PowerShell or Command Prompt has no awk or grep, so there the first line fails.

grep -c 'created' lab/users/run.log
grep -c 'skipped' lab/users/second-run.log
grep -c 'created' lab/users/second-run.log
grep -Eic 'revert' lab/users/history.txt
wc -l < lab/users/history.txt

The first run created eight accounts, and the second skipped all eight and created none -- the script is safe to run twice, which is what makes it safe to schedule. The history shows at least three commits, including the revert: the change and its undoing are both on record.

Notes

The Windows equivalent is Import-Csv piped to New-ADUser in a domain, with the same rule: check before creating, log every action, and never put a password in the CSV or the script.

This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.