- Go to the IAM Console in AWS.
- Create a new IAM role.
- Choose the AWS Lambda use case.
- Attach the following policies to the role:
- AmazonEC2FullAccess (for EC2 instance management).
- CloudWatchLogsFullAccess (for logging Lambda function activities).
Step 2: Create Lambda Functions
- Log into AWS Lambda and create two Lambda functions:
- Start EC2 Instances Function: This function will start the EC2 instances.
- Stop EC2 Instances Function: This function will stop the EC2 instances.
Example Lambda Code to Start EC2 Instances:
python
Copy
import boto3
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Replace 'instance_id' with your EC2 instance ID or pass it as part of the event
instance_ids = ['i-xxxxxxxxxxxxxxxxx'] # List your EC2 instance IDs
ec2.start_instances(InstanceIds=instance_ids)
return 'EC2 instances started'
Example Lambda Code to Stop EC2 Instances:
python
Copy
import boto3
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Replace 'instance_id' with your EC2 instance ID or pass it as part of the event
instance_ids = ['i-xxxxxxxxxxxxxxxxx'] # List your EC2 instance IDs
ec2.stop_instances(InstanceIds=instance_ids)
return 'EC2 instances stopped'
- Deploy both functions and ensure the IAM role created earlier is assigned to the Lambda function.
Step 3: Create CloudWatch Events (EventBridge Rules)
You can use CloudWatch Events (EventBridge) to schedule when the Lambda functions should run.
Create Event Rule for Starting EC2 Instances:
- Open the Amazon EventBridge Console.
- Create a New Rule:
- Set Schedule Expression (e.g., cron(0 8 * * ? *) for every day at 8:00 AM UTC).
- For Target, select the Lambda function you created for starting EC2 instances.
- Configure permissions to allow EventBridge to invoke the Lambda function.
Create Event Rule for Stopping EC2 Instances:
- Similarly, create another EventBridge Rule for stopping the EC2 instances.
- Set the Schedule Expression (e.g., cron(0 18 * * ? *) for every day at 6:00 PM UTC).
- Select the Lambda function for stopping EC2 instances as the target.
Step 4: Test the Setup
- Manually invoke the Lambda functions from the AWS Lambda Console to test that they start and stop the instances as expected.
- Monitor the CloudWatch Logs to ensure there are no errors.
Step 5: Monitor and Adjust
- You can adjust the cron expressions in EventBridge rules to customize the schedule (e.g., different times on weekends or weekdays).
- Use CloudWatch Logs to track the activity of your Lambda functions, which will log any issues or execution results.
Example of Schedule Expressions:
- Start at 8 AM UTC every day: cron(0 8 * * ? *)
- Stop at 6 PM UTC every day: cron(0 18 * * ? *)
By following these steps, you'll have automatic EC2 instance management for starting and stopping instances based on your defined schedules.
Would you like more help with any specific part of this?