Search code examples
amazon-web-servicesbashshelljq

How to loop over items from AWS CLI output?


aws ecs list-tasks --cluster dev-ec2s

this shows the list like this below, in this case three lines, but it can change.

"taskArns": [
    "arn:aws:ecs:ap-northeast-1:678100222222:task/dev-ec2-cls/1f3761101efd439f9d8959901e8f6095",
    "arn:aws:ecs:ap-northeast-1:678100222222:task/dev-ec2-cls/2bfb7cdfb9e64362b4df6b7f7e829236",
    "arn:aws:ecs:ap-northeast-1:678100222222:task/dev-ec2-cls/408879277ab24490b1b911b119c81414",

then I made this script,

task id such as 408879277ab24490b1b911b119c81414 is set as environment variable and throw to next command.

task_id=(aws ecs list-tasks --cluster dev-ec2s |
jq '.taskArns[0] | split(\"/\")[-1]' |
awk '{print substr($0, 2, length($0)-2)}')
aws ecs describe-tasks --cluster dev-ec2-cls --tasks "$task_id",

It can work on first row.

However I want to do this for every row.

How can I do this?


Solution

  • You can alter your JQ command by looping over the items ([]), then use split() and [-1] to select the task id's:

    jq -r '.taskArns[] | split("/")[-1]'
    

    This gives us a list of the task id's:

    1f3761101efd439f9d8959901e8f6095
    2bfb7cdfb9e64362b4df6b7f7e829236
    408879277ab24490b1b911b119c81414
    

    Afterwards you can iterate over the result using .. | while read task_id; do:

    jq -r '.taskArns[] | split("/")[-1]' "$(aws ecs list-tasks --cluster dev-ec2s )" \   
        |  while read task_id; do 
               aws ecs describe-tasks --cluster dev-ec2-cls --tasks "$task_id";
           done