Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Created April 16, 2025 03:28
Show Gist options
  • Save xcsrz/884c9ce92a3fa13149ee3b6c6500a027 to your computer and use it in GitHub Desktop.
Save xcsrz/884c9ce92a3fa13149ee3b6c6500a027 to your computer and use it in GitHub Desktop.
Script to quickly launch EC2 instances in a preset VPC, type, etc
#!/bin/bash
# ======= Configuration =======
REGION="us-east-1" # Set your AWS region
INSTANCE_TYPE="t2.micro"
KEY_NAME="your-key-pair-name"
SECURITY_GROUP_ID="sg-xxxxxxxxxxxxxxx"
SUBNET_ID="subnet-xxxxxxxxxxxxxxxxx"
UBUNTU_OWNER="099720109477" # Canonical (Ubuntu's AWS account ID)
UBUNTU_NAME_FILTER="ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
# ==============================
# Input: instance suffix name
if [ -z "$1" ]; then
echo "Usage: $0 <instance-name-suffix>"
exit 1
fi
INSTANCE_NAME="temp-instance-$1"
# Get latest Ubuntu AMI ID
echo "Fetching latest Ubuntu AMI ID for $REGION..."
AMI_ID=$(aws ec2 describe-images \
--region "$REGION" \
--owners "$UBUNTU_OWNER" \
--filters "Name=name,Values=$UBUNTU_NAME_FILTER" "Name=state,Values=available" \
--query 'Images | sort_by(@, &CreationDate)[-1].ImageId' \
--output text)
if [ -z "$AMI_ID" ]; then
echo "Failed to find Ubuntu AMI."
exit 1
fi
# Launch the EC2 instance
echo "Launching EC2 instance named '$INSTANCE_NAME' with 50GB root volume..."
INSTANCE_ID=$(aws ec2 run-instances \
--region "$REGION" \
--image-id "$AMI_ID" \
--count 1 \
--instance-type "$INSTANCE_TYPE" \
--key-name "$KEY_NAME" \
--security-group-ids "$SECURITY_GROUP_ID" \
--subnet-id "$SUBNET_ID" \
--block-device-mappings "[{\"DeviceName\":\"/dev/sda1\",\"Ebs\":{\"VolumeSize\":50,\"VolumeType\":\"gp3\",\"DeleteOnTermination\":true}}]" \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$INSTANCE_NAME}]" \
--query 'Instances[0].InstanceId' \
--output text)
if [ -z "$INSTANCE_ID" ]; then
echo "Failed to launch instance."
exit 1
fi
# Wait for the instance to be in 'running' state
echo "Waiting for instance to be in 'running' state..."
aws ec2 wait instance-running \
--region "$REGION" \
--instance-ids "$INSTANCE_ID"
# Get and print the private IP address
PRIVATE_IP=$(aws ec2 describe-instances \
--region "$REGION" \
--instance-ids "$INSTANCE_ID" \
--query 'Reservations[0].Instances[0].PrivateIpAddress' \
--output text)
if [ -z "$PRIVATE_IP" ]; then
echo "Failed to retrieve private IP address."
exit 1
fi
echo "Private IP: $PRIVATE_IP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment