Last active
April 2, 2024 17:54
-
-
Save jpancoast/f0ddf3fc92f08e13693b592e5eb643ac to your computer and use it in GitHub Desktop.
I don't exec into containers enough to have this memorized, but I need to do it enough, so I whipped up this script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
ERROR=0 | |
# | |
# Default behavior is to run /bin/bash using podman, but if podman isn't installed, | |
# it SHOULD try docker | |
# | |
COMMAND="/bin/bash" | |
NAME_SERVICE="https://frightanic.com/goodies_content/docker-names.php" | |
CONTAINER_ID="" | |
RUNNER="podman" | |
if [[ -n "$1" ]]; then | |
CONTAINER_ID=$1 | |
else | |
ERROR=1 | |
fi | |
if [[ -n "$2" ]]; then | |
COMMAND=$2 | |
fi | |
if [ "$ERROR" -gt 0 ]; then | |
echo "There was an error, I need to know what container to run" | |
echo | |
echo "Usage:" | |
echo -e "\t$0 <CONTAINER_ID> <COMMAND>" | |
echo -e "\t<COMMAND> has a default of \"/bin/bash\"" | |
echo | |
exit 1 | |
fi | |
# | |
# Choose between podman or docker, if podman is installed, use that | |
# If no podman, assume docker | |
# | |
WHICH_PODMAN=$(which podman) | |
if [[ -z $WHICH_PODMAN ]]; then | |
RUNNER="docker" | |
fi | |
echo "Grabbing container name from $NAME_SERVICE" | |
CONTAINER_NAME=$(curl -s $NAME_SERVICE) | |
if ! [[ $CONTAINER_NAME =~ ^[a-z].*_[a-z].* ]]; then | |
echo "We couldn't get the container name from the service, generating a UUID and using that." | |
CONTAINER_NAME=$(uuidgen) | |
fi | |
# | |
# run the container, just in case it has an entrypoint defined | |
# | |
echo "Running container \"$CONTAINER_ID\" with Container Name \"$CONTAINER_NAME\" using \"$RUNNER\"" | |
$RUNNER run -d --rm --name $CONTAINER_NAME $CONTAINER_ID 1>/dev/null 2>/dev/null | |
# | |
# If the container DOESN'T have an entry point, it won't be running | |
# If it's not running, we just do a docker run. | |
# | |
# I wish I knew of a way to just examine a container with a docker command | |
# To tell whether it has an entrypoint or CMD or not :/ | |
# | |
docker_ps=$($RUNNER ps --all --no-trunc --format='{{json .}}' | jq | grep -i $CONTAINER_NAME) | |
echo "Execing Command: \"$COMMAND\" using \"$RUNNER\"" | |
if [[ -z $docker_ps ]]; then | |
$RUNNER run -ti --rm --name $CONTAINER_NAME $CONTAINER_ID $COMMAND | |
else | |
# | |
# exec the command in the running container | |
# | |
$RUNNER exec -it $CONTAINER_NAME $COMMAND | |
# | |
# stop the container | |
# | |
echo "Stopping the container \"$CONTAINER_NAME\" using \"$RUNNER\"" | |
$RUNNER stop $CONTAINER_NAME | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment