Pari Baker
Pari Baker

Reputation: 716

Use grep to execute aws ecs 'execute' command

I would like to connect to my containers with aws ecs execute container command

aws ecs execute-command --cluster <cluster> --task <task_id> --container <container_name> --interactive --command "/bin/bash"

Currently I need to go to my aws dashboard and grab the task id but recently I realized I could just use

aws ecs list-tasks --cluster <cluster> --family <container> | grep -e "arn"

** Note I still need to grab the actual id from the result

I would like to run the second one and use the output to call the first one

I have tried:

aws ecs list-tasks --cluster <cluster>--family <family> | grep -e "arn" | aws ecs execute-command --cluster <cluster> --task $1 --container <container> --interactive --command "/bin/bash"

and

aws ecs execute-command --cluster <cluster>--task $(aws ecs list-tasks --cluster <cluster> --family <task-family> | grep -e \"arn\" | awk '{print $1}')  --container <container-name> --interactive --command "/bin/bash"

any ideas ?

Upvotes: 1

Views: 819

Answers (2)

Stephen Nelson
Stephen Nelson

Reputation: 939

You could use jq to parse the result instead of grep. For example:

  1. List available tasks in your cluster, returns a json response:
aws ecs list-tasks --cluster "$cluster" --region "$region"
  1. Extract the first task arn using jq
jq -r .taskArns[0]
  1. Run execute-command, using xargs to take the pipeline output as an arg:
xargs aws ecs execute-command --cluster "$cluster" --region "$region" --container "$container" --command "/bin/bash" --interactive --task

All together:

aws ecs list-tasks --cluster "$cluster" --region "$region" | \
  jq -r .taskArns[0] | \
  xargs aws ecs execute-command --cluster "$cluster" --region "$region" --container "$container" --command "/bin/bash" --interactive --task

I would recommend putting this into a bash script for ease of use, but if you want a one-line script this will do the trick.

Upvotes: 1

Pari Baker
Pari Baker

Reputation: 716

This is ugly but it worked

alias connect-to-app="aws ecs execute-command --cluster <cluster> --task \"$(aws ecs list-tasks --cluster <cluster> --family <family> | grep -e "arn" | grep -o '/<cluster>/\w*' | sed "s@/<cluster>/@@g")\" --container <container> --interactive --command \"/bin/bash"\"

Upvotes: 0

Related Questions