Struggling to transfer RDS database instance metrics to a different stack

Within my development environment, I have two stacks in place - one dedicated to creating an RDS DB and the other focused on managing cloudwatch alarms. My goal is to pass the dbInstance details seamlessly between these two stacks:

import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import { StackProps } from 'aws-cdk-lib';
import { IMetric } from 'aws-cdk-lib/aws-cloudwatch';


export class DatabaseStack extends cdk.Stack {
    public readonly dbName: rds.DatabaseInstance
    public readonly dbCPUUsage: IMetric
    public readonly dbInstance: any;
    constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

/* Created a VPC with a PUBLIC and an ISOLATED subnet groups.
RDS instance will be launched in an ISOLATED subnet because we'll be 
connecting to it from our EC2 instance, which is in the same VPC. */
        const vpc = new ec2.Vpc(this, 'my-cdk-vpc',{
            ...
        });
        const ec2InstanceSG = new ec2.SecurityGroup(this, 'ec2-instance-sg', {
            vpc,
        });

/* create security group for the EC2 instance with single inbound rule,
which allows SSH connections from anywhere. */
        ec2InstanceSG.addIngressRule(
            ec2.Peer.anyIpv4(),
            ec2.Port.tcp(22),
            'allow SSH connections from anywhere',
        );

// Created a t2.micro EC2 instance with Amazon Linux 2 AMI and placed it in a PUBLIC subnet.

        const ec2Instance = new ec2.Instance(this, 'ec2-instance', {
            ...
        });

/* Create RDS instance */
    const dbInstance = new rds.DatabaseInstance(this, 'db-instance',{
            ...

    });

// Allow connections to our RDS instance, on port 5432, from the security group of the EC2 instance
    dbInstance.connections.allowFrom(ec2Instance, ec2.Port.tcp(5432));
    
// Database hostname that we'll use to connect to our RDS instance
    new cdk.CfnOutput(this, 'dbEndpoint', {
        value:dbInstance.instanceEndpoint.hostname,
    });

// Name of the secret that stores the password of the postgres user
    new cdk.CfnOutput(this, 'secretName', {
        value: dbInstance.secret?.secretName!,
    });

    new cloudwatch.Alarm(this, 'HighCPU', {
        metric: dbInstance.metricCPUUtilization(),
        threshold: 100,
        evaluationPeriods: 2,
    })
    
    this.dbName = dbInstance;
    this.dbCPUUsage = dbInstance.metricCPUUtilization();
    }
    ;
}

export interface CloudwatchStackProps extends StackProps {
    dbNameExport: rds.IDatabaseInstance;
    dbCPUUsageExport: IMetric;
};

We then bridge this stack with:

import * as cdk from 'aws-cdk-lib';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import { IDatabaseInstance } from 'aws-cdk-lib/aws-rds';
import { Stack } from 'aws-cdk-lib';
import { CloudwatchStackProps } from '../lib/cdk-database-stack';

export class CloudwatchStack extends Stack {
  private readonly dbInstance: IDatabaseInstance
  constructor(scope: cdk.App, id: string, props: CloudwatchStackProps) {
      super(scope, id, props);
      const cpuUsage = props.dbCPUUsageExport

      new cloudwatch.Alarm(this.dbInstance, 'CPUUsage', {
        metric: cpuUsage(),
        threshold: 100,
        evaluationPeriods: 2,
       });

    }
  }

As I execute CDK Diff, an error surfaces stating "Cannot read properties of undefined (reading 'metric'))."

Below is the content of the bin file included:

#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { AmsAwsTestingGroundsStack } from '../lib/ams-aws-testing-grounds-stack';
import { CloudwatchStack } from '../lib/cdk-cloudwatch-stack';
import { DatabaseStack } from '../lib/cdk-database-stack';

const app = new cdk.App();

new AmsAwsTestingGroundsStack(app, 'AmsAwsTestingGroundsStack');

const databaseStack = new DatabaseStack(app, 'DatabaseStack');

const cloudwatchstack = new CloudwatchStack(app, 'CloudwatchStack', {
    dbNameExport: databaseStack.dbName,
    dbCPUUsageExport: databaseStack.dbCPUUsage,
});

Your assistance would be greatly appreciated, thank you!

EDIT - solution

new cloudwatch.Alarm(this, 'CPUUsage', { 
  metric: cpuUsage,
  threshold: 100,
  evaluationPeriods: 2,
});

Answer №1

Upon reviewing the Alarm constructor, I have identified two key issues:

new cloudwatch.Alarm(this, 'CPUUsage', { // <-- It is recommended to use `this` for `scope` in a stack
  metric: cpuUsage, // <-- The function call should be removed ()
  threshold: 100,
  evaluationPeriods: 2,
});

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

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

Attempting to adhere to the prescribed Cypress tutorial is resulting in various errors related to being "compiled under '--isolatedModules'"

I am new to using Cypress and I have been following the helpful tutorial on testing your first application. However, I have encountered some compiler issues in the third section. Following the instructions, I created a custom command but I am receiving th ...

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

Is there a way to access a file from an S3 bucket URL using Angular?

Currently, I have the URL but I'm not interested in putting in the effort to retrieve the file data or blob. This is my current approach: const url = 'https://s3-us-west-1.amazonaws.com/....'; const a: any = document.createElement('a& ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Having trouble reading the length property of undefined in Angular 7

Seeking to obtain a picture link of the object. The objects are stored in an array and the typescript method looks like this: getMealPicture(orderLineMeal: OrderLine): string { for (let meal of this.meals) { if (meal.id === orderLineMeal.mealId) ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

The revalidateTag and revalidatePath features in Next.js are currently not functioning as expected

I attempted to utilize the revalidateTag and revalidatePath functions with Next.js version 14.2.3. The objective was: there is a server action to fetch a list of items. also, there is a server action to add an item. upon successful addition of an item, I ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

A Step-by-Step Guide on Updating Your Angular 7 Project to Angular Version

I am facing a challenge with my Angular material project, which is currently outdated and needs to be updated to version 13. Running npm outdated revealed the following results: https://i.stack.imgur.com/ayjDu.png The Angular update guide suggests upgra ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

The Element type does no feature a Typescript property

Despite my attempts to include a declaration file and various other solutions, I'm still struggling with this issue: The goal is to define the visible property as a function on the HTML Element object. However, the linter keeps flagging visible with ...

How can I stop the SvelteKit production node server from filling up the logs with "Error: not found /path/here"?

After developing a website using sveltekit, I decided to build it for production as a nodejs server and deploy it on my linux server with Caddy as a reverse proxy. Unexpectedly, upon starting the server, I began receiving error messages in the log such as ...

Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role. Here is my current approach: <form [formGroup]="rolesForm"> <label formArrayName="roles" *ngFor=" ...

Asynchronous function in TypeScript is restricting the return type to only one promise type

Using node version 14.7.0, npm version 6.14.7, and typescript version 3.7.3. I have a function that interacts with a postgres database and retrieves either the first row it finds or all results based on a parameter. It looks something like this: async fet ...

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Embed the value of an array in HTML

Upon running console.log, the data output appears as follows: {TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3} To store this information, I am holding it in an array: userData : arrayResp ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...