rds-database-running-scheduler 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,22 +12,29 @@ This AWS CDK construct controls the start and stop of RDS DB instances and Auror
12
12
  ## Features
13
13
 
14
14
  - **Tag-based targeting**: Start and stop RDS DB instances and Aurora clusters that match a given tag key and values.
15
- - **Account-wide discovery**: Finds tagged RDS resources across all regions in the deployment account.
15
+ - **Multi-region discovery**: Searches every region enabled for the account, one region at a time, for tagged RDS resources. Set `targetRegions` to search only the regions you list.
16
16
  - **Cluster-priority deduplication**: When tag discovery returns both an Aurora cluster and its member DB instances, only the cluster is processed to avoid conflicting start/stop operations.
17
- - **Region-aware RDS control**: Creates per-region RDS clients from each resource ARN so cross-region resources are handled correctly.
17
+ - **Cross-region control**: Each resource is started and stopped in the region it lives in, even when that is not the stack's region.
18
18
  - **EventBridge Scheduler**: Cron-based start and stop schedules with configurable timezone, time, and weekdays.
19
19
  - **Lambda with Durable Execution**: A single durable run discovers resources by tag, starts or stops them, and waits until they reach the desired state or the per-resource wait limit.
20
20
  - **Configurable wait**: Set `resourceWait.intervalSeconds` and `resourceWait.maxSeconds` to control how often each resource is checked and how long the function waits before timing out. Defaults are 60 seconds and 1800 seconds.
21
21
  - **Optional Slack notifications**: Set `notification.slack.enable` to `SlackNotificationEnable.ENABLED` and provide `secretName` to post schedule progress and per-resource results to Slack via Secrets Manager. Leave `enable` unset (default `SlackNotificationEnable.DISABLED`), set it to `DISABLED`, or omit `notification.slack` to skip secret lookup, Slack API calls, and related IAM grants. When Slack is enabled, a timeout posts a message unless `notification.slack.notifyOnWaitTimeout` is `WaitTimeoutNotification.DISABLED`.
22
+ - **Opt-in failure detection**: Set `failureDetection.enabled` to `true` to create CloudWatch alarms for the Lambda `Errors` and `Throttles` metrics and for the handler's failure logs (wait timeout, unexpected status, failed execution). Pass an existing SNS topic as `failureDetection.alarmTopic` to be notified. Nothing is created by default, and the construct never creates an SNS topic.
22
23
  - **Supported resources**: RDS DB instances and RDS Aurora clusters.
23
24
 
24
25
  ## How it works
25
26
 
26
- EventBridge Scheduler runs a start cron and a stop cron. Each one invokes a durable Lambda function.
27
+ EventBridge Scheduler runs a start cron and a stop cron. Each one invokes a durable Lambda function. A failed invocation is retried at most twice, and only while the original event is less than 2 hours old. That window matches the durable execution timeout and is not configurable via props today. On the default schedule it ends before the opposite cron, so a failed stop is not run again after the next start.
27
28
 
28
- The function searches the deployment account for RDS DB instances and Aurora clusters that match `targetResource`. When both a cluster and its member instances match, only the cluster is controlled. Each remaining resource is started or stopped in the region taken from its ARN.
29
+ The function lists the regions enabled for the account and searches each one with the Resource Groups Tagging API for RDS DB instances and Aurora clusters that match `targetResource`. The Tagging API returns only the resources of the region it is called in, so each region is searched separately. When `targetRegions` is set, only those regions are searched. When both a cluster and its member instances match, only the cluster is controlled. Each remaining resource is started or stopped in the region taken from its ARN.
29
30
 
30
- The function then checks that resource every `resourceWait.intervalSeconds` until it is available or stopped, or until `resourceWait.maxSeconds` elapses. When Slack is enabled, it posts progress and, by default, a message when the wait limit is exceeded.
31
+ The function then checks that resource every `resourceWait.intervalSeconds` until it is available or stopped, or until `resourceWait.maxSeconds` elapses. A stop also waits through `storage-optimization`. A start that sees `storage-optimization` waits until the status is `stopped`, then starts the database. `configuring-iam-database-auth` and `configuring-log-exports` are waited on the same way. When Slack is enabled, it posts progress and, by default, a message when the wait limit is exceeded.
32
+
33
+ Some cases change nothing. When no resource matches, the run ends without posting to Slack. A resource that is already in the target state (available for a start, stopped for a stop) gets no start or stop call, but Slack still receives its result message. A cluster that no longer exists is skipped without a failure and without a result message. Both schedules can also be created in the disabled state with `enableScheduling`.
34
+
35
+ A resource that does not reach its target state within the wait limit, or reports a status that cannot be handled (for example `incompatible-restore`), fails the run. The other resources are still processed first, then the whole execution is marked as failed. The failure is also written to the log, which is what the opt-in failure detection alarms watch.
36
+
37
+ The Lambda log group keeps logs for three months. It is deleted only when its creation fails, and it is retained when the stack is deleted or the resource is replaced, so failures stay investigable.
31
38
 
