Skip to content

Instantly share code, notes, and snippets.

@trevor-vaughan
Last active January 23, 2021 23:44
Show Gist options
  • Save trevor-vaughan/23911c41277773f798330122ca1a9366 to your computer and use it in GitHub Desktop.
Save trevor-vaughan/23911c41277773f798330122ca1a9366 to your computer and use it in GitHub Desktop.
Extract a container image and run the container against the underlying directory
#!/bin/sh
set -e
container_name="centos:8"
clean_container_name=$( echo "${container_name}" | tr ':' '_' )
export_file="${clean_container_name}.tar"
if [ -f "${export_file}" ]; then
echo "Found ${export_file}; remove the file to re-extract"
else
id=$( podman run -id $container_name )
podman export $id > "${export_file}"
podman rm -f $id
fi
export_file=$( readlink -f "${export_file}" )
target_dirs=( $(tar -tf "${export_file}" | grep '^[[:alnum:]]\+/$' | tr -d '/') )
dirs_to_remove="dev tmp run proc sys lost+found media mnt"
for dir in ${dirs_to_remove[@]}; do
target_dirs=( "${target_dirs[@]/$dir}" )
done
container_volumes=()
for dir in ${target_dirs[@]}; do
volume_name="${clean_container_name}_${dir}"
set +e
volume_info=$( podman volume inspect "${volume_name}" 2>/dev/null )
if [ $? -ne 0 ]; then
set -e
podman volume create "${volume_name}" >& /dev/null
volume_info=$( podman volume inspect "${volume_name}" )
fi
set -e
container_volumes+=("-v ${volume_name}:/${dir}:Z")
(
cd $( echo "${volume_info}" | jq -r '.[] | .Mountpoint' )
tar --skip-old-files --strip-components=1 -xf "${export_file}" "${dir}/"
)
done
echo "${container_name} volumes extracted and ready"
echo "Run the following command to execute:"
echo "podman run $( IFS=$' '; echo "${container_volumes[*]}" ) --systemd=always -id $container_name /usr/sbin/init"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment