Launch, Connect, and Manage EC2 Instances
Provision EC2 instances from the CLI, configure security groups, connect via SSH, and manage instance lifecycle operations.
Prerequisites
- -AWS CLI v2 installed and configured
- -SSH key pair created in your AWS region
Steps
Find the latest Amazon Linux AMI
Query the SSM Parameter Store to find the latest Amazon Linux 2023 AMI ID for your region instead of hardcoding AMI IDs.
Using SSM parameters for AMI lookup ensures you always get the latest patched image for your region.
Create a security group
Create a security group that allows SSH access from your current IP address only.
Never use 0.0.0.0/0 for SSH access in production. Always restrict to known IP ranges.
Launch the EC2 instance
Run an EC2 instance with the selected AMI, instance type, key pair, and security group.
t3.micro is free tier eligible. Always add Name tags to make instances easy to identify.
Wait for the instance to be running
Use the AWS CLI waiter to block until the instance reaches the running state before attempting to connect.
Connect via SSH
SSH into the running instance using your key pair and the public IP address.
If connection is refused, wait a minute for the instance to finish booting. Check that your security group allows your IP.
Stop or terminate the instance
Stop the instance to save costs while preserving data, or terminate it to delete it permanently.
Terminated instances are permanently deleted and cannot be recovered. Use stop-instances to pause billing while keeping the instance.
Full Script
FAQ
Discussion
Loading comments...