Automatic start and stop AWS EC2 instance using Systems Manager

In this blog we will learn how to schedule AWS EC2 instance to start and stop using AWS Systems Manager Maintenance Windows.

Prerequisite: Please make sure SSM agent is installed and running in the EC2 instance.

To schedule Amazon EC2 to start or stop using Systems Manager maintenance windows, register AWS-StartEC2Instance or AWS-StopEC2Instance Automation tasks to a maintenance window. The maintenance window targets the configured EC2 instances, and then stops or starts the instances using the provided Automation document steps on the chosen schedule.

To keep your instance stopped for a predetermined amount of time before it starts, set each task in a separate maintenance window. This prevents the instance from running during times when it’s not needed, which can reduce costs.

Create an IAM policy and role

To schedule maintenance windows to start or stop actions, you must use an AWS IAM role with ec2:StartInstances and ec2:StopInstances permissions.

  1. Open the IAM console, choose Policies from the navigation pane, and click on Create Policy.

2. For Service, choose EC2. For Actions, search for and select DescribeInstanceStatus, StartInstances, and StopInstances.
3. For Resources, It’s a security best practise to select Specific and then add the instance resource ARN. As we are configuring for learning purpose so I will select All resources. And then click on Next: Tags.

4. If you wish add Tags, and click on Next: Review.
5. Provide Name and Description and click on Create Policy.

6. Open the IAM console, choose Roles from the navigation pane, and click on Create role.

7. For Select type of trusted entity, choose AWS service.
8. For Use case, search for Systems Manager and choose Systems Manager. Then click on Next.

9. Search for newly created startstopEC2Policy, and click on Next after select that policy.

10. Provide Role Name (e.g startstopEC2role), and click on Create role.

Create maintenance window:-

  1. Go to Systems Manager and choose Maintenance windows from navigation pane.
  2. Click on Create Maintenance Window.
  3. Provide Name and Description. And make sure Allow unregistered targets is selected (it will required to run the maintenance window on managed instances that we haven’t registered as targets)
  4. Now set maintenance window Schedule. In our case I have selected Cron schedule builder and Daily. And from drop-down select day as per requirement.
  5. Give maintenance window duration and Stop initiating tasks. And other options are optional, as per your requirement you can provide.

Register the Automation Task

  1. Select the radio button for the target maintenance window, and then choose Actions, Register Automation Task.

2. For Maintenance window task details enter name and description (optional).

3. For Automation document, search for and choose either of the following documents depending on your use case (I will select AWS-StopEC2Instance
for this blog ):
AWS-StartEC2Instance
AWS-StopEC2Instance

Note: You can register only one Automation document at a time. To register both, you must repeat the full Register the Automation task process for
each document.
4. For Document Version, choose Default version at runtime.
5. The task priority is set to 1 by default. If you have multiple tasks registered to the same maintenance window, then you must give them different
priority levels. This establishes a run order.

6. For Targets, we will select Selecting unregistered targets as we have not registered target in maintenance window. You can select as per use case.
Then select your target from provided list.

7. For Input parameters, specify the following parameters:
InstanceId: Enter the pseudo parameter {{RESOURCE_ID}} to target more than one resource.
AutomationAssumeRole: Enter the complete role ARN for the IAM role that has the required ec2:StartInstances or ec2:StopInstances permissions.
For example, “arn:aws:iam::123456789101:role/StartStopEC2Role”.

8. For IAM Service role, select custom maintenance window service role. You can create this role by using below given policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:SendCommand",
                "ssm:CancelCommand",
                "ssm:ListCommands",
                "ssm:ListCommandInvocations",
                "ssm:GetCommandInvocation",
                "ssm:GetAutomationExecution",
                "ssm:StartAutomationExecution",
                "ssm:ListTagsForResource",
                "ssm:GetParameters"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "states:DescribeExecution",
                "states:StartExecution"
            ],
            "Resource": [
                "arn:aws:states:*:*:execution:*:*",
                "arn:aws:states:*:*:stateMachine:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "arn:aws:lambda:*:*:function:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "resource-groups:ListGroups",
                "resource-groups:ListGroupResources"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "tag:GetResources"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": [
                        "ssm.amazonaws.com"
                    ]
                }
            }
        }
    ]
}

9. Click on Register Automation Task.

Now check task execution history and instance state after Task Execution Time.

We can see that our task executed successfully and instance is also stopped.

In the same way we can configure another maintenance window to start EC2 instance.

3 thoughts on “Automatic start and stop AWS EC2 instance using Systems Manager”

Leave a Comment

Your email address will not be published. Required fields are marked *