Creating a dedicated ZFS zone for each system user upon account creation

Published on 2016-09-10 15:37:28

This is a script designed to be run as root on the zone to which we delegated the zone zones/users, and will create zones/users/john with the specified quota, and sets the usual options of group, home and shell.


#!/usr/bin/bash

HELP_TEXT=$(cat <<EOF
Usage: ./add_new_user.sh [opts]
Options:
        -h              Print this help and exit
        -u user         Set the username. If not present then a prompt will appear
        -g group        Set the primary group. Calls groupadd, defaults to \$user
        -s shell        Set the shell. Defaults to /usr/bin/bash
        -d home_dir     Set the home directory. Defaults to /home/users/\$user
   -q quota   Set the filesystem quota. Defaults to 20g
EOF
)

NEW_USER=0
NEW_USER_ZONE=0
NEW_USER_HOME=0
NEW_USER_SHELL=0
NEW_USER_GROUP=0
NEW_USER_QUOTA=0

while getopts "hu:g:s:d:q:" GETOPTS_OPTION; do
   case $GETOPTS_OPTION in
      h)
         echo "${HELP_TEXT}"
         exit 0
         ;;
      u)
         NEW_USER=$OPTARG
         ;;
      g)
         NEW_USER_GROUP=$OPTARG
         ;;
      s)
         NEW_USER_SHELL=$OPTARG
         ;;
      d)
         NEW_USER_HOME=$OPTARG
         ;;
      q)
         NEW_USER_QUOTA=$OPTARG
         ;;
      \?)
         echo "Invalid option: -${OPTARG}" >&2
         exit 1
         ;;
      :)
         echo "Option -${OPTARG} requires an argument." >&2
         exit 1
         ;;
   esac
done

[[ $NEW_USER == 0 ]] && read -r -p "Enter name of new user: " NEW_USER
[[ $NEW_USER_ZONE == 0 ]] && NEW_USER_ZONE="zones/users/${NEW_USER}"
[[ $NEW_USER_HOME == 0 ]] && NEW_USER_HOME="/home/users/${NEW_USER}"
[[ $NEW_USER_SHELL == 0 ]] && NEW_USER_SHELL="/usr/bin/bash"
[[ $NEW_USER_GROUP == 0 ]] && NEW_USER_GROUP="${NEW_USER}"
[[ $NEW_USER_QUOTA == 0 ]] && NEW_USER_QUOTA="20g"

echo "Adding new user ${NEW_USER} with the following properties:"
echo "Zone: ${NEW_USER_ZONE}"
echo "Home: ${NEW_USER_HOME}"
echo "Shell: ${NEW_USER_SHELL}"
echo "Group: ${NEW_USER_GROUP}"
read -r -n 1 -s -p "Press any key to continue or Control-C to exit..."
echo

zfs create $NEW_USER_ZONE
zfs set quota=$NEW_USER_QUOTA $NEW_USER_ZONE
groupadd $NEW_USER_GROUP
useradd \
   -d $NEW_USER_HOME \
   -s $NEW_USER_SHELL \
   -g $NEW_USER_GROUP \
   $NEW_USER
chown $NEW_USER:$NEW_USER_GROUP $NEW_USER_HOME
passwd $NEW_USER