Reputation: 51
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?
Upvotes: 0
Views: 921
Reputation: 51
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.
Upvotes: 1