How to check via aws cli if a specific rds instance exists?
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
- https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html
- https://stackoverflow.com/questions/45449174/how-do-i-use-query-parameter-in-aws-rds-describe-db-instances-command
- https://stackoverflow.com/questions/46051538/syntax-for-filters-for-aws-rds-describe-db-instances