Executing custom AWS CDK resource to configure database following the creation of an RDS instance

After setting up an RDS instance and an EKS cluster using AWS CDK and Typescript, I need to find a way to trigger a Lambda function to set up database users for microservices on EKS. The Lambda function should run after the RDS instance is created but before the microservices are installed.

To achieve this, I have created a Custom Resource backed by a Lambda function in Typescript. This Lambda function retrieves the secrets generated by CDK for the RDS instance and the database users, connects to the database, and creates the necessary users.

Although I have not been able to explicitly declare the dependency, as my Lambda function does not technically require one (other than using secret.grantRead(lambda)), simply running a retry loop until everything is up will not be effective due to the long creation times. Any code snippets or examples would be greatly appreciated, as most references so far have only discussed the general approach.

In relation to @jogold's response:

    const database = new rds.DatabaseInstance(this, 'db', {
      instanceIdentifier: conf.systemName,
      engine: rds.DatabaseInstanceEngine.POSTGRES,
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO),
      masterUsername: MASTER_USER,
      allocatedStorage: 20, maxAllocatedStorage: 100,
      multiAz: conf.isProduction,
      storageEncrypted: true,
      backupRetention: cdk.Duration.days(7),
      deletionProtection: false, 
      vpc, securityGroups: [ rdsSG ]
    });

CDK automatically generates a secret with credentials to access the database. I attempted to attach this secret directly to my Lambda:

    new cdk.CustomResource(this, 'preinstall', { 
      serviceToken: preinstallProvider.serviceToken,
      properties: { secret: database.secret }
    });

However, this resulted in the following error:

    Error: Resolution error: Resolution error: Trying to resolve() a Construct at /Resources/${Token[td000.preinstall.Default.LogicalID.221]}/Properties/dbSecret/node/_actualNode.

Additionally, it appears that the ISecret interface does not contain the ID/name of the secret, leaving me unsure of how to proceed in the Lambda function.

Answer №1

When using CDK, it will typically attempt to determine the dependencies for you and ensure they are created in the correct sequence. In cases where this automated process fails, such as in the example provided, you can explicitly specify that one resource depends on another. Here's an example:

const customResource = new cdk.CustomResource(this, 'preinstall', { 
  serviceToken: preinstallProvider.serviceToken,
  properties: { secret: database.secret }
});

customResource.node.addDependency(database);

For more information, refer to the documentation here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetch data from a JSON file using a URL

Having trouble accessing data from a JSON file via URL. Everything seems to be in order but nothing is working, and I'm at a loss for how to troubleshoot it. service export class JsonService { public getMenuData(): Observable<any> { ...

default folder location for core modules adjustment

While experimenting with module imports in TypeScript, I encountered an issue when trying to import a module using import { Component, OnInit } from '@angular/core';. The compiler was successfully finding the module in the node_modules folder. I ...

Combining Angular 2 and Sails.js for Ultimate Web Development

Looking to integrate Sails with Angular 2 and add TypeScript to my project. As a newcomer in this field, I'm unsure how to configure this. I have created a Sails app using the command: sails new myApp Could anyone guide me on how to incorporate thi ...

Struggling to make HttpClient Post work in Angular 5?

I'm facing an issue with my httpClient post request. The service is not throwing any errors, but it's also not successfully posting the data to the database. Below is the code snippet: dataService.ts import { Injectable } from '@angular/c ...

Do we need to import Vue in every component when using Nuxt with TypeScript?

I recently integrated TypeScript into Nuxt using the guidelines provided in the documentation: However, I have a specific question regarding component setup. Should I always include import vue from "vue" and export default Vue.extend ({}); in al ...

Displaying and concealing a subcomponent within a parent element for a set duration of time

I have a notification component that is displayed as a child component in the parent component after a button click. It automatically hides after a certain number of seconds. Here is the code I have developed: MyCode Parent component: <button (click)= ...

When using the react-query library, the useQuery hook may not always return a defined value, leading

Experimenting with reactQuery in a demo app showcased in this repository. The app interacts with a mock API found here. Encountering an issue using the useQuery hook to call the following function in the product API file: export const getAllProducts = asy ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Keep an eye on the output of Firebase database in Angular 2

Just starting out in angular, so please be patient :) Using Angular 2 (version 1.0.4), Angular CLI, and NodeJs 7.9. I've been trying to create a centralized service that checks if a user is logged in, retrieves their data, and sends it back for the ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

How to Implement a ForwardedRef in Material-UI using Typescript

Currently, I have implemented a customized checkbox that is being forwarded as a component to a DataGrid. const CustomCheckbox = ({ checkboxRef, ...props }: { checkboxRef: React.ForwardedRef<unknown>; }) => ( <Checkbox {...props} ...

The declaration file for module 'vue-tabulator' was nowhere to be found

Trying to incorporate the vue-tabulator Vue component from https://github.com/angeliski/vue-tabulator into a basic Vue application written in TypeScript. main.ts: import Vue from 'vue' import VueTabulator from 'vue-tabulator' import A ...

What steps can I take to resolve the error message stating "Type X is not compatible with Type Y" in TypeScript?

I'm encountering an issue with the middleware in my express app. Here is the code: app.use(function(req, res, next) { let _end = res.end; res.end = function end(chunk, encoding) { ... return _end.call(res, chunk, encoding); }; next(); ...

Creating custom TypeScript validation types at compile time

Is it possible to create custom type definitions in TypeScript that are only checked during compile time? I want users to define a value for a variable (that won't change at runtime) and validate if it meets certain criteria. For example, requiring a ...

Tips for dynamically adding a new row to a table within a React application with TypeScript on click

I recently started learning React and TypeScript. I'm trying to figure out how to add a new row to a table when a user clicks a button (FontAwesomeIcon). I'm feeling a bit lost on where to begin with this. Here is the code snippet: import React ...

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

The Proper Way to Position _app.tsx in a Next.js Setup for Personalized App Configuration

I've been working on a Next.js project and I'm currently trying to implement custom app configuration following the guidelines in the Next.js documentation regarding _app.tsx. However, I'm encountering some confusion and issues regarding the ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

What is the best way to showcase a collection of inherited objects in Angular?

How can I efficiently display a list of various objects that inherit from the same abstract class in an Angular application? What is considered optimal practice for accomplishing this task? Consider the following basic model: abstract class Vehicle { ...