- Make sure you have AWS CLI installed and configured.
- Ensure you have an IAM Role with the necessary permissions for SSM and EC2 start/stop operations.
- Create the Maintenance Window for Stopping the EC2 instance:
aws ssm create-maintenance-window \
--name "StopEC2Window" \
--schedule "cron(0 20 ? * MON-FRI *)" \
--duration 2 \
--cutoff 1 \
--allow-unassociated-targets
The above command will create a maintenance window to stop your EC2 instance at 8 pm UTC+1 from Monday to Friday.
- Create the Maintenance Window for Starting the EC2 instance:
aws ssm create-maintenance-window \
--name "StartEC2Window" \
--schedule "cron(0 7 ? * MON-FRI *)" \
--duration 2 \
--cutoff 1 \
--allow-unassociated-targets
This will create a maintenance window to start your EC2 instance at 7 am UTC+1 from Monday to Friday.
- Register the EC2 instance as a target:
Let's assume the instance ID you want to target is i-0abcd1234efgh5678
.
For stopping:
aws ssm register-target-with-maintenance-window \
--window-id "<StopEC2Window_ID_from_step_1>" \
--resource-type "INSTANCE" \
--targets "Key=InstanceIds,Values=i-0abcd1234efgh5678"
For starting:
aws ssm register-target-with-maintenance-window \
--window-id "<StartEC2Window_ID_from_step_2>" \
--resource-type "INSTANCE" \
--targets "Key=InstanceIds,Values=i-0abcd1234efgh5678"
- Register the Maintenance Window Tasks:
For stopping:
aws ssm register-task-with-maintenance-window \
--window-id "<StopEC2Window_ID_from_step_1>" \
--targets "Key=WindowTargetIds,Values=<Target_ID_from_previous_step>" \
--task-type "RUN_COMMAND" \
--task-arn "AWS-StopEC2Instance" \
--service-role-arn "<Your_IAM_Role_ARN>" \
--max-concurrency "1" \
--max-errors "1" \
--priority 1 \
--task-invocation-parameters '{"RunCommand":{"DocumentVersion":"1"}}'
For starting:
aws ssm register-task-with-maintenance-window \
--window-id "<StartEC2Window_ID_from_step_2>" \
--targets "Key=WindowTargetIds,Values=<Target_ID_from_previous_step>" \
--task-type "RUN_COMMAND" \
--task-arn "AWS-StartEC2Instance" \
--service-role-arn "<Your_IAM_Role_ARN>" \
--max-concurrency "1" \
--max-errors "1" \
--priority 1 \
--task-invocation-parameters '{"RunCommand":{"DocumentVersion":"1"}}'
Notes:
- Replace placeholders like
<Your_IAM_Role_ARN>
,<StopEC2Window_ID_from_step_1>
, and<StartEC2Window_ID_from_step_2>
with appropriate values. - This playbook uses AWS CLI. If you prefer the Management Console, you can follow similar steps in the AWS Systems Manager Dashboard.
Final Advice: Always double-check your configurations, especially when scheduling automated tasks. A typo or a misconfiguration could lead to unexpected behavior. And make sure you test these on non-critical environments first!
Happy automating! π€ππ