Skip to content

Commit 9afb6bf

Browse files
committed
Fix PostgreSQL Lambda integration issues and improve setup process
- Fix security group rule direction (allowDefaultPortFrom instead of allowDefaultPortTo) - Improve Lambda to PostgreSQL connection with increased timeout and better logging - Replace custom CloudFormation response handling with cfn-response library - Update PostgreSQL setup function to use standard CloudFormation response pattern - Add proper error handling in setup function
1 parent af5ac03 commit 9afb6bf

File tree

4 files changed

+26
-65
lines changed

4 files changed

+26
-65
lines changed

typescript/postgres-lambda/lambda/lambda-to-postgres/index.js

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,18 @@ const secretsManager = new SecretsManager();
88
*/
99
exports.handler = async (event) => {
1010
console.log('Event received:', JSON.stringify(event));
11-
11+
1212
try {
1313
// Get database credentials from Secrets Manager
1414
const secretArn = process.env.DB_SECRET_ARN;
1515
const dbName = process.env.DB_NAME;
16-
16+
1717
console.log(`Retrieving secret from ${secretArn}`);
1818
const secretResponse = await secretsManager.getSecretValue({ SecretId: secretArn });
1919
const secret = JSON.parse(secretResponse.SecretString);
20-
20+
const logSecret = {...secret, password: '*********'};
21+
console.log(logSecret);
22+
2123
// Create PostgreSQL client
2224
const client = new Client({
2325
host: secret.host,
@@ -28,13 +30,13 @@ exports.handler = async (event) => {
2830
ssl: {
2931
rejectUnauthorized: false, // For demo purposes only, consider proper SSL setup in production
3032
},
31-
connectionTimeoutMillis: 5000,
33+
connectionTimeoutMillis: 10000,
3234
});
33-
35+
3436
// Connect to the database
3537
console.log('Connecting to PostgreSQL database...');
3638
await client.connect();
37-
39+
3840
// Check if our demo table exists, if not create it
3941
console.log('Creating demo table if it does not exist...');
4042
await client.query(`
@@ -44,19 +46,19 @@ exports.handler = async (event) => {
4446
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
4547
)
4648
`);
47-
49+
4850
// Insert a record
4951
const message = event.message || 'Hello from Lambda!';
5052
console.log(`Inserting message: ${message}`);
5153
await client.query('INSERT INTO demo_table (message) VALUES ($1)', [message]);
52-
54+
5355
// Query the records
5456
console.log('Querying records...');
5557
const result = await client.query('SELECT * FROM demo_table ORDER BY created_at DESC LIMIT 10');
56-
58+
5759
// Close the connection
5860
await client.end();
59-
61+
6062
// Return the results
6163
return {
6264
statusCode: 200,
Lines changed: 10 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
const { Client } = require('pg');
22
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');
3-
const https = require('https');
4-
const url = require('url');
3+
const response = require('cfn-response');
54

65
const secretsManager = new SecretsManagerClient();
76

8-
exports.handler = async (event) => {
7+
exports.handler = async (event, context) => {
98
console.log('Event:', JSON.stringify(event, null, 2));
109

1110
if (event.RequestType === 'Delete') {
12-
return sendResponse(event, 'SUCCESS', 'Delete operation completed');
11+
return response.send(event, context, response.SUCCESS, {}, 'postgres-setup-delete');
1312
}
1413

1514
try {
@@ -68,56 +67,15 @@ exports.handler = async (event) => {
6867
await client.query(setupSQL);
6968
await client.end();
7069

71-
return sendResponse(event, 'SUCCESS', 'PostgreSQL setup completed successfully');
70+
// Send success response
71+
return response.send(event, context, response.SUCCESS, {
72+
Message: 'PostgreSQL setup completed successfully'
73+
}, 'postgres-setup-' + Date.now());
7274

7375
} catch (error) {
7476
console.error('Error:', error);
75-
return sendResponse(event, 'FAILED', error.message);
77+
return response.send(event, context, response.FAILED, {
78+
Error: error.message
79+
});
7680
}
7781
};
78-
79-
function sendResponse(event, status, reason) {
80-
return new Promise((resolve, reject) => {
81-
const responseBody = JSON.stringify({
82-
Status: status,
83-
Reason: reason,
84-
PhysicalResourceId: 'postgres-setup-' + Date.now(),
85-
StackId: event.StackId,
86-
RequestId: event.RequestId,
87-
LogicalResourceId: event.LogicalResourceId,
88-
Data: {}
89-
});
90-
91-
console.log('Response:', responseBody);
92-
93-
// Parse the URL
94-
const parsedUrl = url.parse(event.ResponseURL);
95-
96-
// Prepare the request options
97-
const options = {
98-
hostname: parsedUrl.hostname,
99-
port: 443,
100-
path: parsedUrl.path,
101-
method: 'PUT',
102-
headers: {
103-
'Content-Type': '',
104-
'Content-Length': responseBody.length
105-
}
106-
};
107-
108-
// Send the response
109-
const request = https.request(options, (response) => {
110-
console.log(`Status code: ${response.statusCode}`);
111-
resolve({ status, reason });
112-
});
113-
114-
request.on('error', (error) => {
115-
console.error('Error sending response:', error);
116-
reject(error);
117-
});
118-
119-
// Write the response body and end the request
120-
request.write(responseBody);
121-
request.end();
122-
});
123-
}

typescript/postgres-lambda/lambda/postgres-setup/package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
"build": "mkdir -p node_modules && npm install --no-package-lock"
88
},
99
"dependencies": {
10-
"pg": "^8.11.0",
11-
"@aws-sdk/client-secrets-manager": "^3.350.0"
10+
"@aws-sdk/client-secrets-manager": "^3.350.0",
11+
"cfn-response": "^1.0.1",
12+
"pg": "^8.11.0"
1213
}
1314
}

typescript/postgres-lambda/lib/postgres-lambda-stack.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export class PostgresLambdaStack extends cdk.Stack {
5858
});
5959

6060
// Grant Lambda access to the DB
61-
dbCluster.connections.allowDefaultPortTo(lambdaToPostgres);
61+
dbCluster.connections.allowDefaultPortFrom(lambdaToPostgres);
6262

6363
// Grant the Lambda function permission to read the database secret
6464
dbCluster.secret?.grantRead(lambdaToPostgres);

0 commit comments

Comments
 (0)