0
votes

I created a publicly accessible PostgreSQL RDS in AWS and have the following code to connect to it:

try {
  DriverManager.registerDriver(new org.postgresql.Driver());
  String url = "jdbc:postgresql://" + DATABASE_SERVER_NAME + ":" + DATABASE_PORT_NUMBER + "/" + DATABASE_NAME + "?user=" + DATABASE_USER + "&password=" + DATABASE_PASSWORD;
  try (Connection connection = DriverManager.getConnection(url)) {
    try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM \"" + PHANTOM_LOAD_STORE_DATABASE_TABLE_NAME + "\"")) {
      try (ResultSet resultSet = statement.executeQuery()) {
        while (resultSet.next()) {
          System.out.println(resultSet.getString("userid"));
        }
      }
    }
  }
} catch (SQLException e) {
  throw new RuntimeException(e);
}

When this is run locally it connects to the database server successfully.

When this is run in an AWS Lambda it fails to connect with the following error:

org.postgresql.util.PSQLException: The connection attempt failed.
...
Caused by: java.net.SocketTimeoutException: connect timed out

The lambda is not in a VPC and has the role policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess.

Can someone tell me what I'm doing wrong?

1
Which IP you enabled from the RDS Security group rules?.I think you need to configure Lambda to access RDS instanceDhanraj
Yes, you're right the security group rule was too restrictive. I've fixed this to be more lax. What do you mean "configure Lambda to access RDS instance"?Kim Barrett
I thought it was may be because of your RDS instance not getting access by lambda function..so for this you needed to do some additonal setting..anyway i hope your issue is solved by chaging RDS security group rules, by the way what did you changed to work?Dhanraj
See my answer below. It had automatically limited incoming requests to just those from my IP so I changed the incoming rule to allow requests from everywhere.Kim Barrett
Got it. Bingo..Dhanraj

1 Answers

1
votes

Despite creating the RDS database to be publicly accessible it had a security group rule that only allowed incoming requests from my IP (the one that created the database). Editing its security group's incoming rules to allow requests from anywhere has allowed the lambda to connect to the database.

The policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess seems unnecessary.

Thanks to this answer for helping me work it out.