Q2
Scenario 2: Write a script that lists all EC2 instances, identifies any in a 'stopped' state, and starts them automatically.
💬Answer
import boto3
ec2 = boto3.resource("ec2", region_name="us-east-1")
# Find stopped instances
stopped_instances = ec2.instances.filter(
Filters=[{"Name": "instance-state-name", "Values": ["stopped"]}]
)
instance_ids = [instance.id for instance in stopped_instances]
if instance_ids:
print(f"Found stopped instances: {instance_ids}. Starting them now...")
# Start the instances
ec2.instances.filter(InstanceIds=instance_ids).start()
else:
print("No stopped instances found.")
Related Python Questions
View All PythonQuestions →
Created by
Apurv Gujjar
DevOps & Cloud Engineer
Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio