bash – 如果存在特定的rds实例,如何通过aws cli检查?

如果已存在具有特定名称的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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...