问题原文
原帖链接 · hey · CC BY-SA 4.0
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?
已采纳解答
原帖链接 · slm · CC BY-SA 4.0
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
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
