script-dump/lxc/get-lxc-idmap-config

81 lines
1.8 KiB
Bash
Executable File

#!/bin/sh
# Manage uid/gid maps for containers
#
# This script manages uids/gids assigned to certain containers or groups of containers. It uses /etc/subuid and
# /etc/subgid by default to save the information. All the ranges are owned by root as we don't want to support creation
# of containers by unprivileged users, but rather want to create unprivileged containers as root user.
USER_ID=0
FIRST_ID=1000000
DEFAULT_COUNT=65536
FILENAME="/etc/sub_____id"
get_filename () (
TYPE="${1}"
echo "${FILENAME}" | sed "s/_____/${TYPE}/"
)
find_range () (
TYPE="${1}"
NAME="${2}"
FILENAME="$(get_filename ${TYPE})"
grep -A 1 "^# ${NAME}$" "${FILENAME}" -A 1 | tail -n 1
)
get_last_range () (
TYPE="${1}"
grep "^${USER_ID}:" "$(get_filename ${TYPE})" | tail -n 1
)
get_new_range () (
TYPE="${1}"
LAST_RANGE=$(get_last_range "${TYPE}")
if [ "${LAST_RANGE}" = "" ]; then
NEW_ID=$FIRST_ID;
else
LAST_ID=$(echo "${LAST_RANGE}" | cut -d : -f 2)
LAST_COUNT=$(echo "${LAST_RANGE}" | cut -d : -f 3)
NEW_ID=$(( $LAST_ID + $LAST_COUNT ))
fi
echo "${USER_ID}:${NEW_ID}:${DEFAULT_COUNT}"
)
append_range () (
TYPE="${1}"
FILENAME="$(get_filename ${TYPE})"
NAME="${2}"
RANGE="${3}"
printf "# ${NAME}\n${RANGE}\n" >> "${FILENAME}"
)
usage () {
echo "usage: get-lxc-idmap-config <u|g> <container-group-name>"
exit 1
}
TYPE="${1}"
if [ "${TYPE}" = "" || "${TYPE}" == "--help" || "${TYPE}" == "-h" ]; then
usage
fi
NAME="${2}"
if [ "${NAME}" = "" ]; then
usage
fi
RANGE=$(find_range "${TYPE}" "${NAME}")
if [ "${RANGE}" = "" ]; then
RANGE=$(get_new_range "${TYPE}")
if [ "${RANGE}" = "" ]; then
exit 1
fi
append_range "${TYPE}" "${NAME}" "${RANGE}"
fi
RANGE_START=$(echo ${RANGE} | cut -d : -f 2)
RANGE_COUNT=$(echo ${RANGE} | cut -d : -f 3)
printf "lxc.idmap = %s 0 %s %s\n" "${TYPE}" "${RANGE_START}" "$(( ${RANGE_COUNT} - 1))"