如何使用 bash for 循环遍历 aws cli 结果? [描述图片]

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

目标:找到特定的 AMI 并将它们复制到另一个 AWS 区域。

使用 describe-images 及其过滤器我得到一个 ImageId 和名称列表,

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

结果:

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

然后我想使用循环将图像复制到另一个 AWS 区域:

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 它不起作用,因为 ${ami[0]}${ami[1]} 没有任何意义,但它们代表了我想要实现的目标。

我确实尝试过将列表转换为数组但没有成功。

谢谢。

这应该达到您的预期:

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