forked from tsari/docker-entrypoint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entrypoint.sh
49 lines (40 loc) · 1.12 KB
/
entrypoint.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash
# general good practice (stop on error):
set -e
function createUser() {
useradd --system --gid=$GID --uid=$UID $USER
}
function createGroup() {
groupadd --system --gid=$GID $USER
}
function renameUser() {
usermod -l $USER -d /home/$USER $1
}
function getUserById() {
echo $(getent passwd "$UID" | awk -F: '{print $1}')
}
function getGroupById() {
echo $(getent group "$GID" | awk -F: '{print $1}')
}
# Execute as user set in dockerfile, when no other user was passed in docker run command.
if [ -z "$GID" ] || [ -z "$USER" ]; then
exec "$@"
else
# check if group already exist and use this group or create a new one
existingGroup=$(getGroupById)
if [ -z "$existingGroup" ]; then
createGroup
existingGroup=$(getGroupById)
fi
# check if user already exists and use this user or create a new one
existingUser=$(getUserById)
if [ -z "$existingUser" ]; then
createUser
existingUser=$(getUserById)
fi
if [ $existingUser != $USER ]; then
renameUser $existingUser
fi
# execute as non-root user
exec sudo -E -u "$USER" "$@"
fi