Skip to content

Instantly share code, notes, and snippets.

@discordianfish
Last active February 17, 2023 13:37
Show Gist options
  • Save discordianfish/7fedcc1dac11d61384ddaf7df5cc7445 to your computer and use it in GitHub Desktop.
Save discordianfish/7fedcc1dac11d61384ddaf7df5cc7445 to your computer and use it in GitHub Desktop.
chatgpt generated ecs cli
#!/bin/bash
ECS_CONTEXT_FILE=~/.ecs/context
# Check if the ECS context file exists
if [ -f "$ECS_CONTEXT_FILE" ]; then
# Read the active cluster from the ECS context file
ECS_CLUSTER=$(cat "$ECS_CONTEXT_FILE")
fi
case "$1" in
use)
# Switch active cluster and update ECS context file
if [ -z "$2" ]; then
echo "Please specify the cluster name."
exit 1
fi
ECS_CLUSTER="$2"
echo "$ECS_CLUSTER" > "$ECS_CONTEXT_FILE"
echo "Active ECS cluster set to: $ECS_CLUSTER"
;;
get)
case "$2" in
clusters)
# List clusters in the region
aws ecs list-clusters
;;
services)
# List services in the active cluster
if [ -z "$ECS_CLUSTER" ]; then
echo "Please use 'ecs use <cluster>' to set the active cluster."
exit 1
fi
aws ecs list-services --cluster "$ECS_CLUSTER"
;;
tasks)
# List tasks in the active cluster
if [ -z "$ECS_CLUSTER" ]; then
echo "Please use 'ecs use <cluster>' to set the active cluster."
exit 1
fi
aws ecs list-tasks --cluster "$ECS_CLUSTER"
;;
*)
echo "Usage: ecs get [clusters|services|tasks]"
exit 1
;;
esac
;;
exec)
# Run interactive command in container of the specified task
if [ -z "$2" ]; then
echo "Please specify the task ID."
exit 1
fi
if [ -z "$ECS_CLUSTER" ]; then
echo "Please use 'ecs use <cluster>' to set the active cluster."
exit 1
fi
TASK_ARN=$(aws ecs list-tasks --cluster "$ECS_CLUSTER" --output text --query "taskArns[?contains(@,'$2')][0]")
if [ -z "$TASK_ARN" ]; then
echo "Task not found."
exit 1
fi
shift
shift
CONTAINER_NAME=""
while [ $# -gt 0 ]; do
case "$1" in
-c)
shift
CONTAINER_NAME="$1"
shift
;;
*)
echo "Invalid argument: $1"
exit 1
;;
esac
done
if [ -z "$CONTAINER_NAME" ]; then
CONTAINER_NAME=$(aws ecs describe-tasks --cluster "$ECS_CLUSTER" --tasks "$TASK_ARN" --query "tasks[0].containers[0].name" --output text)
fi
if [ -z "$CONTAINER_NAME" ]; then
echo "Container not found."
exit 1
fi
aws ecs execute-command --cluster "$ECS_CLUSTER" --task "$TASK_ARN" --container "$CONTAINER_NAME" --interactive
;;
*)
echo "Usage: ecs [use|get|exec]"
exit 1
;;
esac
Write me a bash script "ecs" that uses the aws cli to interact with aws ecs tasks supporting the following commands:
- ecs use <cluster>: Switch active cluster to <cluster>, store in ~/.ecs/context
- ecs get services: List services
- ecs get tasks: List tasks in cluster
- ecs exec <task> [-c container]: Run (interactive) command in container
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment