Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to loop through output from AWS Command Line Client

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.

output="$(aws ec2 describe-instances --filters 'Name=tag:Environment,Values=development' --query '[Reservations[*].Instances[*].PublicDnsName]' --output text)"

echo $output displays something like:

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.

And then try to iterate through the array:

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

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?

like image 408
Mikhail Janowski Avatar asked Apr 06 '16 13:04

Mikhail Janowski


1 Answers

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
like image 191
krishna_mee2004 Avatar answered Sep 19 '22 18:09

krishna_mee2004