{"id":"ec2","name":"ec2","summary":"AWS EC2仮想マシン管理 — インスタンス、セキュリティグループ、キーペア、AMI、EBSボリューム、自動スケーリンググループ、スポットインスタンス、セッションマネージャー、配置グループ、インスタンスライフサイクル自動化。","body":"# AWS EC2\n\nAmazon Elastic Compute Cloud (EC2) provides resizable compute capacity in the cloud.\n\n**Advanced patterns** (Auto Scaling, Spot Fleets, Session Manager, Instance Connect, IMDS, Placement Groups, scheduled scaling): see [instance-management.md](instance-management.md).\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Instance Types\n\n| Category | Example | Use Case |\n|----------|---------|----------|\n| General Purpose | t3, m6i, t4g (Graviton) | Web servers, dev environments |\n| Compute Optimized | c6i, c7g (Graviton) | Batch processing, gaming |\n| Memory Optimized | r6i, r7g (Graviton) | Databases, caching |\n| Storage Optimized | i3, d3 | Data warehousing |\n| Accelerated | p4d, g5 | ML, graphics |\n\nGraviton (ARM) instances (t4g, m7g, c7g, r7g) are ~20% cheaper than x86 equivalents for the same performance — worth considering for new workloads.\n\n### Purchasing Options\n\n| Option | Description |\n|--------|-------------|\n| On-Demand | Pay by the hour/second |\n| Reserved | 1-3 year commitment, up to 72% discount |\n| Spot | Unused capacity, up to 90% discount — can be interrupted with 2-minute notice |\n| Savings Plans | Flexible commitment-based discount |\n\n### AMI (Amazon Machine Image)\n\nTemplate containing OS, software, and configuration for launching instances. Use SSM Parameter Store to look up the latest official AMIs rather than hardcoding IDs:\n\n```bash\n# Latest Amazon Linux 2 AMI\naws ssm get-parameter \\\n  --name /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 \\\n  --query 'Parameter.Value' --output text\n\n# Latest Amazon Linux 2023\naws ssm get-parameter \\\n  --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \\\n  --query 'Parameter.Value' --output text\n\n# Latest Ubuntu 22.04\naws ssm get-parameter \\\n  --name /aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id \\\n  --query 'Parameter.Value' --output text\n```\n\n### Security Groups\n\nVirtual firewalls controlling inbound and outbound traffic. Changes take effect immediately — no restart required.\n\n## Common Patterns\n\n### Launch an Instance\n\n```bash\n# Create key pair\naws ec2 create-key-pair \\\n  --key-name my-key \\\n  --query 'KeyMaterial' \\\n  --output text > my-key.pem\nchmod 400 my-key.pem\n\n# Create security group\naws ec2 create-security-group \\\n  --group-name web-server-sg \\\n  --description \"Web server security group\" \\\n  --vpc-id vpc-12345678\n\n# Allow SSH and HTTP\naws ec2 authorize-security-group-ingress \\\n  --group-id sg-12345678 \\\n  --protocol tcp \\\n  --port 22 \\\n  --cidr 10.0.0.0/8\n\naws ec2 authorize-security-group-ingress \\\n  --group-id sg-12345678 \\\n  --protocol tcp \\\n  --port 80 \\\n  --cidr 0.0.0.0/0\n\n# Launch instance\naws ec2 run-instances \\\n  --image-id ami-0123456789abcdef0 \\\n  --instance-type t3.micro \\\n  --key-name my-key \\\n  --security-group-ids sg-12345678 \\\n  --subnet-id subnet-12345678 \\\n  --associate-public-ip-address \\\n  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-server}]'\n\n# Wait until running, then get IP\naws ec2 wait instance-running --instance-ids i-1234567890abcdef0\naws ec2 describe-instances \\\n  --instance-ids i-1234567890abcdef0 \\\n  --query 'Reservations[].Instances[].PublicIpAddress' --output text\n```\n\n**boto3:**\n\n```python\nimport boto3\n\nec2 = boto3.resource('ec2')\n\ninstances = ec2.create_instances(\n    ImageId='ami-0123456789abcdef0',\n    InstanceType='t3.micro',\n    KeyName='my-key',\n    SecurityGroupIds=['sg-12345678'],\n    SubnetId='subnet-12345678',\n    MinCount=1,\n    MaxCount=1,\n    TagSpecifications=[{\n        'ResourceType': 'instance',\n        'Tags': [{'Key': 'Name', 'Value': 'web-server'}]\n    }]\n)\n\ninstance = instances[0]\ninstance.wait_until_running()\ninstance.reload()\nprint(f\"Instance ID: {instance.id}\")\nprint(f\"Public IP: {instance.public_ip_address}\")\n```\n\n### User Data Script\n\n> **OS package manager note:**\n> - **Amazon Linux 2**: use `amazon-linux-extras install nginx1 -y` — `yum install nginx` fails because nginx is not in the default AL2 repos\n> - **Amazon Linux 2023**: use `dnf install -y nginx`\n> - **Ubuntu**: use `apt-get install -y nginx`\n> - **Amazon Linux 2 / RHEL**: `httpd` (Apache) is always available via `yum install -y httpd`\n\n```bash\n# Amazon Linux 2 — nginx via amazon-linux-extras\naws ec2 run-instances \\\n  --image-id ami-0123456789abcdef0 \\\n  --instance-type t3.micro \\\n  --key-name my-key \\\n  --security-group-ids sg-12345678 \\\n  --subnet-id subnet-12345678 \\\n  --user-data '#!/bin/bash\namazon-linux-extras install nginx1 -y\nsystemctl start nginx\nsystemctl enable nginx\n'\n\n# Amazon Linux 2 — httpd (Apache, simpler alternative)\n# --user-data '#!/bin/bash\n# yum install -y httpd\n# systemctl start httpd\n# systemctl enable httpd\n# echo \"<h1>Hello from $(hostname -f)</h1>\" > /var/www/html/index.html\n# '\n```\n\n### Attach IAM Role\n\n```bash\n# Create instance profile\naws iam create-instance-profile \\\n  --instance-profile-name web-server-profile\n\naws iam add-role-to-instance-profile \\\n  --instance-profile-name web-server-profile \\\n  --role-name web-server-role\n\n# Launch with profile\naws ec2 run-instances \\\n  --image-id ami-0123456789abcdef0 \\\n  --instance-type t3.micro \\\n  --iam-instance-profile Name=web-server-profile \\\n  ...\n```\n\n### Create AMI from Instance\n\n```bash\naws ec2 create-image \\\n  --instance-id i-1234567890abcdef0 \\\n  --name \"my-custom-ami-$(date +%Y%m%d)\" \\\n  --description \"Custom AMI with web server\" \\\n  --no-reboot\n```\n\n### Auto Scaling Group with Spot (Modern Approach)\n\nThe recommended way to use Spot Instances at scale is via Auto Scaling Groups with a mixed-instances policy — not the legacy `request-spot-instances` API. This supports instance diversification to minimize interruptions.\n\nSee [instance-management.md](instance-management.md) for the full setup. Quick example:\n\n```bash\n# 1. Create launch template with IMDSv2\naws ec2 create-launch-template \\\n  --launch-template-name my-lt \\\n  --launch-template-data '{\n    \"ImageId\": \"ami-0123456789abcdef0\",\n    \"SecurityGroupIds\": [\"sg-12345678\"],\n    \"IamInstanceProfile\": {\"Name\": \"my-profile\"},\n    \"MetadataOptions\": {\"HttpTokens\": \"required\", \"HttpEndpoint\": \"enabled\"}\n  }'\n\n# 2. Create ASG with mixed-instances (Spot + On-Demand diversification)\naws autoscaling create-auto-scaling-group \\\n  --auto-scaling-group-name my-asg \\\n  --min-size 0 --max-size 20 --desired-capacity 2 \\\n  --vpc-zone-identifier \"subnet-111,subnet-222\" \\\n  --mixed-instances-policy '{\n    \"LaunchTemplate\": {\n      \"LaunchTemplateSpecification\": {\"LaunchTemplateName\": \"my-lt\", \"Version\": \"$Latest\"},\n      \"Overrides\": [\n        {\"InstanceType\": \"c5.xlarge\"},\n        {\"InstanceType\": \"c5.2xlarge\"},\n        {\"InstanceType\": \"c5a.xlarge\"}\n      ]\n    },\n    \"InstancesDistribution\": {\n      \"OnDemandBaseCapacity\": 0,\n      \"OnDemandPercentageAboveBaseCapacity\": 0,\n      \"SpotAllocationStrategy\": \"capacity-optimized\"\n    }\n  }'\n```\n\n### EBS Volume Management\n\n```bash\n# Create volume\naws ec2 create-volume \\\n  --availability-zone us-east-1a \\\n  --size 100 \\\n  --volume-type gp3 \\\n  --iops 3000 \\\n  --throughput 125 \\\n  --encrypted\n\n# Attach to instance\naws ec2 attach-volume \\\n  --volume-id vol-12345678 \\\n  --instance-id i-1234567890abcdef0 \\\n  --device /dev/sdf\n\n# Create snapshot\naws ec2 create-snapshot \\\n  --volume-id vol-12345678 \\\n  --description \"Daily backup\"\n```\n\n## CLI Reference\n\n### Instance Management\n\n| Command | Description |\n|---------|-------------|\n| `aws ec2 run-instances` | Launch instances |\n| `aws ec2 describe-instances` | List instances |\n| `aws ec2 start-instances` | Start stopped instances |\n| `aws ec2 stop-instances` | Stop running instances |\n| `aws ec2 reboot-instances` | Reboot instances |\n| `aws ec2 terminate-instances` | Terminate instances |\n| `aws ec2 modify-instance-attribute` | Modify instance settings |\n\n### Security Groups\n\n| Command | Description |\n|---------|-------------|\n| `aws ec2 create-security-group` | Create security group |\n| `aws ec2 describe-security-groups` | List security groups |\n| `aws ec2 authorize-security-group-ingress` | Add inbound rule |\n| `aws ec2 revoke-security-group-ingress` | Remove inbound rule |\n| `aws ec2 authorize-security-group-egress` | Add outbound rule |\n\n### AMIs\n\n| Command | Description |\n|---------|-------------|\n| `aws ec2 describe-images` | List AMIs |\n| `aws ec2 create-image` | Create AMI from instance |\n| `aws ec2 copy-image` | Copy AMI to another region |\n| `aws ec2 deregister-image` | Delete AMI |\n\n### EBS Volumes\n\n| Command | Description |\n|---------|-------------|\n| `aws ec2 create-volume` | Create EBS volume |\n| `aws ec2 attach-volume` | Attach to instance |\n| `aws ec2 detach-volume` | Detach from instance |\n| `aws ec2 create-snapshot` | Create snapshot |\n| `aws ec2 modify-volume` | Resize/modify volume |\n\n## Best Practices\n\n### Security\n\n- **Use IAM roles** instead of access keys on instances\n- **Restrict security groups** — principle of least privilege\n- **Use private subnets** for backend instances\n- **Enable IMDSv2** to prevent SSRF attacks\n- **Encrypt EBS volumes** at rest\n\n```bash\n# Require IMDSv2 on existing instance\naws ec2 modify-instance-metadata-options \\\n  --instance-id i-1234567890abcdef0 \\\n  --http-tokens required \\\n  --http-endpoint enabled\n```\n\n### Performance\n\n- **Right-size instances** — monitor and adjust\n- **Use EBS-optimized instances**\n- **Choose appropriate EBS volume type** (gp3 is the default good choice; io2 for high IOPS)\n- **Use placement groups** for low-latency networking (see instance-management.md)\n\n### Cost Optimization\n\n- **Use Spot Instances** for fault-tolerant workloads (batch, ML training, CI)\n- **Stop/terminate unused instances**\n- **Use Reserved Instances or Savings Plans** for steady-state workloads\n- **Delete unused EBS volumes and snapshots**\n- **Consider Graviton (t4g, m7g, c7g)** — ~20% cheaper for same performance\n\n### Reliability\n\n- **Use Auto Scaling Groups** for high availability (see instance-management.md)\n- **Deploy across multiple AZs**\n- **Use Elastic Load Balancer** for traffic distribution\n- **Implement health checks**\n\n## Troubleshooting\n\n### Cannot SSH to Instance\n\n**First: identify the error type — it points to different root causes:**\n\n| Error | What it means | Primary suspects |\n|-------|--------------|-----------------|\n| `Connection refused` | Network is reachable, but SSH daemon is not listening | sshd crashed, sshd not installed, OS firewall (ufw/iptables) blocking, wrong port |\n| `Connection timed out` | Packets never arrive | Security group blocks port 22, NACL blocks traffic, no public IP, wrong IP |\n| `Permission denied` | Connected, but auth failed | Wrong key file, wrong username, key not authorized |\n\n**Common username by OS:**\n\n| OS | Default SSH user |\n|----|-----------------|\n| Amazon Linux 2 / 2023 | `ec2-user` |\n| Ubuntu | `ubuntu` |\n| Debian | `admin` |\n| CentOS / RHEL | `ec2-user` or `centos` |\n| Windows | `Administrator` |\n\n**Diagnostic commands:**\n\n```bash\n# 1. Check instance state and public IP\naws ec2 describe-instances \\\n  --instance-ids i-1234567890abcdef0 \\\n  --query \"Reservations[].Instances[].{State:State.Name,PublicIP:PublicIpAddress,StatusChecks:State.Name}\"\n\n# 2. Check instance status (system + instance checks)\naws ec2 describe-instance-status --instance-ids i-1234567890abcdef0\n\n# 3. Check security group rules for port 22\naws ec2 describe-security-groups \\\n  --group-ids sg-12345678 \\\n  --query \"SecurityGroups[].IpPermissions[?ToPort==\\`22\\`]\"\n\n# 4. Get console output to see boot logs, sshd errors, OOM events\naws ec2 get-console-output \\\n  --instance-id i-1234567890abcdef0 \\\n  --latest \\\n  --query Output --output text\n```\n\n**If connection refused — get inside via Session Manager to fix sshd:**\n\n```bash\n# Requires SSM agent on instance + AmazonSSMManagedInstanceCore policy\naws ssm start-session --target i-1234567890abcdef0\n\n# Once inside, diagnose:\nsystemctl status ssh        # Ubuntu\nsystemctl status sshd       # Amazon Linux\ndf -h                       # Check disk full\nsudo sshd -t                # Test sshd config for syntax errors\nsudo journalctl -u ssh -n 50  # Recent sshd logs\n```\n\n**Use Session Manager instead of SSH** (no open ports, no key pair needed):\n\n```bash\naws ssm start-session --target i-1234567890abcdef0\n\n# Port forwarding via SSM\naws ssm start-session \\\n  --target i-1234567890abcdef0 \\\n  --document-name AWS-StartPortForwardingSession \\\n  --parameters '{\"portNumber\":[\"22\"],\"localPortNumber\":[\"2222\"]}'\n```\n\n### Instance Won't Start\n\n**Causes:**\n- Reached instance limits\n- Insufficient capacity in AZ\n- EBS volume issue\n- Invalid AMI\n\n```bash\n# Check instance state reason\naws ec2 describe-instances \\\n  --instance-ids i-1234567890abcdef0 \\\n  --query \"Reservations[].Instances[].StateReason\"\n```\n\n### Instance Unreachable\n\n```bash\n# Check instance status\naws ec2 describe-instance-status \\\n  --instance-ids i-1234567890abcdef0\n\n# Get console output\naws ec2 get-console-output \\\n  --instance-id i-1234567890abcdef0 \\\n  --latest\n\n# Get screenshot (for Windows/GUI issues)\naws ec2 get-console-screenshot \\\n  --instance-id i-1234567890abcdef0\n```\n\n### High CPU/Memory\n\n```bash\n# Enable detailed monitoring\naws ec2 monitor-instances \\\n  --instance-ids i-1234567890abcdef0\n\n# Check CloudWatch metrics (cross-platform date command)\nSTART=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u --date='1 hour ago' +%Y-%m-%dT%H:%M:%SZ)\naws cloudwatch get-metric-statistics \\\n  --namespace AWS/EC2 \\\n  --metric-name CPUUtilization \\\n  --dimensions Name=InstanceId,Value=i-1234567890abcdef0 \\\n  --start-time \"$START\" \\\n  --end-time \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" \\\n  --period 300 \\\n  --statistics Average\n```\n\n## References\n\n- [EC2 User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)\n- [EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/)\n- [EC2 CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/ec2/)\n- [boto3 EC2](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/ec2","license":"MIT","category":"writing","lang":"en","tokens":3846,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"evals/evals.json","size":4432,"sha256":"3b49a6fa55c9d04bf1414aa99aa660867b4b806938260db2820787fb8fe6e345"},{"path":"instance-management.md","size":9387,"sha256":"460c712f301f43e6b4660fe92b51fe70195313518bee5980c4bfe26039627614"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["boto3.amazonaws.com","docs.aws.amazon.com"]}}