-2

I am using shell script to get instance id and instance state on the basis of instance name. And for that I am using below query in shell script:

INSTANCE_NAME = "ABCDED00WEB"

INSTANCE_DETAIL=$(aws ec2 describe-instances \
  --filters "Name=tag:Name,Values=$INSTANCE_NAME" "Name=instance-state-name,Values=running" \
  --query "Reservations[*].Instances[*].[Tags[?Key=='Name'].Value[],InstanceId,State.Name]" \
  --output text)

Can someone confirm is the above query correct to get instance id and state? Also, how I can check the variable "INSTANCE_DETAIL" null or not and if not null, then how to retrieve Instance Id and state separately from the output variable - INSTANCE_DETAIL

1
  • You've presumably tested this. If the script fails then tell us how it fails. Stack Overflow is not a code review site. Commented Aug 25 at 14:54

1 Answer 1

2

It appears that your requirement is:

  • Given the 'Name' of an Amazon EC2 instance
  • Retrieve the Instance ID

To obtain the Instance ID:

aws ec2 describe-instances \
  --filters "Name=tag:Name,Values=YOUR_INSTANCE_NAME" \
  --query "Reservations[*].Instances[*].InstanceId" \
  --output text

This filters the response to the desired instance and then returns the Instance ID.

To store it in a shell variable, wrap it in a $():

INSTANCE_ID=$(aws ec2 describe-instances \
  --filters "Name=tag:Name,Values=YOUR_INSTANCE_NAME" \
  --query "Reservations[*].Instances[*].InstanceId" \
  --output text)

To test whether it came back with an empty response, you can use shell script like this:

if [ -z "$INSTANCE_ID" ]; then
  echo "No instance found with that Name tag."
  # do something else, maybe exit
  exit 1
else
  echo "Found instance: $INSTANCE_ID"
  # continue with your logic
fi

If you are wanting to do more complex logic, you might find it easier to use Python to script the above. You can use the boto3 library describe_instances() API call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.