Bash 脚本循环遍历 AWS 命令行客户端的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36452555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to loop through output from AWS Command Line Client
提问by Mikhail Janowski
I'm getting a list of EC2 instances and then trying to loop through them but for some reason I'm not able to get the loop to work.
我正在获取 EC2 实例列表,然后尝试遍历它们,但由于某种原因,我无法使循环正常工作。
output="$(aws ec2 describe-instances --filters 'Name=tag:Environment,Values=development' --query '[Reservations[*].Instances[*].PublicDnsName]' --output text)"
output="$(aws ec2 describe-instances --filters 'Name=tag:Environment,Values=development' --query '[Reservations[*].Instances[*].PublicDnsName]' --output text)"
echo $output
displays something like:
echo $output
显示如下内容:
ec2-55-55-555-555.eu-west-1.compute.amazonaws.com
ec2-66-66-666-666.eu-west-1.compute.amazonaws.com
Then I create an array like this:
然后我创建一个这样的数组:
instances=(${output//'\n'/ })
echo ${instances[0]}
and echo ${instances[1]}
gives the correct output.
echo ${instances[0]}
并echo ${instances[1]}
给出正确的输出。
And then try to iterate through the array:
然后尝试遍历数组:
for i in $instances; do echo instance: "$i"; done
for i in $instances; do echo instance: "$i"; done
But I get:
但我得到:
instance: ec2-55-55-555-555.eu-west-1.compute.amazonaws.com ec2-66-66-666-666.eu-west-1.compute.amazonaws.com
实例:ec2-55-55-555-555.eu-west-1.compute.amazonaws.com ec2-66-66-666-666.eu-west-1.compute.amazonaws.com
Instead of:
代替:
instance: ec2-55-55-555-555.eu-west-1.compute.amazonaws.com
instance: ec2-66-66-666-666.eu-west-1.compute.amazonaws.com
What am I doing wrong? And is there a better way to loop through the results, maybe rather using the json output format?
我究竟做错了什么?有没有更好的方法来循环结果,也许是使用 json 输出格式?
回答by krishna_mee2004
I am not sure if you got an answer for this question. Will this help?
我不确定你是否得到了这个问题的答案。这会有帮助吗?
for dns in $(aws ec2 describe-instances --region ap-northeast-1 --query 'Reservations[*].Instances[*].PublicDnsName' --output text) ; do echo $dns ; done
回答by Ion G.
For windows cli:
对于 Windows cli:
aws ec2 describe-instances --query "Reservations[].Instances[].InstanceId" > instances
aws ec2 describe-instances --query "Reservations[].Instances[].InstanceId" > 实例
FOR /f %i IN (instances) DO aws ec2 terminate-instances --instance-ids %i
FOR /f %i IN (instances) DO aws ec2 terminate-instances --instance-ids %i