Skip to content

Instantly share code, notes, and snippets.

@yuuan
Created December 10, 2021 10:09
Show Gist options
  • Save yuuan/965426e409c0164c84e28a717885e090 to your computer and use it in GitHub Desktop.
Save yuuan/965426e409c0164c84e28a717885e090 to your computer and use it in GitHub Desktop.
#!/bin/zsh -eu
function __help {
echo "Usage: ecs-exec [--profile <profile>] [--region <region>] [--cluster <cluster>] [--container <container>] [--base-name <product>] [<command>]"
exit 1
}
function __info() {
echo -e "\e[32m$*\e[m"
}
function __warn() {
echo -e "\e[31m$*\e[m" >&2
}
function __exec() {
local command; command="$*"
__info "> $command"
eval $command
}
function __die() {
__warn "$@"
exit 2
}
PROFILE=mfa
REAGION=ap-northeast-1
CLUSTER=
CONTAINER=
COMMAND=bash
while (( $# > 0 )); do
case "$1" in
-h|--help|help)
__help
;;
-p|--profile)
[ $# -ge 1 ] || __help
PROFILE="$2"
shift
;;
-r|--region)
[ $# -ge 1 ] || __help
REAGION="$2"
shift
;;
-c|--cluster)
[ $# -ge 1 ] || __help
CLUSTER="$2"
shift
;;
-C|--container)
[ $# -ge 1 ] || __help
CONTAINER="$2"
shift
;;
-b|--base-name)
CLUSTER="$1-cluster"
CONTAINER="$1"
;;
*)
COMMAND="$*"
break
;;
esac
shift
done
[ -n "$CLUSTER" -a -n "$CONTAINER" ] || __help
TASKS=$(\aws --profile "$PROFILE" --region "$REAGION" ecs list-tasks --cluster "$CLUSTER" | jq --raw-output ".taskArns[]" 2> /dev/null)
[ $? -eq 0 -a -n "$TASKS" ] || __die "Failed to get tasks."
case $(echo "$TASKS" | wc -l) in
0)
__die "No task found."
;;
1)
TASK="$TASKS"
;;
*)
TASK=$(echo "$TASKS" | peco)
;;
esac
HASH=$(echo "$TASK" | cut -d '/' -f 3 | sed -e "s/\"//g")
[ -n "$HASH" ] || __die "$HASH: Parse error."
__exec "aws --profile \"$PROFILE\" --region \"$REAGION\" ecs execute-command --cluster \"$CLUSTER\" --task \"$HASH\" --container \"$CONTAINER\" --interactive --command \"$COMMAND\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment