Files
skills/public/cloud-aws-iam-security.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
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]>
2026-09-11 00:27:59 -07:00

864 lines
36 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-iam-security</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-iam-security.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/cloud-aws-iam-security">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/cloud-aws-iam-security.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-iam-security</h1><p class="lede">AWS IAM policies, roles, Cognito authentication, Secrets Manager, KMS encryption, and security best practices</p><h1>AWS IAM Security</h1>
<p><strong>Scope</strong>: AWS security - IAM policies, roles, Cognito, Secrets Manager, KMS, STS, least privilege, credential management <strong>Lines</strong>: ~340 <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>Creating IAM policies and roles for AWS services</li><li>Implementing user authentication with Cognito</li><li>Managing secrets with Secrets Manager or Parameter Store</li><li>Configuring encryption with KMS</li><li>Setting up temporary credentials with STS</li><li>Implementing least privilege access control</li><li>Troubleshooting permission errors or access denied issues</li><li>Auditing security configurations and credentials</li></ul>
<h2>Core Concepts</h2>
<h3>Concept 1: IAM Policies</h3>
<p><strong>Policy types</strong>:</p>
<ul><li><strong>Identity-based</strong>: Attached to users, groups, roles</li><li><strong>Resource-based</strong>: Attached to resources (S3, Lambda)</li><li><strong>Permission boundaries</strong>: Maximum permissions</li><li><strong>Service control policies</strong>: Organization-level restrictions</li></ul>
<pre><code class="lang-python">import boto3
import json
iam = boto3.client(&#x27;iam&#x27;)
def create_lambda_execution_role():
&quot;&quot;&quot;Create IAM role for Lambda with least privilege&quot;&quot;&quot;
# Trust policy - who can assume this role
trust_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Principal&quot;: {
&quot;Service&quot;: &quot;lambda.amazonaws.com&quot;
},
&quot;Action&quot;: &quot;sts:AssumeRole&quot;
}
]
}
# Create role
role_response = iam.create_role(
RoleName=&#x27;lambda-execution-role&#x27;,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description=&#x27;Execution role for Lambda functions&#x27;,
Tags=[
{&#x27;Key&#x27;: &#x27;Purpose&#x27;, &#x27;Value&#x27;: &#x27;Lambda&#x27;},
{&#x27;Key&#x27;: &#x27;ManagedBy&#x27;, &#x27;Value&#x27;: &#x27;automation&#x27;}
]
)
role_arn = role_response[&#x27;Role&#x27;][&#x27;Arn&#x27;]
# Attach AWS managed policy for CloudWatch Logs
iam.attach_role_policy(
RoleName=&#x27;lambda-execution-role&#x27;,
PolicyArn=&#x27;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&#x27;
)
# Create custom policy for DynamoDB access
dynamodb_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: [
&quot;dynamodb:GetItem&quot;,
&quot;dynamodb:PutItem&quot;,
&quot;dynamodb:UpdateItem&quot;,
&quot;dynamodb:Query&quot;
],
&quot;Resource&quot;: [
&quot;arn:aws:dynamodb:us-east-1:123456789012:table/Users&quot;,
&quot;arn:aws:dynamodb:us-east-1:123456789012:table/Users/index/*&quot;
]
}
]
}
# Create and attach custom policy
policy_response = iam.create_policy(
PolicyName=&#x27;lambda-dynamodb-access&#x27;,
PolicyDocument=json.dumps(dynamodb_policy),
Description=&#x27;Allow Lambda to access DynamoDB Users table&#x27;
)
iam.attach_role_policy(
RoleName=&#x27;lambda-execution-role&#x27;,
PolicyArn=policy_response[&#x27;Policy&#x27;][&#x27;Arn&#x27;]
)
print(f&quot;Created Lambda execution role: {role_arn}&quot;)
return role_arn
def create_s3_readonly_policy(bucket_name):
&quot;&quot;&quot;Create policy for read-only S3 access&quot;&quot;&quot;
policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: [
&quot;s3:GetObject&quot;,
&quot;s3:ListBucket&quot;
],
&quot;Resource&quot;: [
f&quot;arn:aws:s3:::{bucket_name}&quot;,
f&quot;arn:aws:s3:::{bucket_name}/*&quot;
]
}
]
}
response = iam.create_policy(
PolicyName=f&#x27;{bucket_name}-readonly&#x27;,
PolicyDocument=json.dumps(policy)
)
return response[&#x27;Policy&#x27;][&#x27;Arn&#x27;]</code></pre>
<h3>Concept 2: Cognito User Authentication</h3>
<p><strong>Cognito components</strong>:</p>
<ul><li><strong>User Pools</strong>: User directory, sign-up/sign-in</li><li><strong>Identity Pools</strong>: AWS credentials for users</li><li><strong>Authentication flows</strong>: Username/password, OAuth, SAML</li></ul>
<pre><code class="lang-python">import boto3
cognito = boto3.client(&#x27;cognito-idp&#x27;)
def create_user_pool():
&quot;&quot;&quot;Create Cognito User Pool for authentication&quot;&quot;&quot;
response = cognito.create_user_pool(
PoolName=&#x27;myapp-users&#x27;,
Policies={
&#x27;PasswordPolicy&#x27;: {
&#x27;MinimumLength&#x27;: 12,
&#x27;RequireUppercase&#x27;: True,
&#x27;RequireLowercase&#x27;: True,
&#x27;RequireNumbers&#x27;: True,
&#x27;RequireSymbols&#x27;: True
}
},
AutoVerifiedAttributes=[&#x27;email&#x27;],
EmailConfiguration={
&#x27;EmailSendingAccount&#x27;: &#x27;COGNITO_DEFAULT&#x27;
},
Schema=[
{
&#x27;Name&#x27;: &#x27;email&#x27;,
&#x27;AttributeDataType&#x27;: &#x27;String&#x27;,
&#x27;Required&#x27;: True,
&#x27;Mutable&#x27;: False
},
{
&#x27;Name&#x27;: &#x27;name&#x27;,
&#x27;AttributeDataType&#x27;: &#x27;String&#x27;,
&#x27;Required&#x27;: True,
&#x27;Mutable&#x27;: True
}
],
MfaConfiguration=&#x27;OPTIONAL&#x27;,
UserAttributeUpdateSettings={
&#x27;AttributesRequireVerificationBeforeUpdate&#x27;: [&#x27;email&#x27;]
}
)
user_pool_id = response[&#x27;UserPool&#x27;][&#x27;Id&#x27;]
# Create app client
app_response = cognito.create_user_pool_client(
UserPoolId=user_pool_id,
ClientName=&#x27;myapp-web&#x27;,
GenerateSecret=False, # Public client (SPA)
RefreshTokenValidity=30, # Days
AccessTokenValidity=60, # Minutes
IdTokenValidity=60,
TokenValidityUnits={
&#x27;RefreshToken&#x27;: &#x27;days&#x27;,
&#x27;AccessToken&#x27;: &#x27;minutes&#x27;,
&#x27;IdToken&#x27;: &#x27;minutes&#x27;
},
ExplicitAuthFlows=[
&#x27;ALLOW_USER_PASSWORD_AUTH&#x27;,
&#x27;ALLOW_REFRESH_TOKEN_AUTH&#x27;
]
)
client_id = app_response[&#x27;UserPoolClient&#x27;][&#x27;ClientId&#x27;]
print(f&quot;Created User Pool: {user_pool_id}&quot;)
print(f&quot;App Client ID: {client_id}&quot;)
return user_pool_id, client_id
def authenticate_user(username, password, client_id):
&quot;&quot;&quot;Authenticate user and get tokens&quot;&quot;&quot;
response = cognito.initiate_auth(
ClientId=client_id,
AuthFlow=&#x27;USER_PASSWORD_AUTH&#x27;,
AuthParameters={
&#x27;USERNAME&#x27;: username,
&#x27;PASSWORD&#x27;: password
}
)
# Get tokens
id_token = response[&#x27;AuthenticationResult&#x27;][&#x27;IdToken&#x27;]
access_token = response[&#x27;AuthenticationResult&#x27;][&#x27;AccessToken&#x27;]
refresh_token = response[&#x27;AuthenticationResult&#x27;][&#x27;RefreshToken&#x27;]
return {
&#x27;id_token&#x27;: id_token,
&#x27;access_token&#x27;: access_token,
&#x27;refresh_token&#x27;: refresh_token
}</code></pre>
<h3>Concept 3: Secrets Manager</h3>
<p><strong>Secrets Manager vs Parameter Store</strong>:</p>
<ul><li><strong>Secrets Manager</strong>: Automatic rotation, audit, encryption ($0.40/secret/month)</li><li><strong>Parameter Store</strong>: Simple key-value, cheaper (free tier available)</li></ul>
<pre><code class="lang-python">import boto3
import json
secrets = boto3.client(&#x27;secretsmanager&#x27;)
def create_database_secret(db_username, db_password, db_host, db_name):
&quot;&quot;&quot;Store database credentials in Secrets Manager&quot;&quot;&quot;
secret_value = {
&#x27;username&#x27;: db_username,
&#x27;password&#x27;: db_password,
&#x27;host&#x27;: db_host,
&#x27;database&#x27;: db_name,
&#x27;port&#x27;: 5432
}
response = secrets.create_secret(
Name=&#x27;myapp/database/credentials&#x27;,
Description=&#x27;Database credentials for myapp&#x27;,
SecretString=json.dumps(secret_value),
Tags=[
{&#x27;Key&#x27;: &#x27;Environment&#x27;, &#x27;Value&#x27;: &#x27;production&#x27;},
{&#x27;Key&#x27;: &#x27;Application&#x27;, &#x27;Value&#x27;: &#x27;myapp&#x27;}
]
)
print(f&quot;Created secret: {response[&#x27;ARN&#x27;]}&quot;)
return response[&#x27;ARN&#x27;]
def get_database_secret():
&quot;&quot;&quot;Retrieve database credentials&quot;&quot;&quot;
response = secrets.get_secret_value(
SecretId=&#x27;myapp/database/credentials&#x27;
)
secret_data = json.loads(response[&#x27;SecretString&#x27;])
return {
&#x27;username&#x27;: secret_data[&#x27;username&#x27;],
&#x27;password&#x27;: secret_data[&#x27;password&#x27;],
&#x27;host&#x27;: secret_data[&#x27;host&#x27;],
&#x27;database&#x27;: secret_data[&#x27;database&#x27;],
&#x27;port&#x27;: secret_data[&#x27;port&#x27;]
}
def rotate_secret(secret_id, lambda_arn):
&quot;&quot;&quot;Configure automatic rotation&quot;&quot;&quot;
secrets.rotate_secret(
SecretId=secret_id,
RotationLambdaARN=lambda_arn,
RotationRules={
&#x27;AutomaticallyAfterDays&#x27;: 30
}
)
print(f&quot;Configured rotation for {secret_id}&quot;)</code></pre>
<h3>Concept 4: KMS Encryption</h3>
<p><strong>KMS key types</strong>:</p>
<ul><li><strong>AWS managed</strong>: Created by AWS services (free)</li><li><strong>Customer managed</strong>: Full control, custom policies</li><li><strong>Symmetric</strong>: Same key for encrypt/decrypt</li><li><strong>Asymmetric</strong>: Public/private key pair</li></ul>
<pre><code class="lang-python">import boto3
import base64
kms = boto3.client(&#x27;kms&#x27;)
def create_kms_key():
&quot;&quot;&quot;Create customer-managed KMS key&quot;&quot;&quot;
response = kms.create_key(
Description=&#x27;Application data encryption key&#x27;,
KeyUsage=&#x27;ENCRYPT_DECRYPT&#x27;,
Origin=&#x27;AWS_KMS&#x27;,
MultiRegion=False,
Tags=[
{&#x27;TagKey&#x27;: &#x27;Application&#x27;, &#x27;TagValue&#x27;: &#x27;myapp&#x27;},
{&#x27;TagKey&#x27;: &#x27;Purpose&#x27;, &#x27;TagValue&#x27;: &#x27;data-encryption&#x27;}
]
)
key_id = response[&#x27;KeyMetadata&#x27;][&#x27;KeyId&#x27;]
# Create alias
kms.create_alias(
AliasName=&#x27;alias/myapp-data-key&#x27;,
TargetKeyId=key_id
)
print(f&quot;Created KMS key: {key_id}&quot;)
return key_id
def encrypt_data(plaintext, key_id):
&quot;&quot;&quot;Encrypt data with KMS key&quot;&quot;&quot;
response = kms.encrypt(
KeyId=key_id,
Plaintext=plaintext.encode(&#x27;utf-8&#x27;)
)
# Return base64-encoded ciphertext
ciphertext_blob = response[&#x27;CiphertextBlob&#x27;]
encrypted = base64.b64encode(ciphertext_blob).decode(&#x27;utf-8&#x27;)
return encrypted
def decrypt_data(encrypted_data):
&quot;&quot;&quot;Decrypt data (KMS determines key automatically)&quot;&quot;&quot;
# Decode base64
ciphertext_blob = base64.b64decode(encrypted_data)
response = kms.decrypt(
CiphertextBlob=ciphertext_blob
)
plaintext = response[&#x27;Plaintext&#x27;].decode(&#x27;utf-8&#x27;)
return plaintext
def envelope_encryption(plaintext, key_id):
&quot;&quot;&quot;Encrypt large data using envelope encryption&quot;&quot;&quot;
# Generate data key
response = kms.generate_data_key(
KeyId=key_id,
KeySpec=&#x27;AES_256&#x27;
)
plaintext_key = response[&#x27;Plaintext&#x27;]
encrypted_key = response[&#x27;CiphertextBlob&#x27;]
# Encrypt data with plaintext key (client-side)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
iv = os.urandom(16)
cipher = Cipher(
algorithms.AES(plaintext_key),
modes.CBC(iv),
backend=default_backend()
)
encryptor = cipher.encryptor()
# Pad plaintext to block size
padded = plaintext + &#x27; &#x27; * (16 - len(plaintext) % 16)
ciphertext = encryptor.update(padded.encode()) + encryptor.finalize()
return {
&#x27;encrypted_data&#x27;: base64.b64encode(ciphertext).decode(),
&#x27;encrypted_key&#x27;: base64.b64encode(encrypted_key).decode(),
&#x27;iv&#x27;: base64.b64encode(iv).decode()
}</code></pre>
<hr>
<h2>Patterns</h2>
<h3>Pattern 1: Cross-Account Access with STS</h3>
<p><strong>When to use</strong>: Grant temporary access to resources in another account</p>
<pre><code class="lang-python">import boto3
sts = boto3.client(&#x27;sts&#x27;)
def assume_role(role_arn, session_name):
&quot;&quot;&quot;Assume role in another account&quot;&quot;&quot;
response = sts.assume_role(
RoleArn=role_arn,
RoleSessionName=session_name,
DurationSeconds=3600 # 1 hour
)
credentials = response[&#x27;Credentials&#x27;]
# Create client with assumed role credentials
s3_client = boto3.client(
&#x27;s3&#x27;,
aws_access_key_id=credentials[&#x27;AccessKeyId&#x27;],
aws_secret_access_key=credentials[&#x27;SecretAccessKey&#x27;],
aws_session_token=credentials[&#x27;SessionToken&#x27;]
)
return s3_client
# Trust policy for cross-account role
cross_account_trust_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Principal&quot;: {
&quot;AWS&quot;: &quot;arn:aws:iam::123456789012:root&quot; # Trusting account
},
&quot;Action&quot;: &quot;sts:AssumeRole&quot;,
&quot;Condition&quot;: {
&quot;StringEquals&quot;: {
&quot;sts:ExternalId&quot;: &quot;unique-external-id&quot;
}
}
}
]
}</code></pre>
<h3>Pattern 2: Service-to-Service Authentication</h3>
<p><strong>Use case</strong>: EC2 instance accessing S3 without credentials</p>
<pre><code class="lang-python"># No credentials needed - use IAM instance profile
def create_ec2_instance_profile():
&quot;&quot;&quot;Create instance profile for EC2&quot;&quot;&quot;
# Create role
trust_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Principal&quot;: {&quot;Service&quot;: &quot;ec2.amazonaws.com&quot;},
&quot;Action&quot;: &quot;sts:AssumeRole&quot;
}
]
}
role_response = iam.create_role(
RoleName=&#x27;ec2-s3-access-role&#x27;,
AssumeRolePolicyDocument=json.dumps(trust_policy)
)
# Attach S3 read policy
iam.attach_role_policy(
RoleName=&#x27;ec2-s3-access-role&#x27;,
PolicyArn=&#x27;arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess&#x27;
)
# Create instance profile
iam.create_instance_profile(
InstanceProfileName=&#x27;ec2-s3-profile&#x27;
)
# Add role to profile
iam.add_role_to_instance_profile(
InstanceProfileName=&#x27;ec2-s3-profile&#x27;,
RoleName=&#x27;ec2-s3-access-role&#x27;
)
print(&quot;Created instance profile: ec2-s3-profile&quot;)
# EC2 instance code - no credentials needed
s3 = boto3.client(&#x27;s3&#x27;) # Automatically uses instance profile
buckets = s3.list_buckets()</code></pre>
<h3>Pattern 3: Multi-Factor Authentication (MFA)</h3>
<p><strong>Use case</strong>: Require MFA for sensitive operations</p>
<pre><code class="lang-python">def enforce_mfa_policy():
&quot;&quot;&quot;Create policy requiring MFA for sensitive actions&quot;&quot;&quot;
mfa_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Sid&quot;: &quot;AllowAllActionsWithMFA&quot;,
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: &quot;*&quot;,
&quot;Resource&quot;: &quot;*&quot;,
&quot;Condition&quot;: {
&quot;BoolIfExists&quot;: {
&quot;aws:MultiFactorAuthPresent&quot;: &quot;true&quot;
}
}
},
{
&quot;Sid&quot;: &quot;DenyAllActionsWithoutMFA&quot;,
&quot;Effect&quot;: &quot;Deny&quot;,
&quot;Action&quot;: [
&quot;ec2:TerminateInstances&quot;,
&quot;rds:DeleteDBInstance&quot;,
&quot;s3:DeleteBucket&quot;
],
&quot;Resource&quot;: &quot;*&quot;,
&quot;Condition&quot;: {
&quot;BoolIfExists&quot;: {
&quot;aws:MultiFactorAuthPresent&quot;: &quot;false&quot;
}
}
}
]
}
response = iam.create_policy(
PolicyName=&#x27;require-mfa-for-sensitive-ops&#x27;,
PolicyDocument=json.dumps(mfa_policy)
)
return response[&#x27;Policy&#x27;][&#x27;Arn&#x27;]</code></pre>
<h3>Pattern 4: Least Privilege with Permission Boundaries</h3>
<p><strong>Use case</strong>: Limit maximum permissions for developers</p>
<pre><code class="lang-python">def create_developer_role_with_boundary():
&quot;&quot;&quot;Create developer role with permission boundary&quot;&quot;&quot;
# Permission boundary - maximum allowed permissions
boundary_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: [
&quot;s3:*&quot;,
&quot;dynamodb:*&quot;,
&quot;lambda:*&quot;,
&quot;logs:*&quot;,
&quot;cloudwatch:*&quot;
],
&quot;Resource&quot;: &quot;*&quot;
},
{
&quot;Effect&quot;: &quot;Deny&quot;,
&quot;Action&quot;: [
&quot;iam:*&quot;,
&quot;organizations:*&quot;,
&quot;account:*&quot;
],
&quot;Resource&quot;: &quot;*&quot;
}
]
}
# Create boundary policy
boundary_response = iam.create_policy(
PolicyName=&#x27;developer-boundary&#x27;,
PolicyDocument=json.dumps(boundary_policy)
)
# Create developer role with boundary
trust_policy = {
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Principal&quot;: {&quot;AWS&quot;: &quot;arn:aws:iam::123456789012:root&quot;},
&quot;Action&quot;: &quot;sts:AssumeRole&quot;
}
]
}
iam.create_role(
RoleName=&#x27;developer-role&#x27;,
AssumeRolePolicyDocument=json.dumps(trust_policy),
PermissionsBoundary=boundary_response[&#x27;Policy&#x27;][&#x27;Arn&#x27;]
)
# Developer can only create resources within boundary limits
print(&quot;Created developer role with permission boundary&quot;)</code></pre>
<hr>
<h2>Quick Reference</h2>
<h3>IAM Policy Structure</h3>
<pre><code class="lang-json">{
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
{
&quot;Sid&quot;: &quot;DescriptiveStatementId&quot;,
&quot;Effect&quot;: &quot;Allow&quot;, // or &quot;Deny&quot;
&quot;Principal&quot;: {&quot;AWS&quot;: &quot;arn:aws:iam::123456789012:user/Alice&quot;},
&quot;Action&quot;: [&quot;s3:GetObject&quot;, &quot;s3:PutObject&quot;],
&quot;Resource&quot;: &quot;arn:aws:s3:::my-bucket/*&quot;,
&quot;Condition&quot;: {
&quot;IpAddress&quot;: {&quot;aws:SourceIp&quot;: &quot;192.0.2.0/24&quot;}
}
}
]
}</code></pre>
<h3>Common IAM Actions</h3>
<pre><code>Service | Common Actions
-----------|----------------------------------
S3 | s3:GetObject, s3:PutObject, s3:DeleteObject
DynamoDB | dynamodb:GetItem, dynamodb:PutItem, dynamodb:Query
Lambda | lambda:InvokeFunction, lambda:UpdateFunctionCode
EC2 | ec2:RunInstances, ec2:TerminateInstances
RDS | rds:CreateDBInstance, rds:DeleteDBInstance</code></pre>
<h3>Key Guidelines</h3>
<pre><code>✅ DO: Follow principle of least privilege
✅ DO: Use IAM roles instead of access keys
✅ DO: Enable MFA for privileged users
✅ DO: Rotate credentials regularly
✅ DO: Use Secrets Manager for sensitive data
✅ DO: Encrypt data at rest with KMS
✅ DO: Use resource-based policies when possible
❌ DON&#x27;T: Hardcode credentials in code
❌ DON&#x27;T: Use root account for daily operations
❌ DON&#x27;T: Grant full access (*:*) unless absolutely necessary
❌ DON&#x27;T: Share IAM user credentials
❌ DON&#x27;T: Leave unused access keys active
❌ DON&#x27;T: Disable CloudTrail logging</code></pre>
<hr>
<h2>Anti-Patterns</h2>
<h3>Critical Violations</h3>
<pre><code class="lang-python"># ❌ NEVER: Hardcode credentials
AWS_ACCESS_KEY_ID = &quot;AKIAIOSFODNN7EXAMPLE&quot;
AWS_SECRET_ACCESS_KEY = &quot;wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY&quot;
s3 = boto3.client(
&#x27;s3&#x27;,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
# ✅ CORRECT: Use IAM roles (EC2, Lambda) or environment variables
s3 = boto3.client(&#x27;s3&#x27;) # Automatically uses IAM role
# Or for local development
# Use AWS CLI: aws configure
# Or environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY</code></pre>
<p>❌ <strong>Hardcoded credentials</strong>: Security breach, exposed in code, logs, version control</p>
<p>✅ <strong>Correct approach</strong>: IAM roles for services, AWS CLI config for local, Secrets Manager for apps</p>
<h3>Common Mistakes</h3>
<pre><code class="lang-json">// ❌ Don&#x27;t grant overly broad permissions
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: &quot;*&quot;,
&quot;Resource&quot;: &quot;*&quot;
}
// ✅ Correct: Specific actions and resources
{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Action&quot;: [
&quot;s3:GetObject&quot;,
&quot;s3:PutObject&quot;
],
&quot;Resource&quot;: &quot;arn:aws:s3:::my-bucket/data/*&quot;
}</code></pre>
<p>❌ <strong>Overly broad permissions</strong>: Security risk, violates least privilege</p>
<p>✅ <strong>Better</strong>: Specific actions, specific resources, conditions when appropriate</p>
<hr>
<h2>Related Skills</h2>
<ul><li><code>aws-lambda-functions.md</code> - IAM execution roles for Lambda</li><li><code>aws-ec2-compute.md</code> - IAM instance profiles for EC2</li><li><code>aws-databases.md</code> - IAM database authentication</li><li><code>aws-networking.md</code> - Security groups and network security</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-iam-security.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>