AWS CLI – How to Check if a Specific RDS Instance Exists

amazon-rdsaws-clibash

I want my bash script to detect, if an AWS RDS instance with a specific name exists already.

This is what I tried:

#!/usr/bin/env bash

DBINSTANCEIDENTIFIER=greatdb

EXISTINGINSTANCE=$(aws rds describe-db-instances \
    --db-instance-identifier="$DBINSTANCEIDENTIFIER" \
    --output text\
    )

I would expect an empty list, or a zero as a result – but I receive an error message:

An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: DBInstance greatdb not found.

Does anyone know how to properly find out if an instance exists or not, without an error message?

Best Answer

Notice the constraint in the docs when using --db-instance-indentifier:

--db-instance-identifier (string)

  The user-supplied instance identifier. If this parameter is specified, 
  information from only the specific DB instance is returned. This parameter 
  isn't case-sensitive.

Constraints:   
  - If supplied, must match the identifier of an existing DBInstance

So you can only use this option if you know the DB in fact exists.

Using queries

To search for a DB that may or may not exist you'll have to use the --query option:

$ aws rds describe-db-instances \
    --query 'DBInstances[*].[DBName,DBInstanceIdentifier]' --output text

The DBINstances JSON structure is accessible in the awscli help:

$ aws rds describe-db-instances help --output text
...
...
       {
          "DBInstances": [
              {
                  "PubliclyAccessible": false,
                  "MasterUsername": "mymasteruser",
                  "MonitoringInterval": 0,
                  "LicenseModel": "general-public-license",
                  ...
                  ...
                  "DBName": "sample",
                  ...
                  ...
                  "DBInstanceStatus": "stopped",
                  "EngineVersion": "5.6.27",
                  "AvailabilityZone": "us-east-1e",
                  "StorageType": "standard",
                  "StorageEncrypted": false,
                  "DBInstanceClass": "db.t2.micro",
                  "DbInstancePort": 0,
                  "DBInstanceIdentifier": "mydbinstance-1"
              }
          ]
      }
...
...

Using Filters

Another simple solution for the initial question is, to use the --filters parameter. The query will return either the instance identifier (if the instance exists), or an empty string (if it does not exist):

#!/usr/bin/env bash

DBINSTANCEIDENTIFIER="greatdb"
EXISTINGINSTANCE=$(aws rds describe-db-instances \
    --query 'DBInstances[*].[DBInstanceIdentifier]' \
    --filters Name=db-instance-id,Values=$DBINSTANCEIDENTIFIER \
    --output text \
    )

if [ -z $EXISTINGINSTANCE ]
then
    echo "instance $DBINSTANCEIDENTIFIER does not exist!"
else
    echo "instance $DBINSTANCEIDENTIFIER exists!"
fi

References

Related Topic