如果已存在具有特定名称的AWS RDS实例,我希望我的bash脚本检测到.
这是我试过的:
#!/usr/bin/env bash DBINSTANCEIDENTIFIER=greatdb EXISTINGINSTANCE=$(aws rds describe-db-instances \ --db-instance-identifier="$DBINSTANCEIDENTIFIER" \ --output text\ )
我希望有一个空列表,或者结果为零 – 但是我收到一条错误消息:
An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: DBInstance greatdb not found.
有没有人知道如何正确地找出实例是否存在,没有错误信息?
使用–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
因此,如果您知道DB实际存在,则只能使用此选项.
使用查询
要搜索可能存在或不存在的数据库,您必须使用–query选项:
$aws rds describe-db-instances \ --query 'DBInstances[*].[DBName,DBInstanceIdentifier]' --output text
可以在awscli帮助中访问DBINstances JSON结构:
$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" } ] } ... ...
使用过滤器
初始问题的另一个简单解决方案是使用–filters参数.查询将返回实例标识符(如果实例存在)或空字符串(如果它不存在):
#!/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
参考
> 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