Search code examples
bashloopsamazon-ec2aws-cliamazon-ami

how to iterate over aws cli result using bash for loop ? [describe-images]


Goal: find specific AMI's and copy them to another AWS region.

using describe-images and its filter i get a list of ImageId and Name,

AMI_LIST=$(aws ec2 describe-images --filters "Name=tag:Name,Values=*one*,*two*,*three*,*four*" \
"Name=state,Values=available" "Name=tag:Name,Values=${CUSTOMER_NAME}*" \
--query 'Images[*].{ID:ImageId,NAME:Name}' --output text)
echo $AMI_LIST

result:

ami-036ba4ef9fa1d148d big394_one_1 ami-06d13684f11138f1f big394_two_3 ami-0706803a11e21946d big394_two_1 ami-094043f896db39243 big394_two_2 ami-0c11ff60c981c2273 big394_three_1 ami-0d0b30fcc69f30af8 big394_four_1

then i want to copy the images to another AWS region using a loop:

for ami in $AMI_LIST; do
aws ec2 copy-image --source-image-id ${ami[0]} --source-region us-east-1 --region us-west-2 --name ${ami[2]}
done

ofc it does not work because ${ami[0]} and ${ami[1]} has no meaning, but they represent what i would like to achieve.

i did try to play with converting the list to array but without success.

Thanks.


Solution

  • This should achieve what you expected :

    aws ec2 describe-images --filters "Name=tag:Name,Values=*one*,*two*,*three*,*four*" \
    "Name=state,Values=available" "Name=tag:Name,Values=${CUSTOMER_NAME}*" \
    --query 'Images[*].{ID:ImageId,NAME:Name}' --output text \
    | while read ami name; do
        aws ec2 copy-image --source-image-id $ami --source-region us-east-1\
                           --region us-west-2 --name $name
    done