How do you create EC2 Spot InstanceA Python script to create an EC2 Spot instance using boto3. The script launches a spot instance based on an AMI, associates it with a specific security group in a given VPC, and assigns custom tags for easy identification. Prerequisites:- Install boto3:
pip install boto3 - Configure AWS CLI credentials:
aws configure
import boto3
import time
# AWS Configuration
region = "us-east-1" # Change as needed
ami_id = "ami-xxxxxxxxxxxxxxxxx" # Replace with your AMI ID
instance_type = "t3.micro" # Change instance type as needed
security_group_id = "sg-xxxxxxxxxxxxxx" # Replace with your security group ID
subnet_id = "subnet-xxxxxxxxxxxxxx" # Replace with your subnet ID within the VPC
key_name = "your-key-pair" # Replace with your SSH key pair name
tag_name = "MySpotInstance"
# Initialize boto3 clients
ec2_client = boto3.client("ec2", region_name=region)
# Request Spot Instance
spot_request = ec2_client.request_spot_instances(
InstanceCount=1,
LaunchSpecification={
"ImageId": ami_id,
"InstanceType": instance_type,
"KeyName": key_name,
"SecurityGroupIds": [security_group_id],
"SubnetId": subnet_id,
},
Type="one-time",
SpotPrice="0.005", # Adjust price based on instance type and AWS pricing
)
# Extract Spot Request ID
spot_request_id = spot_request["SpotInstanceRequests"][0]["SpotInstanceRequestId"]
print(f"Spot Instance Request ID: {spot_request_id}")
# Wait for Spot Request to be fulfilled
while True:
response = ec2_client.describe_spot_instance_requests(SpotInstanceRequestIds=[spot_request_id])
state = response["SpotInstanceRequests"][0]["State"]
print(f"Spot request state: {state}")
if state == "active":
instance_id = response["SpotInstanceRequests"][0]["InstanceId"]
print(f"Spot Instance Launched: {instance_id}")
break
elif state in ["cancelled", "failed", "closed"]:
print("Spot request failed or was cancelled.")
exit(1)
time.sleep(5) # Wait and check again
# Assign Tags to the Instance
ec2_client.create_tags(
Resources=[instance_id],
Tags=[
{"Key": "Name", "Value": tag_name},
{"Key": "Environment", "Value": "Test"},
{"Key": "Owner", "Value": "YourName"},
],
)
print(f"Instance {instance_id} tagged successfully!")
Explanation:- Request a Spot Instance: Uses
request_spot_instances() to request a spot instance with a specified AMI, instance type, security group, and subnet. - Monitor the request: The script polls AWS every 5 seconds until the instance is assigned.
- Assign tags: Tags are applied for easier searching and organization.
Search EC2 Instances with Tag InformationYou can search for EC2 instances by tags using boto3 in Python. The describe_instances method allows filtering instances based on specific tags. Example: Search EC2 Instances by TagThis script retrieves EC2 instances with a specific tag and prints their instance IDs and details. Python Scriptimport boto3
# AWS Configuration
region = "us-east-1" # Change as needed
tag_key = "Name" # Change to the tag key you are searching for
tag_value = "MySpotInstance" # Change to the tag value you are searching for
# Initialize EC2 client
ec2_client = boto3.client("ec2", region_name=region)
# Search EC2 instances based on a tag
response = ec2_client.describe_instances(
Filters=[
{"Name": f"tag:{tag_key}", "Values": [tag_value]},
{"Name": "instance-state-name", "Values": ["running", "pending"]}, # Optional: Filter by state
]
)
# Extract instance details
instances = []
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instances.append({
"Instance ID": instance["InstanceId"],
"State": instance["State"]["Name"],
"Type": instance["InstanceType"],
"Public IP": instance.get("PublicIpAddress", "N/A"),
"Private IP": instance["PrivateIpAddress"],
})
# Display results
if instances:
for instance in instances:
print(instance)
else:
print("No instances found with the given tag.")
How It Works:- Uses
describe_instances() with a filter on tag:Name = MySpotInstance. - Filters only running or pending instances (you can modify this).
- Extracts instance details (ID, state, type, IP addresses).
- Displays results in a structured format.
Example Output:{'Instance ID': 'i-0123456789abcdef0', 'State': 'running', 'Type': 't3.micro', 'Public IP': '34.123.45.67', 'Private IP': '10.0.1.12'}
Terminate EC2 InstancesYou can terminate an EC2 instance using boto3 in Python by calling the terminate_instances() method. Python Script to Terminate an EC2 Instanceimport boto3
# AWS Configuration
region = "us-east-1" # Change as needed
instance_id = "i-0123456789abcdef0" # Replace with your EC2 Instance ID
# Initialize EC2 client
ec2_client = boto3.client("ec2", region_name=region)
# Terminate the instance
response = ec2_client.terminate_instances(InstanceIds=[instance_id])
# Extract termination details
for instance in response["TerminatingInstances"]:
print(f"Instance {instance['InstanceId']} is {instance['CurrentState']['Name']}")
How It Works- Uses
terminate_instances() to terminate the specified EC2 instance. - Prints the instance ID and its current state.
Example OutputInstance i-0123456789abcdef0 is shutting-down
Terminate EC2 Instances by TagIf you want to terminate instances based on a tag, use this script: # Terminate EC2 instances by tag
tag_key = "Name"
tag_value = "MySpotInstance"
# Search for instances with the given tag
instances = ec2_client.describe_instances(
Filters=[{"Name": f"tag:{tag_key}", "Values": [tag_value]}]
)
instance_ids = [
instance["InstanceId"]
for reservation in instances["Reservations"]
for instance in reservation["Instances"]
]
if instance_ids:
response = ec2_client.terminate_instances(InstanceIds=instance_ids)
for instance in response["TerminatingInstances"]:
print(f"Instance {instance['InstanceId']} is {instance['CurrentState']['Name']}")
else:
print("No instances found with the given tag.")
Precautions- Cannot undo termination: Once an EC2 instance is terminated, you cannot recover it.
- Detach important volumes: If your instance has valuable EBS volumes, detach them first.
- Verify instance ID: Double-check that you're terminating the correct instance.
|