mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
766 lines
34 KiB
HTML
766 lines
34 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>cloud-aws-ec2-compute</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/cloud-aws-ec2-compute.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/cloud-aws-ec2-compute">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/cloud-aws-ec2-compute.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>cloud-aws-ec2-compute</h1><p class="lede">AWS EC2 instances, Auto Scaling, Load Balancing, AMIs, and instance lifecycle management</p><h1>AWS EC2 Compute</h1>
|
|
<p><strong>Scope</strong>: EC2 instances - instance types, Auto Scaling Groups, Elastic Load Balancing, AMIs, user data, spot instances <strong>Lines</strong>: ~350 <strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Deploying applications on EC2 instances</li><li>Configuring Auto Scaling for dynamic capacity</li><li>Setting up load balancers (ALB, NLB, CLB)</li><li>Creating and managing AMIs for deployment</li><li>Implementing immutable infrastructure patterns</li><li>Optimizing compute costs with spot instances</li><li>Configuring user data scripts for instance initialization</li><li>Troubleshooting EC2 performance or connectivity issues</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: EC2 Instance Types and Sizing</h3>
|
|
<p><strong>Instance families</strong>:</p>
|
|
<ul><li><strong>T3/T4g</strong>: Burstable, cost-effective for variable workloads</li><li><strong>M5/M6i</strong>: General purpose, balanced CPU/memory</li><li><strong>C5/C6i</strong>: Compute-optimized for CPU-intensive tasks</li><li><strong>R5/R6i</strong>: Memory-optimized for large datasets</li><li><strong>I3/I4i</strong>: Storage-optimized for high IOPS</li></ul>
|
|
<pre><code class="lang-bash"># Launch t3.medium instance (2 vCPU, 4 GB RAM)
|
|
aws ec2 run-instances \
|
|
--image-id ami-0abcdef1234567890 \
|
|
--instance-type t3.medium \
|
|
--key-name my-key-pair \
|
|
--security-group-ids sg-0123456789abcdef0 \
|
|
--subnet-id subnet-0bb1c79de3EXAMPLE
|
|
|
|
# Launch c5.xlarge for CPU-intensive workload
|
|
aws ec2 run-instances \
|
|
--image-id ami-0abcdef1234567890 \
|
|
--instance-type c5.xlarge \
|
|
--count 2 \
|
|
--key-name my-key-pair</code></pre>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
ec2 = boto3.client('ec2')
|
|
|
|
def launch_instance(instance_type, ami_id, key_name, security_group_ids):
|
|
"""Launch EC2 instance with configuration"""
|
|
|
|
response = ec2.run_instances(
|
|
ImageId=ami_id,
|
|
InstanceType=instance_type,
|
|
KeyName=key_name,
|
|
SecurityGroupIds=security_group_ids,
|
|
MinCount=1,
|
|
MaxCount=1,
|
|
TagSpecifications=[
|
|
{
|
|
'ResourceType': 'instance',
|
|
'Tags': [
|
|
{'Key': 'Name', 'Value': 'my-app-server'},
|
|
{'Key': 'Environment', 'Value': 'production'}
|
|
]
|
|
}
|
|
]
|
|
)
|
|
|
|
instance_id = response['Instances'][0]['InstanceId']
|
|
print(f"Launched instance: {instance_id}")
|
|
|
|
return instance_id</code></pre>
|
|
<h3>Concept 2: Auto Scaling Groups</h3>
|
|
<p><strong>Auto Scaling benefits</strong>:</p>
|
|
<ul><li>Automatic capacity adjustment</li><li>Health checks and replacement</li><li>Multi-AZ high availability</li><li>Integration with load balancers</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
autoscaling = boto3.client('autoscaling')
|
|
|
|
def create_auto_scaling_group():
|
|
"""Create Auto Scaling Group with launch template"""
|
|
|
|
# Create launch template
|
|
ec2 = boto3.client('ec2')
|
|
template_response = ec2.create_launch_template(
|
|
LaunchTemplateName='my-app-template',
|
|
LaunchTemplateData={
|
|
'ImageId': 'ami-0abcdef1234567890',
|
|
'InstanceType': 't3.medium',
|
|
'KeyName': 'my-key-pair',
|
|
'SecurityGroupIds': ['sg-0123456789abcdef0'],
|
|
'UserData': base64.b64encode(USER_DATA.encode()).decode(),
|
|
'IamInstanceProfile': {'Name': 'my-ec2-role'},
|
|
'TagSpecifications': [
|
|
{
|
|
'ResourceType': 'instance',
|
|
'Tags': [
|
|
{'Key': 'Name', 'Value': 'my-app-asg'},
|
|
{'Key': 'ManagedBy', 'Value': 'AutoScaling'}
|
|
]
|
|
}
|
|
]
|
|
}
|
|
)
|
|
|
|
# Create Auto Scaling Group
|
|
autoscaling.create_auto_scaling_group(
|
|
AutoScalingGroupName='my-app-asg',
|
|
LaunchTemplate={
|
|
'LaunchTemplateName': 'my-app-template',
|
|
'Version': '$Latest'
|
|
},
|
|
MinSize=2,
|
|
MaxSize=10,
|
|
DesiredCapacity=3,
|
|
HealthCheckType='ELB', # Use load balancer health checks
|
|
HealthCheckGracePeriod=300,
|
|
VPCZoneIdentifier='subnet-abc123,subnet-def456', # Multi-AZ
|
|
TargetGroupARNs=['arn:aws:elasticloadbalancing:...'],
|
|
Tags=[
|
|
{
|
|
'Key': 'Environment',
|
|
'Value': 'production',
|
|
'PropagateAtLaunch': True
|
|
}
|
|
]
|
|
)
|
|
|
|
print("Created Auto Scaling Group")
|
|
|
|
# Scaling policies
|
|
def create_scaling_policies(asg_name):
|
|
"""Create target tracking scaling policy"""
|
|
|
|
# Scale based on CPU utilization
|
|
autoscaling.put_scaling_policy(
|
|
AutoScalingGroupName=asg_name,
|
|
PolicyName='cpu-target-tracking',
|
|
PolicyType='TargetTrackingScaling',
|
|
TargetTrackingConfiguration={
|
|
'PredefinedMetricSpecification': {
|
|
'PredefinedMetricType': 'ASGAverageCPUUtilization'
|
|
},
|
|
'TargetValue': 70.0 # Scale when CPU > 70%
|
|
}
|
|
)
|
|
|
|
# Scale based on request count
|
|
autoscaling.put_scaling_policy(
|
|
AutoScalingGroupName=asg_name,
|
|
PolicyName='request-count-tracking',
|
|
PolicyType='TargetTrackingScaling',
|
|
TargetTrackingConfiguration={
|
|
'PredefinedMetricSpecification': {
|
|
'PredefinedMetricType': 'ALBRequestCountPerTarget',
|
|
'ResourceLabel': 'app/my-alb/abc123/targetgroup/my-tg/def456'
|
|
},
|
|
'TargetValue': 1000.0 # Scale when requests/target > 1000
|
|
}
|
|
)</code></pre>
|
|
<h3>Concept 3: Elastic Load Balancing</h3>
|
|
<p><strong>Load balancer types</strong>:</p>
|
|
<ul><li><strong>ALB</strong>: Layer 7 (HTTP/HTTPS), host/path routing, WebSocket</li><li><strong>NLB</strong>: Layer 4 (TCP/UDP), high throughput, static IPs</li><li><strong>CLB</strong>: Legacy, basic load balancing (deprecated)</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
elbv2 = boto3.client('elbv2')
|
|
|
|
def create_application_load_balancer():
|
|
"""Create Application Load Balancer with target group"""
|
|
|
|
# Create ALB
|
|
alb_response = elbv2.create_load_balancer(
|
|
Name='my-app-alb',
|
|
Subnets=['subnet-abc123', 'subnet-def456'], # Multi-AZ
|
|
SecurityGroups=['sg-0123456789abcdef0'],
|
|
Scheme='internet-facing',
|
|
Type='application',
|
|
IpAddressType='ipv4',
|
|
Tags=[
|
|
{'Key': 'Name', 'Value': 'my-app-alb'},
|
|
{'Key': 'Environment', 'Value': 'production'}
|
|
]
|
|
)
|
|
|
|
alb_arn = alb_response['LoadBalancers'][0]['LoadBalancerArn']
|
|
dns_name = alb_response['LoadBalancers'][0]['DNSName']
|
|
|
|
print(f"Created ALB: {dns_name}")
|
|
|
|
# Create target group
|
|
tg_response = elbv2.create_target_group(
|
|
Name='my-app-targets',
|
|
Protocol='HTTP',
|
|
Port=80,
|
|
VpcId='vpc-0123456789abcdef0',
|
|
HealthCheckProtocol='HTTP',
|
|
HealthCheckPath='/health',
|
|
HealthCheckIntervalSeconds=30,
|
|
HealthCheckTimeoutSeconds=5,
|
|
HealthyThresholdCount=2,
|
|
UnhealthyThresholdCount=3,
|
|
Matcher={'HttpCode': '200'}
|
|
)
|
|
|
|
tg_arn = tg_response['TargetGroups'][0]['TargetGroupArn']
|
|
|
|
# Create listener
|
|
elbv2.create_listener(
|
|
LoadBalancerArn=alb_arn,
|
|
Protocol='HTTP',
|
|
Port=80,
|
|
DefaultActions=[
|
|
{
|
|
'Type': 'forward',
|
|
'TargetGroupArn': tg_arn
|
|
}
|
|
]
|
|
)
|
|
|
|
return alb_arn, tg_arn
|
|
|
|
def create_alb_listener_rules(listener_arn, tg_arn_api, tg_arn_web):
|
|
"""Create path-based routing rules"""
|
|
|
|
# Route /api/* to API target group
|
|
elbv2.create_rule(
|
|
ListenerArn=listener_arn,
|
|
Priority=10,
|
|
Conditions=[
|
|
{
|
|
'Field': 'path-pattern',
|
|
'Values': ['/api/*']
|
|
}
|
|
],
|
|
Actions=[
|
|
{
|
|
'Type': 'forward',
|
|
'TargetGroupArn': tg_arn_api
|
|
}
|
|
]
|
|
)
|
|
|
|
# Route specific host to different target group
|
|
elbv2.create_rule(
|
|
ListenerArn=listener_arn,
|
|
Priority=20,
|
|
Conditions=[
|
|
{
|
|
'Field': 'host-header',
|
|
'Values': ['admin.example.com']
|
|
}
|
|
],
|
|
Actions=[
|
|
{
|
|
'Type': 'forward',
|
|
'TargetGroupArn': tg_arn_web
|
|
}
|
|
]
|
|
)</code></pre>
|
|
<h3>Concept 4: AMIs and Immutable Infrastructure</h3>
|
|
<p><strong>AMI workflow</strong>:</p>
|
|
<ul><li>Build golden image with application</li><li>Launch instances from AMI</li><li>Replace instances instead of patching</li><li>Faster deployments, consistent state</li></ul>
|
|
<pre><code class="lang-bash"># Create AMI from running instance
|
|
aws ec2 create-image \
|
|
--instance-id i-0123456789abcdef0 \
|
|
--name "my-app-v1.2.3-$(date +%Y%m%d)" \
|
|
--description "My app version 1.2.3" \
|
|
--no-reboot
|
|
|
|
# Copy AMI to another region
|
|
aws ec2 copy-image \
|
|
--source-region us-east-1 \
|
|
--source-image-id ami-0abcdef1234567890 \
|
|
--name "my-app-v1.2.3" \
|
|
--region us-west-2
|
|
|
|
# Share AMI with another account
|
|
aws ec2 modify-image-attribute \
|
|
--image-id ami-0abcdef1234567890 \
|
|
--launch-permission "Add=[{UserId=123456789012}]"</code></pre>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
ec2 = boto3.client('ec2')
|
|
|
|
def create_ami(instance_id, name, description):
|
|
"""Create AMI from instance"""
|
|
|
|
response = ec2.create_image(
|
|
InstanceId=instance_id,
|
|
Name=name,
|
|
Description=description,
|
|
NoReboot=True, # Don't reboot (faster but less consistent)
|
|
TagSpecifications=[
|
|
{
|
|
'ResourceType': 'image',
|
|
'Tags': [
|
|
{'Key': 'Name', 'Value': name},
|
|
{'Key': 'CreatedBy', 'Value': 'automation'}
|
|
]
|
|
}
|
|
]
|
|
)
|
|
|
|
ami_id = response['ImageId']
|
|
print(f"Creating AMI: {ami_id}")
|
|
|
|
# Wait for AMI to be available
|
|
waiter = ec2.get_waiter('image_available')
|
|
waiter.wait(ImageIds=[ami_id])
|
|
|
|
print(f"AMI ready: {ami_id}")
|
|
return ami_id
|
|
|
|
def cleanup_old_amis(name_prefix, keep_count=5):
|
|
"""Delete old AMIs, keep only recent versions"""
|
|
|
|
# List AMIs
|
|
response = ec2.describe_images(
|
|
Owners=['self'],
|
|
Filters=[
|
|
{'Name': 'name', 'Values': [f'{name_prefix}*']},
|
|
{'Name': 'state', 'Values': ['available']}
|
|
]
|
|
)
|
|
|
|
# Sort by creation date
|
|
images = sorted(
|
|
response['Images'],
|
|
key=lambda x: x['CreationDate'],
|
|
reverse=True
|
|
)
|
|
|
|
# Delete old images
|
|
for image in images[keep_count:]:
|
|
ami_id = image['ImageId']
|
|
print(f"Deregistering AMI: {ami_id}")
|
|
|
|
# Delete snapshots
|
|
for mapping in image.get('BlockDeviceMappings', []):
|
|
if 'Ebs' in mapping:
|
|
snapshot_id = mapping['Ebs']['SnapshotId']
|
|
ec2.delete_snapshot(SnapshotId=snapshot_id)
|
|
|
|
# Deregister AMI
|
|
ec2.deregister_image(ImageId=ami_id)</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: User Data for Instance Initialization</h3>
|
|
<p><strong>When to use</strong>: Bootstrap instances on launch</p>
|
|
<pre><code class="lang-bash">#!/bin/bash
|
|
# User data script - runs on first boot
|
|
|
|
# Update packages
|
|
yum update -y
|
|
|
|
# Install application dependencies
|
|
yum install -y docker git
|
|
|
|
# Start Docker
|
|
systemctl start docker
|
|
systemctl enable docker
|
|
|
|
# Pull and run application
|
|
docker pull myregistry/myapp:latest
|
|
docker run -d -p 80:8080 --name myapp myregistry/myapp:latest
|
|
|
|
# Configure CloudWatch agent
|
|
wget https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm
|
|
rpm -U ./amazon-cloudwatch-agent.rpm
|
|
|
|
# Signal Auto Scaling that instance is ready
|
|
aws autoscaling complete-lifecycle-action \
|
|
--lifecycle-action-result CONTINUE \
|
|
--lifecycle-hook-name my-launch-hook \
|
|
--auto-scaling-group-name my-asg \
|
|
--lifecycle-action-token $TOKEN \
|
|
--region us-east-1</code></pre>
|
|
<pre><code class="lang-python">import base64
|
|
|
|
# User data in Python
|
|
USER_DATA = """#!/bin/bash
|
|
set -e
|
|
|
|
# Install dependencies
|
|
yum update -y
|
|
yum install -y python3 pip3
|
|
|
|
# Clone application
|
|
cd /opt
|
|
git clone https://github.com/myorg/myapp.git
|
|
cd myapp
|
|
|
|
# Install requirements
|
|
pip3 install -r requirements.txt
|
|
|
|
# Start application
|
|
python3 app.py &
|
|
|
|
# Health check endpoint
|
|
echo "Instance ready" > /var/www/html/health
|
|
"""
|
|
|
|
# Launch instance with user data
|
|
ec2.run_instances(
|
|
ImageId='ami-0abcdef1234567890',
|
|
InstanceType='t3.medium',
|
|
UserData=base64.b64encode(USER_DATA.encode()).decode(),
|
|
IamInstanceProfile={'Name': 'my-ec2-role'}
|
|
)</code></pre>
|
|
<h3>Pattern 2: Spot Instances for Cost Savings</h3>
|
|
<p><strong>Use case</strong>: Non-critical workloads, batch processing, CI/CD</p>
|
|
<pre><code class="lang-python">def request_spot_instances():
|
|
"""Request spot instances at target price"""
|
|
|
|
ec2 = boto3.client('ec2')
|
|
|
|
response = ec2.request_spot_instances(
|
|
SpotPrice='0.05', # Max price per hour
|
|
InstanceCount=5,
|
|
Type='one-time', # or 'persistent'
|
|
LaunchSpecification={
|
|
'ImageId': 'ami-0abcdef1234567890',
|
|
'InstanceType': 'c5.xlarge',
|
|
'KeyName': 'my-key-pair',
|
|
'SecurityGroupIds': ['sg-0123456789abcdef0'],
|
|
'UserData': base64.b64encode(BATCH_JOB_SCRIPT.encode()).decode(),
|
|
'IamInstanceProfile': {'Name': 'batch-job-role'}
|
|
}
|
|
)
|
|
|
|
for request in response['SpotInstanceRequests']:
|
|
print(f"Spot request: {request['SpotInstanceRequestId']}")
|
|
|
|
# Mix on-demand and spot in Auto Scaling Group
|
|
def create_mixed_instance_asg():
|
|
"""Create ASG with on-demand and spot instances"""
|
|
|
|
autoscaling.create_auto_scaling_group(
|
|
AutoScalingGroupName='mixed-asg',
|
|
MixedInstancesPolicy={
|
|
'LaunchTemplate': {
|
|
'LaunchTemplateSpecification': {
|
|
'LaunchTemplateName': 'my-template',
|
|
'Version': '$Latest'
|
|
},
|
|
'Overrides': [
|
|
{'InstanceType': 't3.medium'},
|
|
{'InstanceType': 't3.large'},
|
|
{'InstanceType': 't3a.medium'}, # AMD variant
|
|
]
|
|
},
|
|
'InstancesDistribution': {
|
|
'OnDemandBaseCapacity': 2, # Always 2 on-demand
|
|
'OnDemandPercentageAboveBaseCapacity': 20, # 20% on-demand
|
|
'SpotAllocationStrategy': 'lowest-price',
|
|
'SpotInstancePools': 3
|
|
}
|
|
},
|
|
MinSize=2,
|
|
MaxSize=20,
|
|
VPCZoneIdentifier='subnet-abc123,subnet-def456'
|
|
)</code></pre>
|
|
<h3>Pattern 3: Instance Metadata Service</h3>
|
|
<p><strong>Use case</strong>: Access instance info, credentials, user data</p>
|
|
<pre><code class="lang-python">import requests
|
|
|
|
METADATA_URL = "http://169.254.169.254/latest/meta-data/"
|
|
TOKEN_URL = "http://169.254.169.254/latest/api/token"
|
|
|
|
def get_instance_metadata(path):
|
|
"""Fetch instance metadata using IMDSv2 (secure)"""
|
|
|
|
# Get session token (IMDSv2 requirement)
|
|
token_response = requests.put(
|
|
TOKEN_URL,
|
|
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'}
|
|
)
|
|
token = token_response.text
|
|
|
|
# Fetch metadata
|
|
response = requests.get(
|
|
f"{METADATA_URL}{path}",
|
|
headers={'X-aws-ec2-metadata-token': token}
|
|
)
|
|
|
|
return response.text
|
|
|
|
# Usage
|
|
instance_id = get_instance_metadata('instance-id')
|
|
availability_zone = get_instance_metadata('placement/availability-zone')
|
|
instance_type = get_instance_metadata('instance-type')
|
|
public_ip = get_instance_metadata('public-ipv4')
|
|
|
|
print(f"Instance {instance_id} ({instance_type}) in {availability_zone}")
|
|
print(f"Public IP: {public_ip}")
|
|
|
|
# Get IAM role credentials
|
|
iam_role = get_instance_metadata('iam/security-credentials/')
|
|
credentials = get_instance_metadata(f'iam/security-credentials/{iam_role}')</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Instance Type Selection</h3>
|
|
<p>| Workload | Instance Family | Example | Notes | |----------|----------------|---------|-------| | Web servers | T3, T4g | t3.medium | Burstable, cost-effective | | APIs, microservices | M5, M6i | m5.large | Balanced CPU/memory | | Batch processing | C5, C6i | c5.2xlarge | Compute-optimized | | Databases, caching | R5, R6i | r5.xlarge | Memory-optimized | | Data analytics | I3, I4i | i3.2xlarge | Storage-optimized (NVMe) |</p>
|
|
<h3>Load Balancer Selection</h3>
|
|
<pre><code>Use Case | ALB | NLB | CLB
|
|
----------------------------|-----|-----|-----
|
|
HTTP/HTTPS APIs | ✅ | ❌ | ✅
|
|
Path-based routing | ✅ | ❌ | ❌
|
|
WebSocket | ✅ | ✅ | ❌
|
|
TCP/UDP (non-HTTP) | ❌ | ✅ | ✅
|
|
High throughput (millions) | ❌ | ✅ | ❌
|
|
Static IP required | ❌ | ✅ | ❌</code></pre>
|
|
<h3>Key Guidelines</h3>
|
|
<pre><code>✅ DO: Use Auto Scaling for variable load
|
|
✅ DO: Deploy across multiple AZs for high availability
|
|
✅ DO: Create AMIs for consistent deployments
|
|
✅ DO: Use spot instances for non-critical workloads
|
|
✅ DO: Tag instances for cost tracking
|
|
✅ DO: Use IMDSv2 for instance metadata (secure)
|
|
|
|
❌ DON'T: Run single instance in production (no HA)
|
|
❌ DON'T: Manually patch instances (use AMIs instead)
|
|
❌ DON'T: Use CLB for new applications (deprecated)
|
|
❌ DON'T: Skip health checks in Auto Scaling Groups
|
|
❌ DON'T: Use large instance types without monitoring (cost)</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Critical Violations</h3>
|
|
<pre><code class="lang-bash"># ❌ NEVER: Store credentials in user data
|
|
#!/bin/bash
|
|
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
|
|
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG
|
|
# Visible in console, metadata, logs
|
|
|
|
# ✅ CORRECT: Use IAM instance profile
|
|
# Attach role to instance, no credentials needed
|
|
aws ec2 run-instances \
|
|
--iam-instance-profile Name=my-ec2-role \
|
|
...</code></pre>
|
|
<p>❌ <strong>Credentials in user data</strong>: Exposed in EC2 console, metadata service, CloudTrail logs</p>
|
|
<p>✅ <strong>Correct approach</strong>: Use IAM roles attached to instances</p>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code class="lang-python"># ❌ Don't run single instance without Auto Scaling
|
|
ec2.run_instances(
|
|
ImageId='ami-123',
|
|
InstanceType='t3.medium',
|
|
MinCount=1,
|
|
MaxCount=1
|
|
)
|
|
# Instance failure = downtime
|
|
|
|
# ✅ Correct: Use Auto Scaling Group with min=1
|
|
autoscaling.create_auto_scaling_group(
|
|
AutoScalingGroupName='my-app',
|
|
MinSize=1,
|
|
MaxSize=3,
|
|
DesiredCapacity=1,
|
|
HealthCheckType='ELB'
|
|
)
|
|
# Instance failure = automatic replacement</code></pre>
|
|
<p>❌ <strong>Single instance without HA</strong>: No recovery from failures</p>
|
|
<p>✅ <strong>Better</strong>: Even for small apps, use ASG with min=1 for auto-recovery</p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>aws-storage.md</code> - EBS volumes, snapshots, and instance storage</li><li><code>aws-networking.md</code> - VPC, security groups, and network configuration</li><li><code>aws-iam-security.md</code> - IAM roles and instance profiles</li><li><code>aws-lambda-functions.md</code> - Serverless alternative to EC2</li><li><code>infrastructure/aws-serverless.md</code> - When to use Lambda vs EC2</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/cloud-aws-ec2-compute.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |