From 08bc19909b5b838a3b022df377dcd69270202e2a Mon Sep 17 00:00:00 2001 From: ffrancis Date: Thu, 27 Aug 2026 21:01:57 +0530 Subject: [PATCH] CI: Handle existing UID/GID when creating container user Reuse existing group and user entries when the requested GID/UID are already present instead of failing during groupadd or useradd. Rename existing entries to the requested username when needed and update the account's primary group, home directory, and shell settings. Continue creating the group and user when the requested IDs do not already exist. Allow the script to work correctly with Ubuntu 24.04 base images that already ship with a default ubuntu user and group using UID/GID 1000. Signed-off-by: ffrancis --- create_user.sh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/create_user.sh b/create_user.sh index a4938e8..17534f9 100644 --- a/create_user.sh +++ b/create_user.sh @@ -6,8 +6,23 @@ USER_ID=${USER_ID:-1000} GROUP_ID=${GROUP_ID:-1000} # Create user +# Ubuntu 24.04 base images already ship a "ubuntu" user/group at 1000:1000, +# so reuse the existing group/account if it already occupies the requested +# GID/UID instead of failing on groupadd/useradd. +if getent group "$GROUP_ID" >/dev/null 2>&1; then + CURRENT_GROUP_NAME=$(getent group "$GROUP_ID" | cut -d: -f1) + [ "$CURRENT_GROUP_NAME" = "$USER" ] || groupmod -n "$USER" "$CURRENT_GROUP_NAME" +else groupadd -g "$GROUP_ID" "$USER" +fi + +if getent passwd "$USER_ID" >/dev/null 2>&1; then + CURRENT_USER_NAME=$(getent passwd "$USER_ID" | cut -d: -f1) + [ "$CURRENT_USER_NAME" = "$USER" ] || usermod -l "$USER" -d "/home/$USER" -m "$CURRENT_USER_NAME" + usermod -g "$GROUP_ID" -s /bin/bash "$USER" +else useradd -m -s /bin/bash -u "$USER_ID" -g "$GROUP_ID" "$USER" +fi # Add the user to sudo group apt-get update