Skip to content

Commit f40ec8d

Browse files
committed
fix: wait for secret attachment before DB init
1 parent 2221311 commit f40ec8d

2 files changed

Lines changed: 15 additions & 11 deletions

File tree

demos/rds-init-example.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ export class RdsInitStackExample extends Stack {
7272
})
7373
// manage resources dependency
7474
initializer.customResource.node.addDependency(dbServer)
75+
const credsAttachment = creds.node.tryFindChild('Attachment')
76+
if (credsAttachment) {
77+
initializer.customResource.node.addDependency(credsAttachment)
78+
}
7579

7680
// allow the initializer function to connect to the RDS instance
7781
dbServer.connections.allowFrom(initializer.function, Port.tcp(3306)) // note: not required for LocalStack

demos/rds-init-fn-code/index.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,7 @@ exports.handler = async (e) => {
2727
let connection
2828
try {
2929
const { config } = e.params
30-
const { password, username, dbname, port } = await getSecretValue(config.credsSecretName)
31-
connection = await createConnectionWithRetry({
32-
host: hostname,
33-
user: username,
34-
database: dbname,
35-
port,
36-
password,
37-
multipleStatements: true
38-
})
30+
connection = await createConnectionWithRetry(config.credsSecretName)
3931

4032
const sqlScript = fs.readFileSync(path.join(__dirname, 'script.sql')).toString()
4133
const res = await query(connection, sqlScript)
@@ -70,7 +62,15 @@ function query (connection, sql) {
7062
async function createConnectionWithRetry (connectionConfig) {
7163
let lastError
7264
for (let attempt = 1; attempt <= DB_CONNECT_RETRY_MAX_ATTEMPTS; attempt += 1) {
73-
const connection = mysql.createConnection(connectionConfig)
65+
const { password, username, dbname, port } = await getSecretValue(connectionConfig)
66+
const connection = mysql.createConnection({
67+
host: hostname,
68+
user: username,
69+
database: dbname,
70+
port,
71+
password,
72+
multipleStatements: true
73+
})
7474
try {
7575
await connect(connection)
7676
return connection
@@ -82,7 +82,7 @@ async function createConnectionWithRetry (connectionConfig) {
8282
}
8383

8484
const retryInSeconds = DB_CONNECT_RETRY_DELAY_MS / 1000
85-
console.log(`Database connection attempt ${attempt}/${DB_CONNECT_RETRY_MAX_ATTEMPTS} failed with '${error.code || error.message}'. Retrying in ${retryInSeconds}s...`)
85+
console.log(`Database connection attempt ${attempt}/${DB_CONNECT_RETRY_MAX_ATTEMPTS} failed (port=${port}) with '${error.code || error.message}'. Retrying in ${retryInSeconds}s...`)
8686
await sleep(DB_CONNECT_RETRY_DELAY_MS)
8787
}
8888
}

0 commit comments

Comments
 (0)