How to schedule EC2 instances to change type

We can modify the EC2 instance type at any time according to the requirements.

This article explains the steps to schedule EC2 instances to change type using Lambda functions and Cloudwatch.

Step1: Login to AWS console.

Step2: Open IAM dashboard.

Step3: Choose Policies from left menu and Create a new IAM policy with the following json.

{
    "Version": "2012-10-17",
    "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
        ],
    "Resource": "arn:aws:logs:*:*:*"
    },
    {
        "Effect": "Allow",
            "Action": [
            "ec2:*"
        ],
    "Resource": "*"
    }
]
}

Step4: Choose Roles from left menu and Create a new role for Lambda and attach the policy that created earlier.

Step5: Open Lambda Dashboard.

Step6: Create the Lambda function to change the EC2 instance type and use the following Python code.

import boto3
client = boto3.client('ec2')

# Insert your Instance ID here  
my_instance = 'instance-id'

# Stop the instance
client.stop_instances(InstanceIds=[my_instance])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[my_instance])

# Change the instance type
client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value='type')

# Start the instance
client.start_instances(InstanceIds=[my_instance])

Where instance-id and type need to be replaced with id of the EC2 instance and proposed instance type respectively.

Please note to use the newly created IAM role as the execution role and Python3.8 as the run-time.

Step7: Deploy the Lambda function.

Step8: Open the Cloudwatch console.

Step9: In the left navigation pane, under Events, choose Rules.

Step10: Select Create rule.

Step11: Choose Schedule under Event Source

Step12: Enter the cron expression according to the requirement.

Cron Fields: Minutes Hours Day-of-month Month Day-of-week Year

Step13: Choose Add target under Targets.

Step14: Choose Lambda function and select the function that we have created for changing the EC2 instance type.

Step15: Choose Configure details.

Step16: Put the Name and Description for the rule.

Step17: Select the Enabled check box and Create rule.

That's all…