Skip to content

Instantly share code, notes, and snippets.

@nickistre
Last active April 25, 2024 18:41
Show Gist options
  • Save nickistre/30f0a73e945975f2d1b2fb821a473f81 to your computer and use it in GitHub Desktop.
Save nickistre/30f0a73e945975f2d1b2fb821a473f81 to your computer and use it in GitHub Desktop.
Helper script to have apps in docker run as user and group of project folder.
# Add to Docker image and include in other scripts with (using the current directory
# for the user_id and group_id):
# source /path/to/run_as_user_setup_source.sh "$(pwd)"
# Requires commands:
# sudo
# Tested on BASH
# Run apps or scripts as the user of the used directory with:
# run_as_user command -args
# The project folder which is binded from the host system. Used passed in folder.
RUN_AS_PROJECT_FOLDER="${1}"
# Get user id and group id of project folder.
RUN_AS_USER_ID=$(stat -c '%u' "${RUN_AS_PROJECT_FOLDER}")
RUN_AS_GROUP_ID=$(stat -c '%g' "${RUN_AS_PROJECT_FOLDER}")
# Check if user and group already exist.
RUN_AS_USER_NAME="$(id -u -n ${RUN_AS_USER_ID} 2> /dev/null)"
RUN_AS_GROUP_NAME="$(getent group ${RUN_AS_GROUP_ID} | cut -d: -f1)"
# Setup user name and group name
# By default, create a random string of 13 lowercase letters.
if [[ -z "${RUN_AS_GROUP_NAME}" ]]; then
# Create group as it doesn't exist
RUN_AS_GROUP_NAME="$(tr -dc a-z </dev/urandom | head -c 13 ; echo '')"
groupadd -g ${RUN_AS_GROUP_ID} -o ${RUN_AS_GROUP_NAME}
fi
if [[ -z "${RUN_AS_USER_NAME}" ]]; then
# Create user as it doesn't exist
RUN_AS_USER_NAME="$(tr -dc a-z </dev/urandom | head -c 13 ; echo '')"
# The home directory to use within the directory within the container.
RUN_AS_USER_HOME="/home/${RUN_AS_USER_NAME}"
useradd -u ${RUN_AS_USER_ID} -o -d "${RUN_AS_USER_HOME}" -s /bin/bash -M -g ${RUN_AS_GROUP_ID} ${RUN_AS_USER_NAME} && \
mkdir -p "${RUN_AS_USER_HOME}" && \
chown "${RUN_AS_USER_ID}":"${RUN_AS_GROUP_ID}" "${RUN_AS_USER_HOME}"
fi
# Change to the shell you wish to use
RUN_AS_SHELL=/bin/sh
# Function definition
function run_as_user() {
# Change the following to add custom environment variables
OVERRIDE_ENV="${OVERRIDE_ENV:-}"
# List of comma-separated Environment variables to preserve into the new environment
PRESERVE_ENV="${PRESERVE_ENV:-}"
sudo -n -u "#${RUN_AS_USER_ID}" -g "#${RUN_AS_GROUP_ID}" --preserve-env="${PRESERVE_ENV}" -- "${RUN_AS_SHELL}" -c "${OVERRIDE_ENV} ${*}"
}
# Add setting up any custom folders for user below. E.q.:
#mkdir -p "${USER_HOME}/.cache" 2> /dev/null
#mkdir -p /go/pkg 2> /dev/null
#chown -R "${USER_ID}":"${GROUP_ID}" "${USER_HOME}/.cache" /go/pkg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment