Reputation: 344
I have an EC2 instance and I want to stop at 12:00 am at night and start it again at 7pm everyday.Is there any AWS service by which I could achieve this?
Any help would be appreciated
Upvotes: 3
Views: 327
Reputation: 79015
My recommendation would be to use AWS Instance Scheduler. There is a demo video at https://aws.amazon.com/premiumsupport/knowledge-center/stop-start-instance-scheduler/
Upvotes: 1
Reputation: 59906
You can do that using Two approach, Two lambda functions or you do that using one but for that, you may need to check trigger time and second is bash script using AWS CLI with cron job.
Using Lambda:
Important thing both Lambda should be based on scheduled event. Remember that the time is in UTC.
1.To Stop
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)
import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + str(instances)
Lamda role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
You can read more details about this approach here and here.
Using AWS cli and Cron Job
stop.sh
#!/bin/bash
ID="i-1234567890abcdef0"
echo "stop instance having ID=$ID
aws ec2 stop-instances --instance-ids $ID
start.sh
#!/bin/bash
echo "starting instance....."
aws ec2 start-instances --instance-ids i-1234567890abcdef0
cron job
To stop
0 0 * * * stop.sh
To start
0 7 * * * start.sh
Using the second approach you will be saving resources and cost of Lamda function.
Upvotes: 1
Reputation: 1780
There are a few different ways to do this.
Upvotes: 1
Reputation: 32376
There are enough examples on this, you can follow the official links of aws for doing this.
If you are looking for a simple solution I would suggest doing it using AWS lambda and cloudwatch https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
If you are looking for a robust solution, then as mentioned in earlier doc follow https://aws.amazon.com/premiumsupport/knowledge-center/stop-start-instance-scheduler/
Upvotes: 3