Indentify whether we are running an spot instance using AWS CLI

2 min read | by Jordi Prats

On a running instance we might want to be able to identify whether it is a spot or on demand instance. We can use awscli to identify it

First we'll need to get our instance id to be able to query the AWS API. To do so we can retrieve it from the instance's metadata as follows:

# wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
i-72f539ee7164c3101

Using this instance id we can now query AWS filtering for this instance to retrieve the attribute SpotInstanceRequests:

# aws ec2 describe-spot-instance-requests --filters Name=instance-id,Values="$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)" --region us-west-2 | jq -r '.SpotInstanceRequests'
[
  {
    "Status": {
      "Message": "Your spot request is fulfilled.",
      "Code": "fulfilled",
      "UpdateTime": "2022-05-22T19:34:28.000Z"
    },
(...)

When there is at least one object on this attribute, it means we are using a spot instance instead of an on demand. Using jq we can make it print spot or ondemand using the length function as follows:

# aws ec2 describe-spot-instance-requests --filters Name=instance-id,Values="$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)" --region us-west-2 | jq -r '.SpotInstanceRequests | if length > 0 then "spot" else "ondemand" end'
spot

Posted on 23/05/2022