2

I have the command to list all the RDS endpoints I have running in my aws account but I want to find RDS endpoint for RDS running in the same VPC as the ec2 instance I want to use it from.

I have multiple VPC's up with multiple RDS's so when I issue the command it gives me all the running RDS's. How can i filter this to just show me the one in the same VPC?

I run the command -

aws rds --region us-east-2 describe-db-instances --query "DBInstances[*].Endpoint.Address"

And I get -

"acme-networkstack.vbjrxfom0phf.us-east-2.rds.amazonaws.com", "acme-aws-beta-network.vbjrxfom0phf.us-east-2.rds.amazonaws.com", "acme-demo.vbjrxfom0phf.us-east-2.rds.amazonaws.com", "acme-dev.vbjrxfom0phf.us-east-2.rds.amazonaws.com"

I only want the one endpoint that is in the same VPC as the instance I am running the CLI command from.

Thanks!

Ernie

2 Answers2

2

Here's a little script that should do the trick, just replace the ec2 describe-instanceswith your rds cli command:

#!/bin/bash
mac=`curl -s http://169.254.169.254/latest/meta-data/mac`
vpcID=`curl -s http://169.254.169.254/latest/meta-data/network/interfaces/macs/$mac/vpc-id`
aws ec2 describe-instances --region eu-west-1 --filter "Name=vpc-id,Values=$vpcID"

You're first curling the instance meta-data to find it's VpcId, and then filtering the outputs of your cli command to limit to a certain vpc.

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-output.html

WarrenG
  • 1,750
  • 12
  • 20
  • I ran this : aws rds describe-db-instances --region us-east-2 --filter "Name=vpc-id,Values=vpc-11dee6c84a8573a26" An error occurred (InvalidParameterValue) when calling the DescribeDBInstances operation: Unrecognized filter name: vpc-id – Ernie Van Duyne Apr 18 '19 at 18:50
2

describe-db-instances has a limited set of filters which doesn't include the VPC. The solution I suggest uses a combination of the meta-data information from the host and jq to select only the endpoints that match the VPC.

First, You can get the VPC ID as suggested by WarrenG.

#!/bin/bash
mac=`curl -s http://169.254.169.254/latest/meta-data/mac`
VPC_ID=`curl -s http://169.254.169.254/latest/meta-data/network/interfaces/macs/$mac/vpc-id`

Then uses the AWS CLI in combination with jq to derive your desired output.

aws rds describe-db-instances | jq -r --arg VPC_ID "VPC_ID" '.DBInstances[] |select (.DBSubnetGroup.VpcId==$VPC_ID) | .Endpoint.Address'

I haven't run this from a script but it works from the command line. If it doesn't work in a script let me know.

References

https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html

Passing bash variable to jq select

kenlukas
  • 3,616
  • 9
  • 25
  • 36
  • 1
    Good suggestion, I wasn't aware of the limitations of RDS filters. This should be the accepted answer. – WarrenG Apr 22 '19 at 19:16