首页 > 解决方案 > 如何使用 bash for 循环迭代 aws cli 结果?[描述图像]

问题描述

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

使用describe-images它的过滤器,我得到一个 ImageId 和 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

结果:

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]}没有任何意义,但它们代表了我想要实现的目标。

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

谢谢。

标签: bashloopsamazon-ec2aws-cliamazon-ami

解决方案


这应该达到您的预期:

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

推荐阅读