Search code examples
typescriptamazon-web-servicesamazon-ec2amazon-rdsaws-cdk

Is there a way to restart RDS and EC2 instances on CDK?


I've recently started using CDK and I have little programming experience.

I've managed to set up an environment with a basic EC2 instance, a VPC with 2 subnets and an RDS instance. I've also created some CloudWatch Alarms for CPU usage of the RDS DB, for example:

      const CPUUsage = new cw.Alarm(this, 'CPUUsage', {
        metric: cpuUsage, //imported from another stack where I created the DB
        threshold: 4,
        evaluationPeriods: 2,
        alarmName: 'DB CPU Usage',
      });

I want to create an alarm where if the CPU of an instance (one alarm for EC2 and another for RDS) goes over an % (4 in this case) it would restart.

So far I haven't found anything that would restart the RDS instance, and for the EC2 instance I've only found the InitCommand class which doesn't really fit my needs, as I don't want to use shell commands in the code (if there's no other way it has to be done that way I guess).

Thank you in advance for any help given!


Solution

  • Yes, if you supply a metric that is a built-in per-instance metric, or any metric with an InstanceId dimension that contains a valid instance ID, you can use the EC2Action alarm action:

    alarm.addAlarmAction(
      new actions.Ec2Action(actions.Ec2InstanceAction.REBOOT),
    );
    

    Refer to https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html