Scheduling EC2 Instance Management on Ubuntu Using Python with Linux System
Prerequisites
Before you proceed, ensure you have:
pip install boto3
aws configure
#### Python script######
#!/usr/bin/python
import boto3
from botocore.exceptions import ClientError
import sys
import time
client = boto3.client('ec2', region_name='eu-central-1')
client2 = boto3.resource('ec2', region_name='eu-central-1')
def describe_instances(tag_name):
instance_ids = []
try:
response = client.describe_instances(
Filters=[
{
'Name': 'tag:Name',
'Values': [tag_name] # Filter by instance Name tag
}
]
)
instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
status = response['Reservations'][0]['Instances'][0]['State']['Name']
if status == "stopped":
instance_ids.append(instance_id)
return instance_ids, status
elif status == "running":
instance_ids.append(instance_id)
return instance_ids, status
except Exception as e:
print(e)
def start_instance(instance_id):
response = client.start_instances(
InstanceIds=[instance_id],
DryRun=False
)
print(response)
def stop_instance(instance_id):
response = client.stop_instances(
InstanceIds=[instance_id],
DryRun=False
)
print(response)
if name == "__main__":
instance_name = "my-web"
instences, state = describe_instances(instance_name)
print(instences)
print(state)
for instance in instences:
if state == "stopped":
start_instance(instance)
time.sleep(60)
elif state == "running":
stop_instance(instance)
time.sleep(60)
else:
print("No instance found")w
sys.exit(1)
0 8,20 * /usr/bin/python3 /path/to/your/ec2_scheduler.py
Conclusion
You have successfully set up a Python script on your Ubuntu system to manage EC2 instances and scheduled it using cron. This automation will help you efficiently manage your resources, potentially reducing costs and manual intervention. You can further customize the script and scheduling as per your requirements. Happy coding!
In the next post, we’ll explore how to use AWS Lambda and CloudWatch Events to automate EC2 start/stop actions without needing a local server. Stay tuned for a serverless approach to managing EC2 instances!