debootstrap disk image

From Noah.org
Jump to navigationJump to search


This creates a minimal Debian Sid root filesystem with added networking and OpenSSH Server. The root password is set to password. This also adds your public SSH RSA key to the new environment's /root/.ssh/authorized_keys file.

#!/bin/bash

mktempdir () {
    CLEAN_NAME=$(echo $0 | sed -e "s/[^[:alpha:]]//g")
    NEW_TMPDIR=${TMPDIR-/tmp}/$(date "+tmp-${CLEAN_NAME}.$$.%H%M%S")
    (umask 077 && mkdir ${NEW_TMPDIR} 2>/dev/null && echo ${NEW_TMPDIR}) || return 1
    return 0
}

if ! LOOP=$(mktempdir); then
        echo "ERROR: Could not create a temporary directory for loop mount." >&2
        exit 1
fi

DISK_NAME=$1
DISK_SIZE=$2
HOSTNAME=$3
DOMAIN=$4
IP=$5
NM=$6
GW=$7
NS=$8
AUTHORIZED_KEYS=$9

# Allocate the disk image. Use fallocate if possible.
if type fallocate 2>/dev/null 1>/dev/null; then
        fallocate -l ${DISK_SIZE} ${DISK_NAME}
else
        dd if=/dev/zero of=${DISK_NAME} bs=1048576 count=$((1+${DISK_SIZE}/1048576)) of=${DISK_NAME}
fi
mkfs -F -t ext4 ${DISK_NAME}
mkdir -p ${LOOP}
mount -o loop ${DISK_NAME} ${LOOP}
# Debootstrap
debootstrap --include=openssh-server,vim sid ${LOOP} http://ftp.us.debian.org/debian/
#  FIXME: This sets the console to use the Xen virtual console, which only applies to Xen.
### sed -i -e 's/tty1/hvc0/g' ${LOOP}/etc/inittab
echo root:password | chroot ${LOOP} chpasswd
cp /etc/hosts ${LOOP}/etc/hosts
cat > ${LOOP}/etc/network/interfaces <<EOF_INTERFACES
# interfaces(5) file used by ifup(8) and ifdown(8)

source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    address ${IP}
    netmask ${NM}
    gateway ${GW}
EOF_INTERFACES
cat > ${LOOP}/etc/resolv.conf <<EOF_RESOLV_CONF
search ${HOSTNAME}.${DOMAIN}
nameserver ${NS}
EOF_RESOLV_CONF
# SSH
mkdir ${LOOP}/root/.ssh
chmod 700 ${LOOP}/root/.ssh
chown 0:0 ${LOOP}/root/.ssh
if [ -r "${AUTHORIZED_KEYS}" ]; then
        cat "${AUTHORIZED_KEYS}" > ${LOOP}/root/.ssh/authorized_keys
        chmod 600 ${LOOP}/root/.ssh/authorized_keys
        chown 0:0 ${LOOP}/root/.ssh/authorized_keys
fi
# inputrc
cat > ${LOOP}/etc/inputrc <<EOF_INPUTRC
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[2~": quoted-insert
"\e[3~": delete-char
"\e[1~": beginning-of-line
"\e[4~": end-of-line
set show-all-if-ambiguous on
set show-all-if-unmodified on
set completion-query-items -1
set skip-completed-text on
set page-completions off
set print-completions-horizontally on
$if bash
    set expand-tilde on
    set match-hidden-files off
    set visible-stats on
    set completion-ignore-case on
    set mark-directories on
    set mark-symlinked-directories on
$endif
EOF_INPUTRC