32
39
  ## Installation
33
40
 
@@ -51,7 +58,39 @@ pnpm add rds-database-running-scheduler
51
58
 
52
59
  ## Usage
53
60
 
54
- Use the **Construct** `RDSDatabaseRunningScheduler` when adding the scheduler into an existing Stack or any CDK scope.
61
+ ### Minimal deployable app
62
+
63
+ Use the **Stack** `RDSDatabaseRunningScheduleStack` when you want a dedicated stack you can deploy as-is. Put this in your CDK app entry (for example `bin/app.ts`).
64
+
65
+ ```typescript
66
+ import { App } from 'aws-cdk-lib';
67
+ import { RDSDatabaseRunningScheduleStack } from 'rds-database-running-scheduler';
68
+
69
+ const app = new App();
70
+
71
+ new RDSDatabaseRunningScheduleStack(app, 'RDSDatabaseRunningScheduleStack', {
72
+ env: {
73
+ account: process.env.CDK_DEFAULT_ACCOUNT,
74
+ region: process.env.CDK_DEFAULT_REGION,
75
+ },
76
+ targetResource: { tagKey: 'WorkHoursRunning', tagValues: ['YES'] },
77
+ });
78
+
79
+ app.synth();
80
+ ```
81
+
82
+ This uses the default schedules: start at 07:50 UTC and stop at 19:05 UTC, Monday–Friday. Slack notifications and failure detection are off. Every region enabled for the account is searched.
83
+
84
+ Deploy checklist:
85
+
86
+ 1. Install this package and its peers (`aws-cdk-lib`, `constructs`, `lambda-failure-detector`) in your CDK app.
87
+ 2. Tag the RDS DB instances or Aurora clusters you want to control with the same `tagKey` and one of the `tagValues`.
88
+ 3. Only when you enable Slack, create the Secrets Manager secret first (see [Slack secret](#slack-secret)).
89
+ 4. From the CDK app: `npx cdk deploy RDSDatabaseRunningScheduleStack`
90
+
91
+ ### Construct
92
+
93
+ Use the **Construct** `RDSDatabaseRunningScheduler` when adding the scheduler into an existing Stack or any CDK scope. It accepts the same scheduler props as the Stack.
55
94
 
56
95
  ```typescript
57
96
  import { RDSDatabaseRunningScheduler } from 'rds-database-running-scheduler';
@@ -61,32 +100,36 @@ new RDSDatabaseRunningScheduler(scope, 'RDSDatabaseRunningScheduler', {
61
100
  });
62
101
  ```
63
102
 
64
- This uses the default schedules: start at 07:50 UTC and stop at 19:05 UTC, Monday–Friday. Slack notifications are off.
103
+ To search only some regions, list them in `targetRegions`:
65
104
 
66
- With Slack notifications and a custom schedule:
105
+ ```typescript
106
+ new RDSDatabaseRunningScheduler(scope, 'RDSDatabaseRunningScheduler', {
107
+ targetResource: { tagKey: 'WorkHoursRunning', tagValues: ['YES'] },
108
+ targetRegions: ['ap-northeast-1', 'us-east-1'],
109
+ });
110
+ ```
111
+
112
+ To be alerted when a run fails, enable failure detection and pass an SNS topic you already own:
67
113
 
68
114
  ```typescript
69
- import { TimeZone } from 'aws-cdk-lib';
70
- import { RDSDatabaseRunningScheduler, SchedulingEnable, SlackNotificationEnable } from 'rds-database-running-scheduler';
115
+ import { Topic } from 'aws-cdk-lib/aws-sns';
71
116
 
72
117
  new RDSDatabaseRunningScheduler(scope, 'RDSDatabaseRunningScheduler', {
73
118
  targetResource: { tagKey: 'WorkHoursRunning', tagValues: ['YES'] },
74
- notification: { slack: { enable: SlackNotificationEnable.ENABLED, secretName: 'example/slack/webhook' } },
75
- enableScheduling: SchedulingEnable.ENABLED,
76
- startSchedule: { timezone: TimeZone.ASIA_TOKYO, minute: '50', hour: '7', week: 'MON-FRI' },
77
- stopSchedule: { timezone: TimeZone.ASIA_TOKYO, minute: '5', hour: '19', week: 'MON-FRI' },
119
+ failureDetection: {
120
+ enabled: true,
121
+ alarmTopic: Topic.fromTopicArn(scope, 'AlarmTopic', 'arn:aws:sns:ap-northeast-1:123456789012:alarm-topic'),
122
+ },
78
123
  });
79
124
  ```
80
125
 
81
- Use the **Stack** `RDSDatabaseRunningScheduleStack` when you want a dedicated Stack that only contains the scheduler. Both accept the same scheduler props.
126
+ With Slack notifications and a custom schedule:
82
127
 
83
128
  ```typescript
84
- import { App, TimeZone } from 'aws-cdk-lib';
85
- import { RDSDatabaseRunningScheduleStack, SchedulingEnable, SlackNotificationEnable } from 'rds-database-running-scheduler';
86
-
87
- const app = new App();
129
+ import { TimeZone } from 'aws-cdk-lib';
130
+ import { RDSDatabaseRunningScheduler, SchedulingEnable, SlackNotificationEnable } from 'rds-database-running-scheduler';
88
131
 
89
- new RDSDatabaseRunningScheduleStack(app, 'RDSDatabaseRunningScheduleStack', {
132
+ new RDSDatabaseRunningScheduler(scope, 'RDSDatabaseRunningScheduler', {
90
133
  targetResource: { tagKey: 'WorkHoursRunning', tagValues: ['YES'] },
91
134
  notification: { slack: { enable: SlackNotificationEnable.ENABLED, secretName: 'example/slack/webhook' } },
92
135
  enableScheduling: SchedulingEnable.ENABLED,
@@ -95,11 +138,13 @@ new RDSDatabaseRunningScheduleStack(app, 'RDSDatabaseRunningScheduleStack', {
95
138
  });
96
139
  ```
97
140
 
98
- Tag your RDS instances or Aurora clusters with the same `tagKey` and one of the `tagValues` so they are included in the schedule.
141
+ The Stack takes the same props, so the same options work with `RDSDatabaseRunningScheduleStack`.
99
142
 
100
143
  For Aurora, tagging the cluster is sufficient. If member DB instances inherit the same tag, the Lambda automatically excludes them when the parent cluster is also targeted, so cluster-level start/stop is applied once without conflicting instance-level operations.
101
144
 
102
- When Slack is enabled, the secret in AWS Secrets Manager must contain JSON with `token` and `channel` fields:
145
+ ### Slack secret
146
+
147
+ Slack is optional. Only when `notification.slack.enable` is `SlackNotificationEnable.ENABLED` do you need to create the secret in AWS Secrets Manager **before deploying**. Without it, no secret is read and no secret-related IAM is granted. When enabled, the construct grants the Lambda read access to that secret and attaches the AWS Parameters and Secrets Lambda Extension layer, so you do not add either yourself. The secret must contain JSON with `token` and `channel` fields:
103
148
 
104
149
  ```json
105
150
  {
@@ -113,11 +158,13 @@ When Slack is enabled, the secret in AWS Secrets Manager must contain JSON with
113
158
  | Option | Type | Required | Description |
114
159
  |--------|------|----------|-------------|
115
160
  | `targetResource` | `TargetResource` | Yes | Tag key and values used to select RDS resources. |
161
+ | `targetRegions` | `string[]` | No | Regions to search for tagged RDS resources. Each must be a region enabled for the account. Must not be empty, blank, or contain duplicates. Default: every region enabled for the account. |
116
162
  | `notification` | `Notification` | No | Notification channels. Set `notification.slack.enable` to `SlackNotificationEnable.ENABLED` to send Slack messages. |
117
163
  | `resourceWait` | `ResourceWait` | No | Per-resource status-check interval and maximum wait. Default: 60-second interval, 1800-second maximum. |
118
164
  | `enableScheduling` | `SchedulingEnable` | No | Whether start and stop schedules are enabled. `ENABLED` or `DISABLED`. Default: `ENABLED`. |
119
165
  | `startSchedule` | `Schedule` | No | Start schedule. Default: 07:50 UTC, MON–FRI. |
120
166
  | `stopSchedule` | `Schedule` | No | Stop schedule. Default: 19:05 UTC, MON–FRI. |
167
+ | `failureDetection` | `LambdaFailureDetection` | No | Opt-in CloudWatch failure detection from [lambda-failure-detector](https://www.npmjs.com/package/lambda-failure-detector). Alarms are created only when `enabled` is `true`. `alarmTopic` is an optional existing SNS topic for every alarm. Default: no failure detection resources. |
121
168
 
122
169
  ### Schedule
123
170
 
@@ -165,8 +212,38 @@ See [API.md](./API.md).
165
212
  - **Node.js**: >= 20.0.0
166
213
  - **AWS CDK**: ^2.232.0
167
214
  - **constructs**: ^10.5.1
168
- - **AWS**: Account and region with permissions to create EventBridge Scheduler, Lambda, IAM, and CloudWatch Logs; RDS describe/start/stop permissions for targeted resources. Start/stop IAM is scoped to DB instance and cluster ARNs in the account and to `aws:ResourceTag` matching `targetResource`. Resource Groups Tagging API access is required for resource discovery. Secrets Manager access is required only when Slack notifications are enabled.
215
+ - **lambda-failure-detector**: ^0.2.1 (peer dependency, used only when `failureDetection.enabled` is `true`)
216
+ - **AWS**: Account and region with permissions to create EventBridge Scheduler, Lambda, IAM, and CloudWatch Logs; RDS describe/start/stop permissions for targeted resources. Start/stop IAM is scoped to DB instance and cluster ARNs in the account and to `aws:ResourceTag` matching `targetResource`. Resource Groups Tagging API access (`tag:GetResources`) and `ec2:DescribeRegions` are required for resource discovery. Secrets Manager access is required only when Slack notifications are enabled.
217
+
218
+ ## Notes
219
+
220
+ - **Least privilege**: Discovery and status checks (`tag:GetResources`, `ec2:DescribeRegions`, `rds:DescribeDBInstances`, `rds:DescribeDBClusters`) do not support resource-level permissions, so they use `*`. Start and stop are limited to DB instance and cluster ARNs in your account and to resources whose `aws:ResourceTag/<tagKey>` matches `targetResource`. The region part of those ARNs is `*` because tagged resources may live outside the stack region.
221
+ - **Safe to run again**: A start on an available resource and a stop on a stopped resource make no RDS call, so a retried or repeated run does not repeat a finished operation.
222
+ - **Retries**: Failed invocations are retried at most twice within 2 hours, which is not configurable via props today. A run that fails because a resource timed out or reported an unexpected status is a failed invocation too.
223
+
224
+ ## Troubleshooting
225
+
226
+ Start with the Lambda log group (`/aws/lambda/<function name>`). It keeps logs for three months and is retained when the stack is deleted.
227
+
228
+ When nothing seems to happen, check these in order:
229
+
230
+ 1. The schedules were not created with `enableScheduling: SchedulingEnable.DISABLED`.
231
+ 2. The resources carry the exact `tagKey` and one of the `tagValues`.
232
+ 3. The resources are in a searched region: every enabled region by default, or only `targetRegions` when it is set.
233
+ 4. The resource is not a cluster that no longer exists, which is skipped silently.
234
+
235
+ When Slack messages are missing, confirm the secret exists, contains `token` and `channel`, and that `notification.slack.enable` is `ENABLED`. A secret that cannot be read fails the run.
236
+
237
+ When `failureDetection.enabled` is `true`, these alarms are created. Each one counts ERROR logs that start with the marker of the same name, in the `RDSDatabaseRunningScheduler` metric namespace:
238
+
239
+ | Alarm / marker | Meaning |
240
+ |----------------|---------|
241
+ | `ResourceWaitTimedOut` | A resource did not reach its target state within `resourceWait.maxSeconds`. |
242
+ | `ResourceStatusUnexpected` | A resource reported a status that cannot be handled, for example `incompatible-restore`. |
243
+ | `ScheduleExecutionFailed` | The whole execution failed for any reason, including the two above. It also fires for failures before any resource is processed, such as an invalid `targetRegions`. |
244
+
245
+ The Lambda `Errors` and `Throttles` alarms cover failures of the invocation itself. A durable execution that fails inside the handler does not always raise `Errors`, so rely on `ScheduleExecutionFailed` for those.
169
246
 
170
247
  ## License
171
248
 
172
- This project is licensed under the Apache-2.0 License.
249
+ This project is licensed under the (Apache-2.0) License.