Files
azure-cli/azure-cli

117 lines
3.1 KiB
Bash
Executable File

#!/usr/bin/env bash
# Set default values
ACCOUNT_NAME="$(id -un)"
USER_NAME="ubuntu"
EXTRA_ARGS=()
LIST=""
VOLUME_NAME=""
while [ $# -gt 0 ]; do
case $1 in
--list|-l)
LIST=true
break
;;
--name|-n)
VOLUME_NAME="$2"
shift 2
;;
--account|-a)
ACCOUNT_NAME="$2"
shift 2
;;
--user|-u)
USER_NAME="$2"
shift 2
;;
--volume|-v)
read VOL_SRC VOL_DST < <(echo "$2" | tr ':' ' ')
EXTRA_ARGS+=("--mount" "type=bind,source=${VOL_SRC},target=${VOL_DST}")
shift 2
;;
--)
# Stop parsing arguments
shift
break
;;
--help|-h)
cat <<EOF
Usage: $(basename "$0")
[--list|-l]
or
[--account|-a ACCOUNT_NAME]
[--name|-n VOLUME_NAME]
[--user|-u USER_NAME]
[--volume|-v HOST_PATH:CONTAINER_PATH]
[--]
[additional args to pass to container]
EOF
exit 0
;;
*)
break
;;
esac
done
IMAGE_NAME="skoszewski/azure-cli:latest"
# Check if a custom volume name is provided
if [ -z "$VOLUME_NAME" ]; then
# Normalize account name for use in volume name
VOLUME_NAME="account_${ACCOUNT_NAME/@/_at_}"
VOLUME_NAME="${VOLUME_NAME//[-.]/_}"
fi
# Find container runtime
if command -v podman &> /dev/null; then
CMD="podman"
EXTRA_ARGS+=("--hostname $(hostname -s)")
elif command -v docker &> /dev/null; then
CMD="docker"
EXTRA_ARGS+=("--hostname $(hostname -s)")
elif command -v container &> /dev/null; then
# Apple container command line tool
CMD="container"
else
echo "Error: No usable container runtime was found." >&2
exit 1
fi
if [ -n "$LIST" ]; then
echo "Available accounts:"
$CMD volume ls --format json | jq -r '.[] | select(.labels | has("account")) | .labels.account'
exit 0
fi
# Check, if the account volume exists, if not create it
# This ensures persistent storage for the Azure CLI configuration
if [ ! "FOUND" = "$($CMD volume ls --format json | jq -r --arg name "$VOLUME_NAME" --arg account "$ACCOUNT_NAME" '.[] | select(.name == $name or .labels.account == $account) | "FOUND"')" ]; then
echo "A volume for account '$ACCOUNT_NAME' does not exist."
read -p "Would you like to create one? (y/n) " -r RESPONSE
if [[ ! "$RESPONSE" =~ ^[Yy]$ ]]; then
echo "Aborting."
exit 1
fi
echo "Creating volume $VOLUME_NAME for Azure CLI configuration."
if ! $CMD volume create "$VOLUME_NAME" --label "account=$ACCOUNT_NAME" &> /dev/null; then
echo "Error: Failed to create volume $VOLUME_NAME." >&2
exit 1
fi
fi
EXTRA_ARGS+=(
"--mount" "type=volume,source=$VOLUME_NAME,target=/home/${USER_NAME}"
"--mount" "type=bind,source=$(pwd),target=/workdir"
"--env" "ACCOUNT_NAME=$ACCOUNT_NAME"
"--name" "azure-cli-$VOLUME_NAME"
"--workdir" "/workdir"
)
# Run the container
$CMD run --rm -it ${EXTRA_ARGS[@]} $IMAGE_NAME --user "$USER_NAME" "$@"