|
| 1 | +import { Stack, StackProps } from 'aws-cdk-lib'; |
| 2 | +import * as ssm from 'aws-cdk-lib/aws-ssm'; |
| 3 | +import * as iam from 'aws-cdk-lib/aws-iam'; |
| 4 | +import { Construct } from 'constructs'; |
| 5 | + |
| 6 | +export class PatchManagerStack extends Stack { |
| 7 | + constructor(scope: Construct, id: string, props: Props) { |
| 8 | + super(scope, id, props); |
| 9 | + |
| 10 | + // IAM role used by the maintenance window |
| 11 | + const maintenanceRole = new iam.Role(this, 'MaintenanceWindowRole', { |
| 12 | + assumedBy: new iam.ServicePrincipal('ssm.amazonaws.com'), |
| 13 | + }); |
| 14 | + |
| 15 | + maintenanceRole.addToPolicy( |
| 16 | + new iam.PolicyStatement({ |
| 17 | + actions: [ |
| 18 | + 'ssm:SendCommand', |
| 19 | + 'ssm:ListCommands', |
| 20 | + 'ssm:ListCommandInvocations', |
| 21 | + ], |
| 22 | + resources: ['*'], |
| 23 | + }), |
| 24 | + ); |
| 25 | + |
| 26 | + // Maintenance Window |
| 27 | + const maintenanceWindow = new ssm.CfnMaintenanceWindow( |
| 28 | + this, |
| 29 | + 'PatchMaintenanceWindow', |
| 30 | + { |
| 31 | + name: 'patch-maintenance-window', |
| 32 | + description: 'Weekly patching using AWS default patch baseline', |
| 33 | + schedule: 'cron(0 7 ? * WED *)', // Wednesdays 07:00 UTC |
| 34 | + duration: 3, |
| 35 | + cutoff: 1, |
| 36 | + allowUnassociatedTargets: false, |
| 37 | + }, |
| 38 | + ); |
| 39 | + |
| 40 | + // Target EC2 instances by Name tag |
| 41 | + const target = new ssm.CfnMaintenanceWindowTarget( |
| 42 | + this, |
| 43 | + 'PatchTarget', |
| 44 | + { |
| 45 | + windowId: maintenanceWindow.ref, |
| 46 | + resourceType: 'INSTANCE', |
| 47 | + targets: [ |
| 48 | + { |
| 49 | + key: 'InstanceIds', |
| 50 | + values: [...props.instanceIds], |
| 51 | + }, |
| 52 | + ], |
| 53 | + }, |
| 54 | + ); |
| 55 | + |
| 56 | + // Patch task (Install) |
| 57 | + new ssm.CfnMaintenanceWindowTask(this, 'PatchInstallTask', { |
| 58 | + windowId: maintenanceWindow.ref, |
| 59 | + taskArn: 'AWS-RunPatchBaseline', |
| 60 | + taskType: 'RUN_COMMAND', |
| 61 | + priority: 1, |
| 62 | + maxConcurrency: '2', |
| 63 | + maxErrors: '1', |
| 64 | + serviceRoleArn: maintenanceRole.roleArn, |
| 65 | + targets: [ |
| 66 | + { |
| 67 | + key: 'WindowTargetIds', |
| 68 | + values: [target.ref], |
| 69 | + }, |
| 70 | + ], |
| 71 | + taskInvocationParameters: { |
| 72 | + maintenanceWindowRunCommandParameters: { |
| 73 | + parameters: { |
| 74 | + Operation: ['Install'], |
| 75 | + }, |
| 76 | + }, |
| 77 | + }, |
| 78 | + }); |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +export interface Props extends StackProps { |
| 83 | + /** |
| 84 | + * Instance IDs to target for patching. |
| 85 | + */ |
| 86 | + instanceIds: string[]; |
| 87 | +} |
0 commit comments