alpine-chroot

Various utilities for creating and using Alpine Linux chroots

git clone https://git.8pit.net/alpine-chroot.git

 1#!/bin/sh
 2# Creates a new alpine chroot.
 3
 4set -e
 5
 6##
 7# Default values
 8##
 9
10ARCH="$(uname -m)"
11RELEASE="edge"
12CHROOT="alpine-chroot-${RELEASE}-${ARCH}"
13MIRROR="http://dl-cdn.alpinelinux.org/alpine"
14APKTOOL="$(command -v apk 2>&1)"
15
16if [ -d "/etc/apk/keys" ]; then
17	KEYDIR="/etc/apk/keys"
18else
19	KEYDIR=""
20fi
21
22##
23# Functions
24##
25
26create_chroot() {
27	mkdir -p "${CHROOT}"/etc/apk/
28	if [ -n "${KEYDIR}" ]; then
29		cp -r "${KEYDIR}"/ "${CHROOT}"/etc/apk/keys
30	else
31		APKTOOL="${APKTOOL} --allow-untrusted"
32	fi
33
34	repos="main community"
35	if [ "${RELEASE}" = "edge" ]; then
36		repos="${repos} testing"
37	fi
38
39	echo "# Package repositories and mirrors" \
40		> "${CHROOT}"/etc/apk/repositories
41	for repo in ${repos}; do
42		echo "${MIRROR}/${RELEASE}/${repo}" \
43			>> "${CHROOT}"/etc/apk/repositories
44	done
45
46	"${APKTOOL}" --initdb \
47		--root "${CHROOT}" \
48		--arch "${ARCH}" \
49		--update-cache \
50		add alpine-base
51
52	mkdir -p "${CHROOT}"/proc
53	mount -v -t proc none "${CHROOT}"/proc
54
55	for directory in dev sys run; do
56		mkdir -p "${CHROOT}/${directory}"
57		mount -v --rbind "/${directory}" \
58			"${CHROOT}/${directory}"
59	done
60
61	cp -L /etc/resolv.conf "${CHROOT}"/etc/resolv.conf
62}
63
64##
65# Go for it!
66##
67
68if [ $(id -u) -ne 0 ]; then
69	echo "${0##*/} has to be started as root." 1>&2
70	exit 1
71fi
72
73while getopts a:c:r:k:m:p: flag; do
74	case "${flag}" in
75		a) ARCH="${OPTARG}"    ;;
76		c) CHROOT="${OPTARG}"  ;;
77		r) RELEASE="${OPTARG}" ;;
78		k) KEYDIR="${OPTARG}"  ;;
79		m) MIRROR="${OPTARG}"  ;;
80		p) APKTOOL="${OPTARG}" ;;
81	esac
82done
83
84if [ ! -x "${APKTOOL}" ]; then
85	echo "Couldn't find apk(1). Either add it to your \$PATH" 1>&2
86	echo "or specify the path to your apk tool using the -p" 1>&2
87	echo "command line flag. Also make sure that it is executable." 1>&2
88	exit 1
89fi
90
91if [ -d "${CHROOT}" ]; then
92	echo "Chroot '${CHROOT}' already exists."
93	exit 0
94fi
95
96create_chroot