Reputation: 2805
I've got a bash script calling for the IPs of various instances based on a parameter from the user. Right now if their query doesn't match the script doesn't return anything at all, not even null
. I'd love to incorporate some kind of error handling to prompt the user to retry. This could be anything from an inbuilt AWS function to a custom error message, I'm not picky.
My script is as follows;
#!/usr/bin/env bash
set -e
#READ ARGUMENTS PASSED IN - expects stack name
if [ "$#" != 1 ]; then
echo "Illegal number of parameters. Expecting 1: stack name"
exit 1
fi
name=$1
aws ec2 describe-instances --query "Reservations[].Instances[].[PublicIpAddress,Tags[?Key=='Name'].Value]" --filter Name=tag:Name,Values=${name} --output text
If it succeeds I'll get something like
00.00.00.000
name-of-instance
but if it fails I get nothing.
Is there a way to prompt the user or otherwise show an error message if an aws describe-instances returns no matches?
Upvotes: 0
Views: 3522
Reputation: 52433
output=`aws ec2 describe-instances --query "Reservations[].Instances[].[PublicIpAddress,Tags[?Key=='Name'].Value]" --filter Name=tag:Name,Values=${name} --output text`
if [ -n "$output" ]; then
echo "$output"
else
echo "No such instance $name exists"
fi
Upvotes: 3
Reputation: 200988
Capture the output into a variable first like so:
output=$(aws ec2 describe-instances --query "Reservations[].Instances[].[PublicIpAddress,Tags[?Key=='Name'].Value]" --filter Name=tag:Name,Values=${name} --output text)
Then check the content of output
. If there is something there just echo it to the screen. If there isn't, show your custom error message.
Upvotes: 3