Create Lambda function for Lightsail

Example of how to create a quick stop/start Lambda function for Lightsail in AWS

  1. Add function name

  2. Select runtime (in our case python)

  3. Create the function

  4. Add code to stop/start instance:

Code to STOP Lightsail Instance:

# TO STOP
import json
import boto3
def lambda_handler(event, context):
    client = boto3.client('lightsail', region_name='REGION-NAME')
    response = client.stop_instance(
    instanceName='INSTANCE-NAME'
)
    return {
        'statusCode': 200,
        'body': json.dumps('Lambda has stopped instance')
    }

Code to START Lightsail Instance:

# TO START
import json
import boto3
def lambda_handler(event, context):
    client = boto3.client('lightsail', region_name='REGION-NAME')
    response = client.start_instance(
    instanceName='INSTANCE-NAME'
)
    return {
        'statusCode': 200,
        'body': json.dumps('Lambda has started instance')
    }t

5. Go to Amazone EventBridge --> Events --> Rules --> Create Rule

6. Select Scheduled --> Next

7. Select CRON pattern --> Use 5 2 ? * 7 * for Every Saturday at 2:05 GMT (Example) --> Next

8. On the Right side: Select tragets(s) --> AWS Service --> Lambda function --> Select Lambda Function Name

9. Click Next --> Review --> Next --> Finished

Resources:

Time Conversion Romania

AWS Cron Expressions Documentation

Last updated